From 66515f87dbe3a4d5e3acab04960e2fa67b546ea3 Mon Sep 17 00:00:00 2001 From: UNV Date: Sat, 11 Oct 2025 11:19:22 +0300 Subject: [PATCH 1/2] Localizing inspections (part 6). --- .../MagicCharacterInspection.java | 101 ++- .../NumericToStringInspection.java | 99 +-- ...mpleDateFormatWithoutLocaleInspection.java | 66 +- .../StringConcatenationInspection.java | 388 +++++----- .../StringEqualsIgnoreCaseInspection.java | 184 +++-- .../StringEqualsInspection.java | 172 +++-- .../StringToUpperWithoutLocaleInspection.java | 130 ++-- .../StringTokenizerInspection.java | 117 +-- .../TimeToStringInspection.java | 101 +-- ...sWithOnlyOneDirectInheritorInspection.java | 59 +- ...nymousInnerClassMayBeStaticInspection.java | 87 +-- .../ArrayLengthInLoopConditionInspection.java | 141 ++-- ...emoryOnLargeArrayAllocationInspection.java | 143 ++-- .../ig/j2me/ConnectionResourceInspection.java | 349 ++++----- ...eWithOnlyOneDirectInheritorInspection.java | 47 +- .../MethodCallInLoopConditionInspection.java | 123 ++-- ...ultiplyOrDivideByPowerOfTwoInspection.java | 311 ++++---- ...gePrimitiveArrayInitializerInspection.java | 99 +-- ...ssBetweenOuterAndInnerClassInspection.java | 409 +++++------ .../j2me/RecordStoreResourceInspection.java | 318 ++++---- .../SimplifiableIfStatementInspection.java | 682 +++++++++--------- .../SingleCharacterStartsWithInspection.java | 199 +++-- .../ClassWithoutConstructorInspection.java | 145 ++-- ...lassWithoutNoArgConstructorInspection.java | 110 +-- .../FieldHasSetterButNoGetterInspection.java | 62 +- .../HtmlTagCanBeJavadocTagInspection.java | 249 ++++--- ...kageDotHtmlMayBePackageInfoInspection.java | 327 ++++----- .../UnnecessaryInheritDocInspection.java | 130 ++-- .../UnnecessaryJavaDocLinkInspection.java | 375 +++++----- .../ig/jdk/AnnotationClassInspection.java | 41 +- .../impl/ig/jdk/AnnotationInspection.java | 42 +- .../impl/ig/jdk/AssertAsNameInspection.java | 136 ++-- .../ig/jdk/AssertStatementInspection.java | 39 +- .../impl/ig/jdk/AutoBoxingInspection.java | 556 +++++++------- .../impl/ig/jdk/AutoUnboxingInspection.java | 676 +++++++++-------- .../impl/ig/jdk/EnumAsNameInspection.java | 136 ++-- .../java/impl/ig/jdk/EnumClassInspection.java | 41 +- .../ig/jdk/ForeachStatementInspection.java | 211 +++--- .../ig/jdk/VarargParameterInspection.java | 227 +++--- ...lsBetweenInconvertibleTypesInspection.java | 8 +- .../AssertsWithoutMessagesInspection.java | 155 ++-- ...lassIsPublicStaticVoidNoArgInspection.java | 17 +- ...IsPublicStaticVoidNoArgInspectionBase.java | 126 ++-- ...oreOrAfterIsPublicVoidNoArgInspection.java | 101 +-- ...ConstantJUnitAssertArgumentInspection.java | 103 ++- ...xpectedExceptionNeverThrownInspection.java | 10 +- .../ig/junit/IgnoredJUnitTestInspection.java | 95 +-- ...tyleTestMethodInJUnit4ClassInspection.java | 174 +++-- ...tatedMethodInJUnit3TestCaseInspection.java | 434 ++++++----- ...ctTestClassNamingConventionInspection.java | 162 +++-- 50 files changed, 4656 insertions(+), 4557 deletions(-) diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/internationalization/MagicCharacterInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/internationalization/MagicCharacterInspection.java index 1ffc286a82..dbe369dfee 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/internationalization/MagicCharacterInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/internationalization/MagicCharacterInspection.java @@ -24,66 +24,63 @@ import com.siyeh.ig.psiutils.ExpressionUtils; import com.siyeh.localize.InspectionGadgetsLocalize; import consulo.annotation.component.ExtensionImpl; +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; @ExtensionImpl public class MagicCharacterInspection extends BaseInspection { + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.magicCharacterDisplayName(); + } - @Override - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.magicCharacterDisplayName().get(); - } - - @Override - @Nonnull - public String buildErrorString(Object... infos) { - return InspectionGadgetsLocalize.magicCharacterProblemDescriptor().get(); - } - - @Override - protected InspectionGadgetsFix buildFix(Object... infos) { - return new IntroduceConstantFix(); - } - - @Override - protected boolean buildQuickFixesOnlyForOnTheFlyErrors() { - return true; - } + @Override + @Nonnull + public String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.magicCharacterProblemDescriptor().get(); + } - @Override - public BaseInspectionVisitor buildVisitor() { - return new CharacterLiteralsShouldBeExplicitlyDeclaredVisitor(); - } + @Override + protected InspectionGadgetsFix buildFix(Object... infos) { + return new IntroduceConstantFix(); + } - private static class CharacterLiteralsShouldBeExplicitlyDeclaredVisitor - extends BaseInspectionVisitor { + @Override + protected boolean buildQuickFixesOnlyForOnTheFlyErrors() { + return true; + } @Override - public void visitLiteralExpression( - @Nonnull PsiLiteralExpression expression) { - super.visitLiteralExpression(expression); - final PsiType type = expression.getType(); - if (type == null) { - return; - } - if (!type.equals(PsiType.CHAR)) { - return; - } - final String text = expression.getText(); - if (text == null) { - return; - } - if (text.equals(" ")) { - return; - } - if (ExpressionUtils.isDeclaredConstant(expression)) { - return; - } - if (NonNlsUtils.isNonNlsAnnotatedUse(expression)) { - return; - } - registerError(expression); + public BaseInspectionVisitor buildVisitor() { + return new CharacterLiteralsShouldBeExplicitlyDeclaredVisitor(); + } + + private static class CharacterLiteralsShouldBeExplicitlyDeclaredVisitor extends BaseInspectionVisitor { + @Override + public void visitLiteralExpression(@Nonnull PsiLiteralExpression expression) { + super.visitLiteralExpression(expression); + final PsiType type = expression.getType(); + if (type == null) { + return; + } + if (!type.equals(PsiType.CHAR)) { + return; + } + final String text = expression.getText(); + if (text == null) { + return; + } + if (text.equals(" ")) { + return; + } + if (ExpressionUtils.isDeclaredConstant(expression)) { + return; + } + if (NonNlsUtils.isNonNlsAnnotatedUse(expression)) { + return; + } + registerError(expression); + } } - } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/internationalization/NumericToStringInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/internationalization/NumericToStringInspection.java index f5df77e41b..619054900f 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/internationalization/NumericToStringInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/internationalization/NumericToStringInspection.java @@ -22,62 +22,63 @@ import com.siyeh.ig.BaseInspectionVisitor; import com.siyeh.localize.InspectionGadgetsLocalize; import consulo.annotation.component.ExtensionImpl; +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; +import org.intellij.lang.annotations.Pattern; @ExtensionImpl public class NumericToStringInspection extends BaseInspection { + @Nonnull + @Override + @Pattern(VALID_ID_PATTERN) + public String getID() { + return "CallToNumericToString"; + } - @Nonnull - public String getID() { - return "CallToNumericToString"; - } - - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.callToNumericTostringDisplayName().get(); - } - - @Nonnull - public String buildErrorString(Object... infos) { - return InspectionGadgetsLocalize.callToNumericTostringProblemDescriptor().get(); - } + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.callToNumericTostringDisplayName(); + } - public BaseInspectionVisitor buildVisitor() { - return new NumericToStringVisitor(); - } + @Nonnull + public String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.callToNumericTostringProblemDescriptor().get(); + } - private static class NumericToStringVisitor extends BaseInspectionVisitor { + public BaseInspectionVisitor buildVisitor() { + return new NumericToStringVisitor(); + } - @Override - public void visitMethodCallExpression( - @Nonnull PsiMethodCallExpression expression) { - super.visitMethodCallExpression(expression); - final PsiReferenceExpression methodExpression = - expression.getMethodExpression(); - final String methodName = methodExpression.getReferenceName(); - if (!HardcodedMethodConstants.TO_STRING.equals(methodName)) { - return; - } - final PsiMethod method = expression.resolveMethod(); - if (method == null) { - return; - } - final PsiParameterList parameterList = method.getParameterList(); - if (parameterList.getParametersCount() != 0) { - return; - } - final PsiClass aClass = method.getContainingClass(); - if (aClass == null) { - return; - } - final String className = aClass.getQualifiedName(); - if (!TypeConversionUtil.isPrimitiveWrapper(className)) { - return; - } - if (NonNlsUtils.isNonNlsAnnotatedUse(expression)) { - return; - } - registerMethodCallError(expression); + private static class NumericToStringVisitor extends BaseInspectionVisitor { + @Override + public void visitMethodCallExpression(@Nonnull PsiMethodCallExpression expression) { + super.visitMethodCallExpression(expression); + final PsiReferenceExpression methodExpression = expression.getMethodExpression(); + final String methodName = methodExpression.getReferenceName(); + if (!HardcodedMethodConstants.TO_STRING.equals(methodName)) { + return; + } + final PsiMethod method = expression.resolveMethod(); + if (method == null) { + return; + } + final PsiParameterList parameterList = method.getParameterList(); + if (parameterList.getParametersCount() != 0) { + return; + } + final PsiClass aClass = method.getContainingClass(); + if (aClass == null) { + return; + } + final String className = aClass.getQualifiedName(); + if (!TypeConversionUtil.isPrimitiveWrapper(className)) { + return; + } + if (NonNlsUtils.isNonNlsAnnotatedUse(expression)) { + return; + } + registerMethodCallError(expression); + } } - } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/internationalization/SimpleDateFormatWithoutLocaleInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/internationalization/SimpleDateFormatWithoutLocaleInspection.java index 052f48cab5..07a711ae41 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/internationalization/SimpleDateFormatWithoutLocaleInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/internationalization/SimpleDateFormatWithoutLocaleInspection.java @@ -23,47 +23,47 @@ import com.siyeh.ig.psiutils.ExpressionUtils; import com.siyeh.localize.InspectionGadgetsLocalize; import consulo.annotation.component.ExtensionImpl; +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; @ExtensionImpl public class SimpleDateFormatWithoutLocaleInspection extends BaseInspection { + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.instantiatingSimpledateformatWithoutLocaleDisplayName(); + } - @Override - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.instantiatingSimpledateformatWithoutLocaleDisplayName().get(); - } - - @Override - @Nonnull - public String buildErrorString(Object... infos) { - return InspectionGadgetsLocalize.instantiatingSimpledateformatWithoutLocaleProblemDescriptor().get(); - } + @Override + @Nonnull + public String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.instantiatingSimpledateformatWithoutLocaleProblemDescriptor().get(); + } - @Override - public BaseInspectionVisitor buildVisitor() { - return new SimpleDateFormatWithoutLocaleVisitor(); - } + @Override + public BaseInspectionVisitor buildVisitor() { + return new SimpleDateFormatWithoutLocaleVisitor(); + } - private static class SimpleDateFormatWithoutLocaleVisitor extends BaseInspectionVisitor { + private static class SimpleDateFormatWithoutLocaleVisitor extends BaseInspectionVisitor { - @Override - public void visitNewExpression(@Nonnull PsiNewExpression expression) { - super.visitNewExpression(expression); - if (!ExpressionUtils.hasType(expression, "java.text.SimpleDateFormat")) { - return; - } - final PsiExpressionList argumentList = expression.getArgumentList(); - if (argumentList == null) { - return; - } - final PsiExpression[] arguments = argumentList.getExpressions(); - for (PsiExpression argument : arguments) { - if (ExpressionUtils.hasType(argument, "java.util.Locale")) { - return; + @Override + public void visitNewExpression(@Nonnull PsiNewExpression expression) { + super.visitNewExpression(expression); + if (!ExpressionUtils.hasType(expression, "java.text.SimpleDateFormat")) { + return; + } + final PsiExpressionList argumentList = expression.getArgumentList(); + if (argumentList == null) { + return; + } + final PsiExpression[] arguments = argumentList.getExpressions(); + for (PsiExpression argument : arguments) { + if (ExpressionUtils.hasType(argument, "java.util.Locale")) { + return; + } + } + registerError(expression); } - } - registerError(expression); } - } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/internationalization/StringConcatenationInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/internationalization/StringConcatenationInspection.java index 62953a90b8..e279cf102e 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/internationalization/StringConcatenationInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/internationalization/StringConcatenationInspection.java @@ -35,6 +35,7 @@ import consulo.language.ast.IElementType; import consulo.language.psi.PsiElement; import consulo.language.psi.util.PsiTreeUtil; +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; import org.jetbrains.annotations.NonNls; @@ -45,215 +46,220 @@ @ExtensionImpl public class StringConcatenationInspection extends BaseInspection { + @SuppressWarnings({"PublicField"}) + public boolean ignoreAsserts = false; - @SuppressWarnings({"PublicField"}) - public boolean ignoreAsserts = false; + @SuppressWarnings({"PublicField"}) + public boolean ignoreSystemOuts = false; - @SuppressWarnings({"PublicField"}) - public boolean ignoreSystemOuts = false; + @SuppressWarnings({"PublicField"}) + public boolean ignoreSystemErrs = false; - @SuppressWarnings({"PublicField"}) - public boolean ignoreSystemErrs = false; + @SuppressWarnings({"PublicField"}) + public boolean ignoreThrowableArguments = false; - @SuppressWarnings({"PublicField"}) - public boolean ignoreThrowableArguments = false; + @SuppressWarnings({"PublicField"}) + public boolean ignoreConstantInitializers = false; - @SuppressWarnings({"PublicField"}) - public boolean ignoreConstantInitializers = false; + @SuppressWarnings({"PublicField"}) + public boolean ignoreInTestCode = false; - @SuppressWarnings({"PublicField"}) - public boolean ignoreInTestCode = false; + @SuppressWarnings("PublicField") + public boolean ignoreInToString = false; - @SuppressWarnings("PublicField") - public boolean ignoreInToString = false; - - @Override - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.stringConcatenationDisplayName().get(); - } - - @Override - @Nonnull - public String buildErrorString(Object... infos) { - return InspectionGadgetsLocalize.stringConcatenationProblemDescriptor().get(); - } - - @Override - @Nonnull - protected InspectionGadgetsFix[] buildFixes(Object... infos) { - final PsiPolyadicExpression polyadicExpression = (PsiPolyadicExpression)infos[0]; - final Collection result = new ArrayList(); - final PsiElement parent = polyadicExpression.getParent(); - if (parent instanceof PsiVariable) { - final PsiVariable variable = (PsiVariable)parent; - final InspectionGadgetsFix fix = new DelegatingFix(new AddAnnotationFix(AnnotationUtil.NON_NLS, variable)); - result.add(fix); - } - else if (parent instanceof PsiAssignmentExpression) { - final PsiAssignmentExpression assignmentExpression = (PsiAssignmentExpression)parent; - final PsiExpression lhs = assignmentExpression.getLExpression(); - if (lhs instanceof PsiReferenceExpression) { - final PsiReferenceExpression referenceExpression = (PsiReferenceExpression)lhs; - final PsiElement target = referenceExpression.resolve(); - if (target instanceof PsiModifierListOwner) { - final PsiModifierListOwner modifierListOwner = (PsiModifierListOwner)target; - final InspectionGadgetsFix fix = new DelegatingFix(new AddAnnotationFix(AnnotationUtil.NON_NLS, modifierListOwner)); - result.add(fix); - } - } - } - final PsiExpression[] operands = polyadicExpression.getOperands(); - for (PsiExpression operand : operands) { - final PsiModifierListOwner element1 = getAnnotatableElement(operand); - if (element1 != null) { - final InspectionGadgetsFix fix = new DelegatingFix(new AddAnnotationFix(AnnotationUtil.NON_NLS, element1)); - result.add(fix); - } - } - final PsiElement expressionParent = PsiTreeUtil.getParentOfType(polyadicExpression, PsiReturnStatement.class, PsiExpressionList.class); - if (!(expressionParent instanceof PsiExpressionList) && expressionParent != null) { - final PsiMethod method = PsiTreeUtil.getParentOfType(expressionParent, PsiMethod.class); - if (method != null) { - final InspectionGadgetsFix fix = new DelegatingFix(new AddAnnotationFix(AnnotationUtil.NON_NLS, method)); - result.add(fix); - } + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.stringConcatenationDisplayName(); } - return result.toArray(new InspectionGadgetsFix[result.size()]); - } - @Nullable - public static PsiModifierListOwner getAnnotatableElement(PsiExpression expression) { - if (!(expression instanceof PsiReferenceExpression)) { - return null; - } - final PsiReferenceExpression referenceExpression = (PsiReferenceExpression)expression; - final PsiElement element = referenceExpression.resolve(); - if (!(element instanceof PsiModifierListOwner)) { - return null; + @Override + @Nonnull + public String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.stringConcatenationProblemDescriptor().get(); } - return (PsiModifierListOwner)element; - } - - @Override - @Nullable - public JComponent createOptionsPanel() { - final MultipleCheckboxOptionsPanel optionsPanel = new MultipleCheckboxOptionsPanel(this); - optionsPanel.addCheckbox(InspectionGadgetsBundle.message("string.concatenation.ignore.assert.option"), "ignoreAsserts"); - optionsPanel.addCheckbox(InspectionGadgetsBundle.message("string.concatenation.ignore.system.out.option"), "ignoreSystemOuts"); - optionsPanel.addCheckbox(InspectionGadgetsBundle.message("string.concatenation.ignore.system.err.option"), "ignoreSystemErrs"); - optionsPanel.addCheckbox(InspectionGadgetsBundle.message("string.concatenation.ignore.exceptions.option"), "ignoreThrowableArguments"); - optionsPanel.addCheckbox(InspectionGadgetsBundle.message("string.concatenation.ignore.constant.initializers.option"), - "ignoreConstantInitializers"); - optionsPanel.addCheckbox(InspectionGadgetsBundle.message("ignore.in.test.code"), "ignoreInTestCode"); - optionsPanel.addCheckbox(InspectionGadgetsBundle.message("ignore.in.tostring"), "ignoreInToString"); - return optionsPanel; - } - - @Override - public BaseInspectionVisitor buildVisitor() { - return new StringConcatenationVisitor(); - } - - private class StringConcatenationVisitor extends BaseInspectionVisitor { @Override - public void visitPolyadicExpression(@Nonnull PsiPolyadicExpression expression) { - super.visitPolyadicExpression(expression); - final IElementType tokenType = expression.getOperationTokenType(); - if (!JavaTokenType.PLUS.equals(tokenType)) { - return; - } - final PsiType type = expression.getType(); - if (!TypeUtils.isJavaLangString(type)) { - return; - } - final PsiExpression[] operands = expression.getOperands(); - for (PsiExpression operand : operands) { - if (NonNlsUtils.isNonNlsAnnotated(operand)) { - return; + @Nonnull + protected InspectionGadgetsFix[] buildFixes(Object... infos) { + final PsiPolyadicExpression polyadicExpression = (PsiPolyadicExpression) infos[0]; + final Collection result = new ArrayList(); + final PsiElement parent = polyadicExpression.getParent(); + if (parent instanceof PsiVariable) { + final PsiVariable variable = (PsiVariable) parent; + final InspectionGadgetsFix fix = new DelegatingFix(new AddAnnotationFix(AnnotationUtil.NON_NLS, variable)); + result.add(fix); } - } - if (AnnotationUtil.isInsideAnnotation(expression)) { - return; - } - if (ignoreInTestCode && TestUtils.isInTestCode(expression)) { - return; - } - if (ignoreAsserts) { - final PsiAssertStatement assertStatement = - PsiTreeUtil.getParentOfType(expression, PsiAssertStatement.class, true, PsiCodeBlock.class, PsiClass.class); - if (assertStatement != null) { - return; + else if (parent instanceof PsiAssignmentExpression) { + final PsiAssignmentExpression assignmentExpression = (PsiAssignmentExpression) parent; + final PsiExpression lhs = assignmentExpression.getLExpression(); + if (lhs instanceof PsiReferenceExpression) { + final PsiReferenceExpression referenceExpression = (PsiReferenceExpression) lhs; + final PsiElement target = referenceExpression.resolve(); + if (target instanceof PsiModifierListOwner) { + final PsiModifierListOwner modifierListOwner = (PsiModifierListOwner) target; + final InspectionGadgetsFix fix = new DelegatingFix(new AddAnnotationFix(AnnotationUtil.NON_NLS, modifierListOwner)); + result.add(fix); + } + } } - } - if (ignoreSystemErrs || ignoreSystemOuts) { - final PsiMethodCallExpression methodCallExpression = - PsiTreeUtil.getParentOfType(expression, PsiMethodCallExpression.class, true, PsiCodeBlock.class, PsiClass.class); - if (methodCallExpression != null) { - final PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression(); - @NonNls - final String canonicalText = methodExpression.getCanonicalText(); - if (ignoreSystemOuts && "System.out.println".equals(canonicalText) || "System.out.print".equals(canonicalText)) { - return; - } - if (ignoreSystemErrs && "System.err.println".equals(canonicalText) || "System.err.print".equals(canonicalText)) { - return; - } + final PsiExpression[] operands = polyadicExpression.getOperands(); + for (PsiExpression operand : operands) { + final PsiModifierListOwner element1 = getAnnotatableElement(operand); + if (element1 != null) { + final InspectionGadgetsFix fix = new DelegatingFix(new AddAnnotationFix(AnnotationUtil.NON_NLS, element1)); + result.add(fix); + } } - } - if (ignoreThrowableArguments) { - final PsiNewExpression newExpression = - PsiTreeUtil.getParentOfType(expression, PsiNewExpression.class, true, PsiCodeBlock.class, PsiClass.class); - if (newExpression != null) { - final PsiType newExpressionType = newExpression.getType(); - if (InheritanceUtil.isInheritor(newExpressionType, CommonClassNames.JAVA_LANG_THROWABLE)) { - return; - } - } else { - final PsiMethodCallExpression methodCallExpression = - PsiTreeUtil.getParentOfType(expression, PsiMethodCallExpression.class, true, PsiCodeBlock.class, PsiClass.class); - if (RefactoringChangeUtil.isSuperOrThisMethodCall(methodCallExpression)) { - return; - } + final PsiElement expressionParent = + PsiTreeUtil.getParentOfType(polyadicExpression, PsiReturnStatement.class, PsiExpressionList.class); + if (!(expressionParent instanceof PsiExpressionList) && expressionParent != null) { + final PsiMethod method = PsiTreeUtil.getParentOfType(expressionParent, PsiMethod.class); + if (method != null) { + final InspectionGadgetsFix fix = new DelegatingFix(new AddAnnotationFix(AnnotationUtil.NON_NLS, method)); + result.add(fix); + } } - } - if (ignoreConstantInitializers) { - PsiElement parent = expression.getParent(); - while (parent instanceof PsiBinaryExpression) { - parent = parent.getParent(); - } - if (parent instanceof PsiField) { - final PsiField field = (PsiField)parent; - if (field.hasModifierProperty(PsiModifier.STATIC) && field.hasModifierProperty(PsiModifier.FINAL)) { - return; - } - final PsiClass containingClass = field.getContainingClass(); - if (containingClass != null && containingClass.isInterface()) { - return; - } - } - } - if (ignoreInToString) { - final PsiMethod method = PsiTreeUtil.getParentOfType(expression, PsiMethod.class, true, PsiClass.class); - if (MethodUtils.isToString(method)) { - return; + return result.toArray(new InspectionGadgetsFix[result.size()]); + } + + @Nullable + public static PsiModifierListOwner getAnnotatableElement(PsiExpression expression) { + if (!(expression instanceof PsiReferenceExpression)) { + return null; } - } - if (NonNlsUtils.isNonNlsAnnotatedUse(expression)) { - return; - } - for (int i = 1; i < operands.length; i++) { - final PsiExpression operand = operands[i]; - if (!ExpressionUtils.isStringConcatenationOperand(operand)) { - continue; + final PsiReferenceExpression referenceExpression = (PsiReferenceExpression) expression; + final PsiElement element = referenceExpression.resolve(); + if (!(element instanceof PsiModifierListOwner)) { + return null; } - final PsiJavaToken token = expression.getTokenBeforeOperand(operand); - if (token == null) { - continue; + return (PsiModifierListOwner) element; + } + + @Override + @Nullable + public JComponent createOptionsPanel() { + final MultipleCheckboxOptionsPanel optionsPanel = new MultipleCheckboxOptionsPanel(this); + optionsPanel.addCheckbox(InspectionGadgetsBundle.message("string.concatenation.ignore.assert.option"), "ignoreAsserts"); + optionsPanel.addCheckbox(InspectionGadgetsBundle.message("string.concatenation.ignore.system.out.option"), "ignoreSystemOuts"); + optionsPanel.addCheckbox(InspectionGadgetsBundle.message("string.concatenation.ignore.system.err.option"), "ignoreSystemErrs"); + optionsPanel.addCheckbox( + InspectionGadgetsBundle.message("string.concatenation.ignore.exceptions.option"), + "ignoreThrowableArguments" + ); + optionsPanel.addCheckbox( + InspectionGadgetsBundle.message("string.concatenation.ignore.constant.initializers.option"), + "ignoreConstantInitializers" + ); + optionsPanel.addCheckbox(InspectionGadgetsBundle.message("ignore.in.test.code"), "ignoreInTestCode"); + optionsPanel.addCheckbox(InspectionGadgetsBundle.message("ignore.in.tostring"), "ignoreInToString"); + return optionsPanel; + } + + @Override + public BaseInspectionVisitor buildVisitor() { + return new StringConcatenationVisitor(); + } + + private class StringConcatenationVisitor extends BaseInspectionVisitor { + + @Override + public void visitPolyadicExpression(@Nonnull PsiPolyadicExpression expression) { + super.visitPolyadicExpression(expression); + final IElementType tokenType = expression.getOperationTokenType(); + if (!JavaTokenType.PLUS.equals(tokenType)) { + return; + } + final PsiType type = expression.getType(); + if (!TypeUtils.isJavaLangString(type)) { + return; + } + final PsiExpression[] operands = expression.getOperands(); + for (PsiExpression operand : operands) { + if (NonNlsUtils.isNonNlsAnnotated(operand)) { + return; + } + } + if (AnnotationUtil.isInsideAnnotation(expression)) { + return; + } + if (ignoreInTestCode && TestUtils.isInTestCode(expression)) { + return; + } + if (ignoreAsserts) { + final PsiAssertStatement assertStatement = + PsiTreeUtil.getParentOfType(expression, PsiAssertStatement.class, true, PsiCodeBlock.class, PsiClass.class); + if (assertStatement != null) { + return; + } + } + if (ignoreSystemErrs || ignoreSystemOuts) { + final PsiMethodCallExpression methodCallExpression = + PsiTreeUtil.getParentOfType(expression, PsiMethodCallExpression.class, true, PsiCodeBlock.class, PsiClass.class); + if (methodCallExpression != null) { + final PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression(); + @NonNls final String canonicalText = methodExpression.getCanonicalText(); + if (ignoreSystemOuts && "System.out.println".equals(canonicalText) || "System.out.print".equals(canonicalText)) { + return; + } + if (ignoreSystemErrs && "System.err.println".equals(canonicalText) || "System.err.print".equals(canonicalText)) { + return; + } + } + } + if (ignoreThrowableArguments) { + final PsiNewExpression newExpression = + PsiTreeUtil.getParentOfType(expression, PsiNewExpression.class, true, PsiCodeBlock.class, PsiClass.class); + if (newExpression != null) { + final PsiType newExpressionType = newExpression.getType(); + if (InheritanceUtil.isInheritor(newExpressionType, CommonClassNames.JAVA_LANG_THROWABLE)) { + return; + } + } + else { + final PsiMethodCallExpression methodCallExpression = + PsiTreeUtil.getParentOfType(expression, PsiMethodCallExpression.class, true, PsiCodeBlock.class, PsiClass.class); + if (RefactoringChangeUtil.isSuperOrThisMethodCall(methodCallExpression)) { + return; + } + } + } + if (ignoreConstantInitializers) { + PsiElement parent = expression.getParent(); + while (parent instanceof PsiBinaryExpression) { + parent = parent.getParent(); + } + if (parent instanceof PsiField) { + final PsiField field = (PsiField) parent; + if (field.hasModifierProperty(PsiModifier.STATIC) && field.hasModifierProperty(PsiModifier.FINAL)) { + return; + } + final PsiClass containingClass = field.getContainingClass(); + if (containingClass != null && containingClass.isInterface()) { + return; + } + } + } + if (ignoreInToString) { + final PsiMethod method = PsiTreeUtil.getParentOfType(expression, PsiMethod.class, true, PsiClass.class); + if (MethodUtils.isToString(method)) { + return; + } + } + if (NonNlsUtils.isNonNlsAnnotatedUse(expression)) { + return; + } + for (int i = 1; i < operands.length; i++) { + final PsiExpression operand = operands[i]; + if (!ExpressionUtils.isStringConcatenationOperand(operand)) { + continue; + } + final PsiJavaToken token = expression.getTokenBeforeOperand(operand); + if (token == null) { + continue; + } + registerError(token, expression); + } } - registerError(token, expression); - } } - } } diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/internationalization/StringEqualsIgnoreCaseInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/internationalization/StringEqualsIgnoreCaseInspection.java index a7ca5b5926..73a592e883 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/internationalization/StringEqualsIgnoreCaseInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/internationalization/StringEqualsIgnoreCaseInspection.java @@ -25,117 +25,105 @@ import com.siyeh.ig.BaseInspectionVisitor; import com.siyeh.ig.InspectionGadgetsFix; import com.siyeh.ig.psiutils.TypeUtils; +import com.siyeh.localize.InspectionGadgetsLocalize; import consulo.annotation.component.ExtensionImpl; +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; +import org.intellij.lang.annotations.Pattern; import java.util.ArrayList; import java.util.List; @ExtensionImpl public class StringEqualsIgnoreCaseInspection extends BaseInspection { - - @Override - @Nonnull - public String getID() { - return "CallToStringEqualsIgnoreCase"; - } - - @Override - @Nonnull - public String getDisplayName() { - return InspectionGadgetsBundle.message( - "string.equalsignorecase.call.display.name"); - } - - @Override - @Nonnull - public String buildErrorString(Object... infos) { - return InspectionGadgetsBundle.message( - "string.equalsignorecase.call.problem.descriptor"); - } - - @Override - @Nonnull - protected InspectionGadgetsFix[] buildFixes(Object... infos) { - final PsiMethodCallExpression methodCallExpression = - (PsiMethodCallExpression)infos[0]; - final List result = new ArrayList(); - final PsiReferenceExpression methodExpression = - methodCallExpression.getMethodExpression(); - final PsiModifierListOwner annotatableQualifier = - NonNlsUtils.getAnnotatableQualifier(methodExpression); - if (annotatableQualifier != null) { - final InspectionGadgetsFix fix = - new DelegatingFix(new AddAnnotationFix( - AnnotationUtil.NON_NLS, annotatableQualifier)); - result.add(fix); + @Nonnull + @Override + @Pattern(VALID_ID_PATTERN) + public String getID() { + return "CallToStringEqualsIgnoreCase"; } - final PsiModifierListOwner annotatableArgument = - NonNlsUtils.getAnnotatableArgument( - methodCallExpression); - if (annotatableArgument != null) { - final InspectionGadgetsFix fix = - new DelegatingFix(new AddAnnotationFix( - AnnotationUtil.NON_NLS, annotatableArgument)); - result.add(fix); + + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.stringEqualsignorecaseCallDisplayName(); } - return result.toArray(new InspectionGadgetsFix[result.size()]); - } - @Override - public BaseInspectionVisitor buildVisitor() { - return new StringEqualsIgnoreCaseVisitor(); - } + @Override + @Nonnull + public String buildErrorString(Object... infos) { + return InspectionGadgetsBundle.message( + "string.equalsignorecase.call.problem.descriptor"); + } - private static class StringEqualsIgnoreCaseVisitor - extends BaseInspectionVisitor { + @Override + @Nonnull + protected InspectionGadgetsFix[] buildFixes(Object... infos) { + final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression) infos[0]; + final List result = new ArrayList(); + final PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression(); + final PsiModifierListOwner annotatableQualifier = NonNlsUtils.getAnnotatableQualifier(methodExpression); + if (annotatableQualifier != null) { + final InspectionGadgetsFix fix = new DelegatingFix(new AddAnnotationFix(AnnotationUtil.NON_NLS, annotatableQualifier)); + result.add(fix); + } + final PsiModifierListOwner annotatableArgument = NonNlsUtils.getAnnotatableArgument(methodCallExpression); + if (annotatableArgument != null) { + final InspectionGadgetsFix fix = new DelegatingFix(new AddAnnotationFix(AnnotationUtil.NON_NLS, annotatableArgument)); + result.add(fix); + } + return result.toArray(new InspectionGadgetsFix[result.size()]); + } @Override - public void visitMethodCallExpression( - @Nonnull PsiMethodCallExpression expression) { - super.visitMethodCallExpression(expression); - final PsiReferenceExpression methodExpression = - expression.getMethodExpression(); - final String methodName = methodExpression.getReferenceName(); - if (!HardcodedMethodConstants.EQUALS_IGNORE_CASE.equals( - methodName)) { - return; - } - final PsiMethod method = expression.resolveMethod(); - if (method == null) { - return; - } - final PsiParameterList parameterList = method.getParameterList(); - if (parameterList.getParametersCount() != 1) { - return; - } - final PsiParameter[] parameters = parameterList.getParameters(); - final PsiType parameterType = parameters[0].getType(); - if (!TypeUtils.isJavaLangString(parameterType)) { - return; - } - final PsiClass aClass = method.getContainingClass(); - if (aClass == null) { - return; - } - final String className = aClass.getQualifiedName(); - if (!CommonClassNames.JAVA_LANG_STRING.equals(className)) { - return; - } - final PsiExpression qualifier = - methodExpression.getQualifierExpression(); - if (NonNlsUtils.isNonNlsAnnotated(qualifier)) { - return; - } - final PsiExpressionList argumentList = expression.getArgumentList(); - final PsiExpression[] arguments = argumentList.getExpressions(); - if (arguments.length != 1) { - return; - } - if (NonNlsUtils.isNonNlsAnnotated(arguments[0])) { - return; - } - registerMethodCallError(expression, expression); + public BaseInspectionVisitor buildVisitor() { + return new StringEqualsIgnoreCaseVisitor(); + } + + private static class StringEqualsIgnoreCaseVisitor extends BaseInspectionVisitor { + @Override + public void visitMethodCallExpression(@Nonnull PsiMethodCallExpression expression) { + super.visitMethodCallExpression(expression); + final PsiReferenceExpression methodExpression = expression.getMethodExpression(); + final String methodName = methodExpression.getReferenceName(); + if (!HardcodedMethodConstants.EQUALS_IGNORE_CASE.equals(methodName)) { + return; + } + final PsiMethod method = expression.resolveMethod(); + if (method == null) { + return; + } + final PsiParameterList parameterList = method.getParameterList(); + if (parameterList.getParametersCount() != 1) { + return; + } + final PsiParameter[] parameters = parameterList.getParameters(); + final PsiType parameterType = parameters[0].getType(); + if (!TypeUtils.isJavaLangString(parameterType)) { + return; + } + final PsiClass aClass = method.getContainingClass(); + if (aClass == null) { + return; + } + final String className = aClass.getQualifiedName(); + if (!CommonClassNames.JAVA_LANG_STRING.equals(className)) { + return; + } + final PsiExpression qualifier = + methodExpression.getQualifierExpression(); + if (NonNlsUtils.isNonNlsAnnotated(qualifier)) { + return; + } + final PsiExpressionList argumentList = expression.getArgumentList(); + final PsiExpression[] arguments = argumentList.getExpressions(); + if (arguments.length != 1) { + return; + } + if (NonNlsUtils.isNonNlsAnnotated(arguments[0])) { + return; + } + registerMethodCallError(expression, expression); + } } - } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/internationalization/StringEqualsInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/internationalization/StringEqualsInspection.java index 7a1cac9fe4..01597bd140 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/internationalization/StringEqualsInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/internationalization/StringEqualsInspection.java @@ -25,110 +25,100 @@ import com.siyeh.ig.InspectionGadgetsFix; import com.siyeh.ig.psiutils.MethodCallUtils; import com.siyeh.ig.psiutils.TypeUtils; +import com.siyeh.localize.InspectionGadgetsLocalize; import consulo.annotation.component.ExtensionImpl; +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; +import org.intellij.lang.annotations.Pattern; import java.util.ArrayList; import java.util.List; @ExtensionImpl public class StringEqualsInspection extends BaseInspection { - - @Override - @Nonnull - public String getID() { - return "CallToStringEquals"; - } - - @Override - @Nonnull - public String getDisplayName() { - return InspectionGadgetsBundle.message( - "string.equals.call.display.name"); - } - - @Override - @Nonnull - public String buildErrorString(Object... infos) { - return InspectionGadgetsBundle.message( - "string.equals.call.problem.descriptor"); - } - - @Override - @Nonnull - protected InspectionGadgetsFix[] buildFixes(Object... infos) { - final PsiMethodCallExpression methodCallExpression = - (PsiMethodCallExpression) infos[0]; - final List result = new ArrayList(); - final PsiReferenceExpression methodExpression = - methodCallExpression.getMethodExpression(); - final PsiModifierListOwner annotatableQualifier = - NonNlsUtils.getAnnotatableQualifier( - methodExpression); - if (annotatableQualifier != null) { - final InspectionGadgetsFix fix = - new DelegatingFix(new AddAnnotationFix( - AnnotationUtil.NON_NLS, annotatableQualifier)); - result.add(fix); + @Nonnull + @Override + @Pattern(VALID_ID_PATTERN) + public String getID() { + return "CallToStringEquals"; } - final PsiModifierListOwner annotatableArgument = - NonNlsUtils.getAnnotatableArgument( - methodCallExpression); - if (annotatableArgument != null) { - final InspectionGadgetsFix fix = - new DelegatingFix(new AddAnnotationFix( - AnnotationUtil.NON_NLS, annotatableArgument)); - result.add(fix); + + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.stringEqualsCallDisplayName(); } - return result.toArray(new InspectionGadgetsFix[result.size()]); - } - @Override - public BaseInspectionVisitor buildVisitor() { - return new StringEqualsVisitor(); - } + @Override + @Nonnull + public String buildErrorString(Object... infos) { + return InspectionGadgetsBundle.message( + "string.equals.call.problem.descriptor"); + } - private static class StringEqualsVisitor extends BaseInspectionVisitor { + @Override + @Nonnull + protected InspectionGadgetsFix[] buildFixes(Object... infos) { + final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression) infos[0]; + final List result = new ArrayList(); + final PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression(); + final PsiModifierListOwner annotatableQualifier = NonNlsUtils.getAnnotatableQualifier(methodExpression); + if (annotatableQualifier != null) { + final InspectionGadgetsFix fix = new DelegatingFix(new AddAnnotationFix(AnnotationUtil.NON_NLS, annotatableQualifier)); + result.add(fix); + } + final PsiModifierListOwner annotatableArgument = NonNlsUtils.getAnnotatableArgument(methodCallExpression); + if (annotatableArgument != null) { + final InspectionGadgetsFix fix = new DelegatingFix(new AddAnnotationFix(AnnotationUtil.NON_NLS, annotatableArgument)); + result.add(fix); + } + return result.toArray(new InspectionGadgetsFix[result.size()]); + } @Override - public void visitMethodCallExpression( - @Nonnull PsiMethodCallExpression expression) { - super.visitMethodCallExpression(expression); - if (!MethodCallUtils.isEqualsCall(expression)) { - return; - } - final PsiMethod method = expression.resolveMethod(); - if (method == null) { - return; - } - final PsiParameterList paramList = method.getParameterList(); - final PsiParameter[] parameters = paramList.getParameters(); - final PsiType parameterType = parameters[0].getType(); - if (!TypeUtils.isJavaLangObject(parameterType)) { - return; - } - final PsiClass aClass = method.getContainingClass(); - if (aClass == null) { - return; - } - final String className = aClass.getQualifiedName(); - if (!CommonClassNames.JAVA_LANG_STRING.equals(className)) { - return; - } - final PsiReferenceExpression methodExpression = expression.getMethodExpression(); - final PsiExpression qualifier = methodExpression.getQualifierExpression(); - if (NonNlsUtils.isNonNlsAnnotated(qualifier)) { - return; - } - final PsiExpressionList argumentList = expression.getArgumentList(); - final PsiExpression[] arguments = argumentList.getExpressions(); - if (arguments.length != 1) { - return; - } - if (NonNlsUtils.isNonNlsAnnotated(arguments[0])) { - return; - } - registerMethodCallError(expression, expression); + public BaseInspectionVisitor buildVisitor() { + return new StringEqualsVisitor(); + } + + private static class StringEqualsVisitor extends BaseInspectionVisitor { + @Override + public void visitMethodCallExpression(@Nonnull PsiMethodCallExpression expression) { + super.visitMethodCallExpression(expression); + if (!MethodCallUtils.isEqualsCall(expression)) { + return; + } + final PsiMethod method = expression.resolveMethod(); + if (method == null) { + return; + } + final PsiParameterList paramList = method.getParameterList(); + final PsiParameter[] parameters = paramList.getParameters(); + final PsiType parameterType = parameters[0].getType(); + if (!TypeUtils.isJavaLangObject(parameterType)) { + return; + } + final PsiClass aClass = method.getContainingClass(); + if (aClass == null) { + return; + } + final String className = aClass.getQualifiedName(); + if (!CommonClassNames.JAVA_LANG_STRING.equals(className)) { + return; + } + final PsiReferenceExpression methodExpression = expression.getMethodExpression(); + final PsiExpression qualifier = methodExpression.getQualifierExpression(); + if (NonNlsUtils.isNonNlsAnnotated(qualifier)) { + return; + } + final PsiExpressionList argumentList = expression.getArgumentList(); + final PsiExpression[] arguments = argumentList.getExpressions(); + if (arguments.length != 1) { + return; + } + if (NonNlsUtils.isNonNlsAnnotated(arguments[0])) { + return; + } + registerMethodCallError(expression, expression); + } } - } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/internationalization/StringToUpperWithoutLocaleInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/internationalization/StringToUpperWithoutLocaleInspection.java index f9f3fe0877..73c2b8d236 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/internationalization/StringToUpperWithoutLocaleInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/internationalization/StringToUpperWithoutLocaleInspection.java @@ -25,80 +25,82 @@ import com.siyeh.ig.InspectionGadgetsFix; import com.siyeh.localize.InspectionGadgetsLocalize; import consulo.annotation.component.ExtensionImpl; +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; +import org.intellij.lang.annotations.Pattern; @ExtensionImpl public class StringToUpperWithoutLocaleInspection extends BaseInspection { + @Nonnull + @Override + @Pattern(VALID_ID_PATTERN) + public String getID() { + return "StringToUpperCaseOrToLowerCaseWithoutLocale"; + } - @Override - @Nonnull - public String getID() { - return "StringToUpperCaseOrToLowerCaseWithoutLocale"; - } - - @Override - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.stringTouppercaseTolowercaseWithoutLocaleDisplayName().get(); - } - - @Override - @Nonnull - public String buildErrorString(Object... infos) { - return InspectionGadgetsLocalize.stringTouppercaseTolowercaseWithoutLocaleProblemDescriptor().get(); - } + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.stringTouppercaseTolowercaseWithoutLocaleDisplayName(); + } - @Override - @Nullable - protected InspectionGadgetsFix buildFix(Object... infos) { - final PsiReferenceExpression methodExpression = (PsiReferenceExpression)infos[0]; - final PsiModifierListOwner annotatableQualifier = NonNlsUtils.getAnnotatableQualifier(methodExpression); - if (annotatableQualifier == null) { - return null; + @Override + @Nonnull + public String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.stringTouppercaseTolowercaseWithoutLocaleProblemDescriptor().get(); } - return new DelegatingFix(new AddAnnotationFix(AnnotationUtil.NON_NLS, annotatableQualifier)); - } - @Override - public BaseInspectionVisitor buildVisitor() { - return new StringToUpperWithoutLocaleVisitor(); - } + @Override + @Nullable + protected InspectionGadgetsFix buildFix(Object... infos) { + final PsiReferenceExpression methodExpression = (PsiReferenceExpression) infos[0]; + final PsiModifierListOwner annotatableQualifier = NonNlsUtils.getAnnotatableQualifier(methodExpression); + if (annotatableQualifier == null) { + return null; + } + return new DelegatingFix(new AddAnnotationFix(AnnotationUtil.NON_NLS, annotatableQualifier)); + } - private static class StringToUpperWithoutLocaleVisitor extends BaseInspectionVisitor { @Override - public void visitMethodCallExpression(@Nonnull PsiMethodCallExpression expression) { - super.visitMethodCallExpression(expression); - final PsiReferenceExpression methodExpression = expression.getMethodExpression(); - final String methodName = methodExpression.getReferenceName(); - if (!HardcodedMethodConstants.TO_UPPER_CASE.equals(methodName) && - !HardcodedMethodConstants.TO_LOWER_CASE.equals(methodName)) { - return; - } - if (NonNlsUtils.isNonNlsAnnotatedUse(expression)) { - return; - } - final PsiMethod method = expression.resolveMethod(); - if (method == null) { - return; - } - final PsiParameterList parameterList = method.getParameterList(); - if (parameterList.getParametersCount() == 1) { - return; - } - final PsiClass containingClass = method.getContainingClass(); - if (containingClass == null) { - return; - } - final String className = containingClass.getQualifiedName(); - if (!CommonClassNames.JAVA_LANG_STRING.equals(className)) { - return; - } - final PsiExpression qualifier = methodExpression.getQualifierExpression(); - if (NonNlsUtils.isNonNlsAnnotated(qualifier)) { - return; - } - registerMethodCallError(expression, methodExpression); + public BaseInspectionVisitor buildVisitor() { + return new StringToUpperWithoutLocaleVisitor(); + } + + private static class StringToUpperWithoutLocaleVisitor extends BaseInspectionVisitor { + @Override + public void visitMethodCallExpression(@Nonnull PsiMethodCallExpression expression) { + super.visitMethodCallExpression(expression); + final PsiReferenceExpression methodExpression = expression.getMethodExpression(); + final String methodName = methodExpression.getReferenceName(); + if (!HardcodedMethodConstants.TO_UPPER_CASE.equals(methodName) && + !HardcodedMethodConstants.TO_LOWER_CASE.equals(methodName)) { + return; + } + if (NonNlsUtils.isNonNlsAnnotatedUse(expression)) { + return; + } + final PsiMethod method = expression.resolveMethod(); + if (method == null) { + return; + } + final PsiParameterList parameterList = method.getParameterList(); + if (parameterList.getParametersCount() == 1) { + return; + } + final PsiClass containingClass = method.getContainingClass(); + if (containingClass == null) { + return; + } + final String className = containingClass.getQualifiedName(); + if (!CommonClassNames.JAVA_LANG_STRING.equals(className)) { + return; + } + final PsiExpression qualifier = methodExpression.getQualifierExpression(); + if (NonNlsUtils.isNonNlsAnnotated(qualifier)) { + return; + } + registerMethodCallError(expression, methodExpression); + } } - } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/internationalization/StringTokenizerInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/internationalization/StringTokenizerInspection.java index ab323a35c0..d92c30bb79 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/internationalization/StringTokenizerInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/internationalization/StringTokenizerInspection.java @@ -21,70 +21,77 @@ import com.siyeh.ig.psiutils.TypeUtils; import com.siyeh.localize.InspectionGadgetsLocalize; import consulo.annotation.component.ExtensionImpl; +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; +import org.intellij.lang.annotations.Pattern; @ExtensionImpl public class StringTokenizerInspection extends BaseInspection { + @Nonnull + @Override + @Pattern(VALID_ID_PATTERN) + public String getID() { + return "UseOfStringTokenizer"; + } - @Nonnull - public String getID() { - return "UseOfStringTokenizer"; - } - - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.useStringtokenizerDisplayName().get(); - } + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.useStringtokenizerDisplayName(); + } - @Nonnull - public String buildErrorString(Object... infos) { - return InspectionGadgetsLocalize.useStringtokenizerProblemDescriptor().get(); - } + @Nonnull + public String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.useStringtokenizerProblemDescriptor().get(); + } - public BaseInspectionVisitor buildVisitor() { - return new StringTokenizerVisitor(); - } + public BaseInspectionVisitor buildVisitor() { + return new StringTokenizerVisitor(); + } - private static class StringTokenizerVisitor extends BaseInspectionVisitor { + private static class StringTokenizerVisitor extends BaseInspectionVisitor { - @Override - public void visitVariable(@Nonnull PsiVariable variable) { - super.visitVariable(variable); - final PsiType type = variable.getType(); - final PsiType deepComponentType = type.getDeepComponentType(); - if (!TypeUtils.typeEquals("java.util.StringTokenizer", - deepComponentType)) { - return; - } - final PsiTypeElement typeElement = variable.getTypeElement(); - if (typeElement == null) { - return; - } - final PsiExpression initializer = variable.getInitializer(); - if (isTokenizingNonNlsAnnotatedElement(initializer)) { - return; - } - registerError(typeElement); - } + @Override + public void visitVariable(@Nonnull PsiVariable variable) { + super.visitVariable(variable); + final PsiType type = variable.getType(); + final PsiType deepComponentType = type.getDeepComponentType(); + if (!TypeUtils.typeEquals( + "java.util.StringTokenizer", + deepComponentType + )) { + return; + } + final PsiTypeElement typeElement = variable.getTypeElement(); + if (typeElement == null) { + return; + } + final PsiExpression initializer = variable.getInitializer(); + if (isTokenizingNonNlsAnnotatedElement(initializer)) { + return; + } + registerError(typeElement); + } - private static boolean isTokenizingNonNlsAnnotatedElement( - PsiExpression initializer) { - if (!(initializer instanceof PsiNewExpression)) { - return false; - } - final PsiNewExpression newExpression = - (PsiNewExpression)initializer; - final PsiExpressionList argumentList = - newExpression.getArgumentList(); - if (argumentList == null) { - return false; - } - final PsiExpression[] expressions = - argumentList.getExpressions(); - if (expressions.length <= 0) { - return false; - } - return NonNlsUtils.isNonNlsAnnotated(expressions[0]); + private static boolean isTokenizingNonNlsAnnotatedElement( + PsiExpression initializer + ) { + if (!(initializer instanceof PsiNewExpression)) { + return false; + } + final PsiNewExpression newExpression = + (PsiNewExpression) initializer; + final PsiExpressionList argumentList = + newExpression.getArgumentList(); + if (argumentList == null) { + return false; + } + final PsiExpression[] expressions = + argumentList.getExpressions(); + if (expressions.length <= 0) { + return false; + } + return NonNlsUtils.isNonNlsAnnotated(expressions[0]); + } } - } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/internationalization/TimeToStringInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/internationalization/TimeToStringInspection.java index 69a554cc37..3e5dc2ad3c 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/internationalization/TimeToStringInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/internationalization/TimeToStringInspection.java @@ -21,62 +21,67 @@ import com.siyeh.ig.BaseInspectionVisitor; import com.siyeh.localize.InspectionGadgetsLocalize; import consulo.annotation.component.ExtensionImpl; +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; +import org.intellij.lang.annotations.Pattern; @ExtensionImpl public class TimeToStringInspection extends BaseInspection { + @Nonnull + @Override + @Pattern(VALID_ID_PATTERN) + public String getID() { + return "CallToTimeToString"; + } - @Nonnull - public String getID() { - return "CallToTimeToString"; - } - - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.timeTostringCallDisplayName().get(); - } + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.timeTostringCallDisplayName(); + } - @Nonnull - public String buildErrorString(Object... infos) { - return InspectionGadgetsLocalize.timeTostringCallProblemDescriptor().get(); - } + @Nonnull + public String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.timeTostringCallProblemDescriptor().get(); + } - public BaseInspectionVisitor buildVisitor() { - return new TimeToStringVisitor(); - } + public BaseInspectionVisitor buildVisitor() { + return new TimeToStringVisitor(); + } - private static class TimeToStringVisitor extends BaseInspectionVisitor { + private static class TimeToStringVisitor extends BaseInspectionVisitor { - @Override - public void visitMethodCallExpression( - @Nonnull PsiMethodCallExpression expression) { - super.visitMethodCallExpression(expression); - final PsiReferenceExpression methodExpression = - expression.getMethodExpression(); - final String methodName = methodExpression.getReferenceName(); - if (!HardcodedMethodConstants.TO_STRING.equals(methodName)) { - return; - } - if (NonNlsUtils.isNonNlsAnnotatedUse(expression)) { - return; - } - final PsiMethod method = expression.resolveMethod(); - if (method == null) { - return; - } - final PsiParameterList parameterList = method.getParameterList(); - if (parameterList.getParametersCount() != 0) { - return; - } - final PsiClass aClass = method.getContainingClass(); - if (aClass == null) { - return; - } - final String className = aClass.getQualifiedName(); - if (!"java.sql.Time".equals(className)) { - return; - } - registerMethodCallError(expression); + @Override + public void visitMethodCallExpression( + @Nonnull PsiMethodCallExpression expression + ) { + super.visitMethodCallExpression(expression); + final PsiReferenceExpression methodExpression = + expression.getMethodExpression(); + final String methodName = methodExpression.getReferenceName(); + if (!HardcodedMethodConstants.TO_STRING.equals(methodName)) { + return; + } + if (NonNlsUtils.isNonNlsAnnotatedUse(expression)) { + return; + } + final PsiMethod method = expression.resolveMethod(); + if (method == null) { + return; + } + final PsiParameterList parameterList = method.getParameterList(); + if (parameterList.getParametersCount() != 0) { + return; + } + final PsiClass aClass = method.getContainingClass(); + if (aClass == null) { + return; + } + final String className = aClass.getQualifiedName(); + if (!"java.sql.Time".equals(className)) { + return; + } + registerMethodCallError(expression); + } } - } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/j2me/AbstractClassWithOnlyOneDirectInheritorInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/j2me/AbstractClassWithOnlyOneDirectInheritorInspection.java index 7841c0b8f9..04e6d48128 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/j2me/AbstractClassWithOnlyOneDirectInheritorInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/j2me/AbstractClassWithOnlyOneDirectInheritorInspection.java @@ -23,42 +23,43 @@ import com.siyeh.ig.BaseInspectionVisitor; import com.siyeh.localize.InspectionGadgetsLocalize; import consulo.annotation.component.ExtensionImpl; +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; @ExtensionImpl public class AbstractClassWithOnlyOneDirectInheritorInspection extends BaseInspection { + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.abstractClassWithOnlyOneDirectInheritorDisplayName(); + } - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.abstractClassWithOnlyOneDirectInheritorDisplayName().get(); - } - - @Nonnull - protected String buildErrorString(Object... infos) { - return InspectionGadgetsLocalize.abstractClassWithOnlyOneDirectInheritorProblemDescriptor().get(); - } + @Nonnull + protected String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.abstractClassWithOnlyOneDirectInheritorProblemDescriptor().get(); + } - public BaseInspectionVisitor buildVisitor() { - return new AbstractClassWithOnlyOneDirectInheritorVisitor(); - } + public BaseInspectionVisitor buildVisitor() { + return new AbstractClassWithOnlyOneDirectInheritorVisitor(); + } - private static class AbstractClassWithOnlyOneDirectInheritorVisitor extends BaseInspectionVisitor { + private static class AbstractClassWithOnlyOneDirectInheritorVisitor extends BaseInspectionVisitor { - @Override - public void visitClass(@Nonnull PsiClass aClass) { - if (aClass.isInterface() || aClass.isAnnotationType() || aClass.isEnum()) { - return; - } - if (aClass instanceof PsiTypeParameter) { - return; - } - if (!aClass.hasModifierProperty(PsiModifier.ABSTRACT)) { - return; - } - if (!InheritanceUtil.hasOneInheritor(aClass)) { - return; - } - registerClassError(aClass); + @Override + public void visitClass(@Nonnull PsiClass aClass) { + if (aClass.isInterface() || aClass.isAnnotationType() || aClass.isEnum()) { + return; + } + if (aClass instanceof PsiTypeParameter) { + return; + } + if (!aClass.hasModifierProperty(PsiModifier.ABSTRACT)) { + return; + } + if (!InheritanceUtil.hasOneInheritor(aClass)) { + return; + } + registerClassError(aClass); + } } - } } diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/j2me/AnonymousInnerClassMayBeStaticInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/j2me/AnonymousInnerClassMayBeStaticInspection.java index 4f4a602bef..061f02349b 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/j2me/AnonymousInnerClassMayBeStaticInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/j2me/AnonymousInnerClassMayBeStaticInspection.java @@ -24,57 +24,58 @@ import com.siyeh.localize.InspectionGadgetsLocalize; import consulo.annotation.component.ExtensionImpl; import consulo.language.psi.util.PsiTreeUtil; +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; @ExtensionImpl public class AnonymousInnerClassMayBeStaticInspection extends BaseInspection { + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.anonymousInnerMayBeNamedStaticInnerClassDisplayName(); + } - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.anonymousInnerMayBeNamedStaticInnerClassDisplayName().get(); - } - - @Nonnull - public String buildErrorString(Object... infos) { - return InspectionGadgetsLocalize.anonymousInnerMayBeNamedStaticInnerClassProblemDescriptor().get(); - } + @Nonnull + public String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.anonymousInnerMayBeNamedStaticInnerClassProblemDescriptor().get(); + } - protected InspectionGadgetsFix buildFix(Object... infos) { - return new MoveAnonymousToInnerClassFix( - InspectionGadgetsLocalize.anonymousInnerMayBeNamedStaticInnerClassQuickfix().get() - ); - } + protected InspectionGadgetsFix buildFix(Object... infos) { + return new MoveAnonymousToInnerClassFix( + InspectionGadgetsLocalize.anonymousInnerMayBeNamedStaticInnerClassQuickfix().get() + ); + } - public BaseInspectionVisitor buildVisitor() { - return new AnonymousInnerClassMayBeStaticVisitor(); - } + public BaseInspectionVisitor buildVisitor() { + return new AnonymousInnerClassMayBeStaticVisitor(); + } - private static class AnonymousInnerClassMayBeStaticVisitor - extends BaseInspectionVisitor { + private static class AnonymousInnerClassMayBeStaticVisitor + extends BaseInspectionVisitor { - @Override - public void visitClass(@Nonnull PsiClass aClass) { - if (!(aClass instanceof PsiAnonymousClass)) { - return; - } - if (aClass instanceof PsiEnumConstantInitializer) { - return; - } - final PsiMember containingMember = - PsiTreeUtil.getParentOfType(aClass, PsiMember.class); - if (containingMember == null || - containingMember.hasModifierProperty(PsiModifier.STATIC)) { - return; - } - final PsiAnonymousClass anAnonymousClass = - (PsiAnonymousClass)aClass; - final InnerClassReferenceVisitor visitor = - new InnerClassReferenceVisitor(anAnonymousClass); - anAnonymousClass.accept(visitor); - if (!visitor.canInnerClassBeStatic()) { - return; - } - registerClassError(aClass); + @Override + public void visitClass(@Nonnull PsiClass aClass) { + if (!(aClass instanceof PsiAnonymousClass)) { + return; + } + if (aClass instanceof PsiEnumConstantInitializer) { + return; + } + final PsiMember containingMember = + PsiTreeUtil.getParentOfType(aClass, PsiMember.class); + if (containingMember == null || + containingMember.hasModifierProperty(PsiModifier.STATIC)) { + return; + } + final PsiAnonymousClass anAnonymousClass = + (PsiAnonymousClass) aClass; + final InnerClassReferenceVisitor visitor = + new InnerClassReferenceVisitor(anAnonymousClass); + anAnonymousClass.accept(visitor); + if (!visitor.canInnerClassBeStatic()) { + return; + } + registerClassError(aClass); + } } - } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/j2me/ArrayLengthInLoopConditionInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/j2me/ArrayLengthInLoopConditionInspection.java index 84afb04caa..65b98c919d 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/j2me/ArrayLengthInLoopConditionInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/j2me/ArrayLengthInLoopConditionInspection.java @@ -23,89 +23,92 @@ import consulo.annotation.component.ExtensionImpl; import consulo.language.psi.PsiElement; import consulo.language.psi.PsiElementVisitor; +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; @ExtensionImpl public class ArrayLengthInLoopConditionInspection extends BaseInspection { - - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.arrayLengthInLoopConditionDisplayName().get(); - } - - @Nonnull - public String buildErrorString(Object... infos) { - return InspectionGadgetsLocalize.arrayLengthInLoopConditionProblemDescriptor().get(); - } - - public BaseInspectionVisitor buildVisitor() { - return new ArrayLengthInLoopConditionVisitor(); - } - - private static class ArrayLengthInLoopConditionVisitor - extends BaseInspectionVisitor { - + @Nonnull @Override - public void visitForStatement(@Nonnull PsiForStatement statement) { - super.visitForStatement(statement); - final PsiExpression condition = statement.getCondition(); - if (condition == null) { - return; - } - checkForMethodCalls(condition); + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.arrayLengthInLoopConditionDisplayName(); } - @Override - public void visitWhileStatement(@Nonnull PsiWhileStatement statement) { - super.visitWhileStatement(statement); - final PsiExpression condition = statement.getCondition(); - if (condition == null) { - return; - } - checkForMethodCalls(condition); + @Nonnull + public String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.arrayLengthInLoopConditionProblemDescriptor().get(); } - @Override - public void visitDoWhileStatement( - @Nonnull PsiDoWhileStatement statement) { - super.visitDoWhileStatement(statement); - final PsiExpression condition = statement.getCondition(); - if (condition == null) { - return; - } - checkForMethodCalls(condition); + public BaseInspectionVisitor buildVisitor() { + return new ArrayLengthInLoopConditionVisitor(); } - private void checkForMethodCalls(PsiExpression condition) { - final PsiElementVisitor visitor = - new JavaRecursiveElementVisitor() { + private static class ArrayLengthInLoopConditionVisitor + extends BaseInspectionVisitor { - @Override - public void visitReferenceExpression( - @Nonnull PsiReferenceExpression expression) { - super.visitReferenceExpression(expression); - final String name = expression.getReferenceName(); - if (!HardcodedMethodConstants.LENGTH.equals(name)) { - return; - } - final PsiExpression qualifier = - expression.getQualifierExpression(); - if (qualifier == null) { - return; + @Override + public void visitForStatement(@Nonnull PsiForStatement statement) { + super.visitForStatement(statement); + final PsiExpression condition = statement.getCondition(); + if (condition == null) { + return; } - final PsiType type = qualifier.getType(); - if (!(type instanceof PsiArrayType)) { - return; + checkForMethodCalls(condition); + } + + @Override + public void visitWhileStatement(@Nonnull PsiWhileStatement statement) { + super.visitWhileStatement(statement); + final PsiExpression condition = statement.getCondition(); + if (condition == null) { + return; } - final PsiElement lengthElement = - expression.getReferenceNameElement(); - if (lengthElement == null) { - return; + checkForMethodCalls(condition); + } + + @Override + public void visitDoWhileStatement( + @Nonnull PsiDoWhileStatement statement + ) { + super.visitDoWhileStatement(statement); + final PsiExpression condition = statement.getCondition(); + if (condition == null) { + return; } - registerError(lengthElement); - } - }; - condition.accept(visitor); + checkForMethodCalls(condition); + } + + private void checkForMethodCalls(PsiExpression condition) { + final PsiElementVisitor visitor = + new JavaRecursiveElementVisitor() { + + @Override + public void visitReferenceExpression( + @Nonnull PsiReferenceExpression expression + ) { + super.visitReferenceExpression(expression); + final String name = expression.getReferenceName(); + if (!HardcodedMethodConstants.LENGTH.equals(name)) { + return; + } + final PsiExpression qualifier = + expression.getQualifierExpression(); + if (qualifier == null) { + return; + } + final PsiType type = qualifier.getType(); + if (!(type instanceof PsiArrayType)) { + return; + } + final PsiElement lengthElement = + expression.getReferenceNameElement(); + if (lengthElement == null) { + return; + } + registerError(lengthElement); + } + }; + condition.accept(visitor); + } } - } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/j2me/CheckForOutOfMemoryOnLargeArrayAllocationInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/j2me/CheckForOutOfMemoryOnLargeArrayAllocationInspection.java index 64483be122..83f54bcbb7 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/j2me/CheckForOutOfMemoryOnLargeArrayAllocationInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/j2me/CheckForOutOfMemoryOnLargeArrayAllocationInspection.java @@ -28,90 +28,83 @@ import javax.swing.*; -public abstract class CheckForOutOfMemoryOnLargeArrayAllocationInspection - extends BaseInspection { +public abstract class CheckForOutOfMemoryOnLargeArrayAllocationInspection extends BaseInspection { + /** + * @noinspection PublicField + */ + public int m_limit = 64; - /** - * @noinspection PublicField - */ - public int m_limit = 64; - - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.largeArrayAllocationNoOutofmemoryerrorDisplayName().get(); - } - - @Nonnull - public String buildErrorString(Object... infos) { - return InspectionGadgetsLocalize.largeArrayAllocationNoOutofmemoryerrorProblemDescriptor().get(); - } - - public JComponent createOptionsPanel() { - LocalizeValue message = InspectionGadgetsLocalize.largeArrayAllocationNoOutofmemoryerrorMaximumNumberOfElementsOption(); - return new SingleIntegerFieldOptionsPanel(message.get(), this, "m_limit"); - } + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.largeArrayAllocationNoOutofmemoryerrorDisplayName(); + } - public BaseInspectionVisitor buildVisitor() { - return new CheckForOutOfMemoryOnLargeArrayAllocationVisitor(); - } + @Nonnull + public String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.largeArrayAllocationNoOutofmemoryerrorProblemDescriptor().get(); + } - private class CheckForOutOfMemoryOnLargeArrayAllocationVisitor - extends BaseInspectionVisitor { + public JComponent createOptionsPanel() { + LocalizeValue message = InspectionGadgetsLocalize.largeArrayAllocationNoOutofmemoryerrorMaximumNumberOfElementsOption(); + return new SingleIntegerFieldOptionsPanel(message.get(), this, "m_limit"); + } - @Override - public void visitNewExpression(@Nonnull PsiNewExpression expression) { - super.visitNewExpression(expression); - final PsiType type = expression.getType(); - if (!(type instanceof PsiArrayType)) { - return; - } - int size = 1; - final PsiExpression[] dimensions = expression.getArrayDimensions(); - for (final PsiExpression dimension : dimensions) { - final Integer intValue = - (Integer)ConstantExpressionUtil.computeCastTo( - dimension, PsiType.INT); - if (intValue != null) { - size *= intValue.intValue(); - } - } - if (size <= m_limit) { - return; - } - if (outOfMemoryExceptionCaught(expression)) { - return; - } - registerNewExpressionError(expression); + public BaseInspectionVisitor buildVisitor() { + return new CheckForOutOfMemoryOnLargeArrayAllocationVisitor(); } - private boolean outOfMemoryExceptionCaught(PsiElement element) { - PsiElement currentElement = element; - while (true) { - final PsiTryStatement containingTryStatement = - PsiTreeUtil.getParentOfType(currentElement, - PsiTryStatement.class); - if (containingTryStatement == null) { - return false; + private class CheckForOutOfMemoryOnLargeArrayAllocationVisitor extends BaseInspectionVisitor { + @Override + public void visitNewExpression(@Nonnull PsiNewExpression expression) { + super.visitNewExpression(expression); + final PsiType type = expression.getType(); + if (!(type instanceof PsiArrayType)) { + return; + } + int size = 1; + final PsiExpression[] dimensions = expression.getArrayDimensions(); + for (final PsiExpression dimension : dimensions) { + final Integer intValue = (Integer) ConstantExpressionUtil.computeCastTo(dimension, PsiType.INT); + if (intValue != null) { + size *= intValue.intValue(); + } + } + if (size <= m_limit) { + return; + } + if (outOfMemoryExceptionCaught(expression)) { + return; + } + registerNewExpressionError(expression); } - if (catchesOutOfMemoryException(containingTryStatement)) { - return true; + + private boolean outOfMemoryExceptionCaught(PsiElement element) { + PsiElement currentElement = element; + while (true) { + final PsiTryStatement containingTryStatement = PsiTreeUtil.getParentOfType(currentElement, PsiTryStatement.class); + if (containingTryStatement == null) { + return false; + } + if (catchesOutOfMemoryException(containingTryStatement)) { + return true; + } + currentElement = containingTryStatement; + } } - currentElement = containingTryStatement; - } - } - private boolean catchesOutOfMemoryException(PsiTryStatement statement) { - final PsiCatchSection[] sections = statement.getCatchSections(); - for (final PsiCatchSection section : sections) { - final PsiType catchType = section.getCatchType(); - if (catchType != null) { - final String typeText = catchType.getCanonicalText(); - if ("java.lang.OutOfMemoryError".equals(typeText)) { - return true; - } + private boolean catchesOutOfMemoryException(PsiTryStatement statement) { + final PsiCatchSection[] sections = statement.getCatchSections(); + for (final PsiCatchSection section : sections) { + final PsiType catchType = section.getCatchType(); + if (catchType != null) { + final String typeText = catchType.getCanonicalText(); + if ("java.lang.OutOfMemoryError".equals(typeText)) { + return true; + } + } + } + return false; } - } - return false; } - } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/j2me/ConnectionResourceInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/j2me/ConnectionResourceInspection.java index 8fbfabc647..3b34916f2c 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/j2me/ConnectionResourceInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/j2me/ConnectionResourceInspection.java @@ -23,195 +23,206 @@ import consulo.annotation.component.ExtensionImpl; import consulo.language.psi.PsiElement; import consulo.language.psi.util.PsiTreeUtil; +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; +import org.intellij.lang.annotations.Pattern; import org.jetbrains.annotations.NonNls; @ExtensionImpl public class ConnectionResourceInspection extends BaseInspection { + @Nonnull + @Override + @Pattern(VALID_ID_PATTERN) + public String getID() { + return "ConnectionOpenedButNotSafelyClosed"; + } - @Nonnull - public String getID() { - return "ConnectionOpenedButNotSafelyClosed"; - } - - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.connectionOpenedNotSafelyClosedDisplayName().get(); - } - - @Nonnull - public String buildErrorString(Object... infos) { - final PsiType type = (PsiType)infos[0]; - final String text = type.getPresentableText(); - return InspectionGadgetsLocalize.resourceOpenedNotClosedProblemDescriptor(text).get(); - } + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.connectionOpenedNotSafelyClosedDisplayName(); + } - public BaseInspectionVisitor buildVisitor() { - return new RecordStoreResourceVisitor(); - } + @Nonnull + public String buildErrorString(Object... infos) { + final PsiType type = (PsiType) infos[0]; + final String text = type.getPresentableText(); + return InspectionGadgetsLocalize.resourceOpenedNotClosedProblemDescriptor(text).get(); + } - private static class RecordStoreResourceVisitor - extends BaseInspectionVisitor { + public BaseInspectionVisitor buildVisitor() { + return new RecordStoreResourceVisitor(); + } - @Override - public void visitMethodCallExpression( - @Nonnull PsiMethodCallExpression expression) { - super.visitMethodCallExpression(expression); - if (!isConnectionFactoryMethod(expression)) { - return; - } - final PsiElement parent = expression.getParent(); - final PsiAssignmentExpression assignment; - if (!(parent instanceof PsiAssignmentExpression)) { - if (!(parent instanceof PsiTypeCastExpression)) { - final PsiType type = expression.getType(); - if (type != null) { - registerError(expression, type); - } - return; - } - final PsiElement grandParent = parent.getParent(); - if (!(grandParent instanceof PsiAssignmentExpression)) { - final PsiType type = expression.getType(); - if (type != null) { - registerError(expression, type); - } - return; - } - assignment = (PsiAssignmentExpression)grandParent; - } - else { - assignment = (PsiAssignmentExpression)parent; - } - final PsiExpression lhs = assignment.getLExpression(); - if (!(lhs instanceof PsiReferenceExpression)) { - return; - } - final PsiReferenceExpression referenceExpression = - (PsiReferenceExpression)lhs; - final PsiElement referent = referenceExpression.resolve(); - if (!(referent instanceof PsiVariable)) { - return; - } - final PsiVariable boundVariable = (PsiVariable)referent; - PsiElement currentContext = expression; - while (true) { - final PsiTryStatement tryStatement = - PsiTreeUtil.getParentOfType(currentContext, - PsiTryStatement.class); - if (tryStatement == null) { - final PsiType type = expression.getType(); - if (type != null) { - registerError(expression, type); - } - return; + private static class RecordStoreResourceVisitor + extends BaseInspectionVisitor { + + @Override + public void visitMethodCallExpression( + @Nonnull PsiMethodCallExpression expression + ) { + super.visitMethodCallExpression(expression); + if (!isConnectionFactoryMethod(expression)) { + return; + } + final PsiElement parent = expression.getParent(); + final PsiAssignmentExpression assignment; + if (!(parent instanceof PsiAssignmentExpression)) { + if (!(parent instanceof PsiTypeCastExpression)) { + final PsiType type = expression.getType(); + if (type != null) { + registerError(expression, type); + } + return; + } + final PsiElement grandParent = parent.getParent(); + if (!(grandParent instanceof PsiAssignmentExpression)) { + final PsiType type = expression.getType(); + if (type != null) { + registerError(expression, type); + } + return; + } + assignment = (PsiAssignmentExpression) grandParent; + } + else { + assignment = (PsiAssignmentExpression) parent; + } + final PsiExpression lhs = assignment.getLExpression(); + if (!(lhs instanceof PsiReferenceExpression)) { + return; + } + final PsiReferenceExpression referenceExpression = + (PsiReferenceExpression) lhs; + final PsiElement referent = referenceExpression.resolve(); + if (!(referent instanceof PsiVariable)) { + return; + } + final PsiVariable boundVariable = (PsiVariable) referent; + PsiElement currentContext = expression; + while (true) { + final PsiTryStatement tryStatement = + PsiTreeUtil.getParentOfType( + currentContext, + PsiTryStatement.class + ); + if (tryStatement == null) { + final PsiType type = expression.getType(); + if (type != null) { + registerError(expression, type); + } + return; + } + if (resourceIsOpenedInTryAndClosedInFinally( + tryStatement, expression, boundVariable)) { + return; + } + currentContext = tryStatement; + } } - if (resourceIsOpenedInTryAndClosedInFinally( - tryStatement, expression, boundVariable)) { - return; - } - currentContext = tryStatement; - } - } - private static boolean resourceIsOpenedInTryAndClosedInFinally( - PsiTryStatement tryStatement, PsiExpression lhs, - PsiVariable boundVariable) { - final PsiCodeBlock finallyBlock = tryStatement.getFinallyBlock(); - if (finallyBlock == null) { - return false; - } - final PsiCodeBlock tryBlock = tryStatement.getTryBlock(); - if (tryBlock == null) { - return false; - } - if (!PsiTreeUtil.isAncestor(tryBlock, lhs, true)) { - return false; - } - return containsResourceClose(finallyBlock, boundVariable); - } + private static boolean resourceIsOpenedInTryAndClosedInFinally( + PsiTryStatement tryStatement, PsiExpression lhs, + PsiVariable boundVariable + ) { + final PsiCodeBlock finallyBlock = tryStatement.getFinallyBlock(); + if (finallyBlock == null) { + return false; + } + final PsiCodeBlock tryBlock = tryStatement.getTryBlock(); + if (tryBlock == null) { + return false; + } + if (!PsiTreeUtil.isAncestor(tryBlock, lhs, true)) { + return false; + } + return containsResourceClose(finallyBlock, boundVariable); + } - private static boolean containsResourceClose( - PsiCodeBlock finallyBlock, PsiVariable boundVariable) { - final CloseVisitor visitor = - new CloseVisitor(boundVariable); - finallyBlock.accept(visitor); - return visitor.containsStreamClose(); - } + private static boolean containsResourceClose( + PsiCodeBlock finallyBlock, PsiVariable boundVariable + ) { + final CloseVisitor visitor = + new CloseVisitor(boundVariable); + finallyBlock.accept(visitor); + return visitor.containsStreamClose(); + } - private static boolean isConnectionFactoryMethod( - @Nonnull PsiMethodCallExpression expression) { - final PsiReferenceExpression methodExpression = - expression.getMethodExpression(); - final String methodName = methodExpression.getReferenceName(); - if (!HardcodedMethodConstants.OPEN.equals(methodName)) { - return false; - } - final PsiMethod method = expression.resolveMethod(); - if (method == null) { - return false; - } - final PsiClass containingClass = method.getContainingClass(); - if (containingClass == null) { - return false; - } - final String className = containingClass.getQualifiedName(); - @NonNls final String microeditionConnector = - "javax.microedition.io.Connector"; - return microeditionConnector.equals(className); + private static boolean isConnectionFactoryMethod( + @Nonnull PsiMethodCallExpression expression + ) { + final PsiReferenceExpression methodExpression = + expression.getMethodExpression(); + final String methodName = methodExpression.getReferenceName(); + if (!HardcodedMethodConstants.OPEN.equals(methodName)) { + return false; + } + final PsiMethod method = expression.resolveMethod(); + if (method == null) { + return false; + } + final PsiClass containingClass = method.getContainingClass(); + if (containingClass == null) { + return false; + } + final String className = containingClass.getQualifiedName(); + @NonNls final String microeditionConnector = + "javax.microedition.io.Connector"; + return microeditionConnector.equals(className); + } } - } - private static class CloseVisitor extends JavaRecursiveElementVisitor { + private static class CloseVisitor extends JavaRecursiveElementVisitor { - private boolean containsClose = false; - private final PsiVariable objectToClose; + private boolean containsClose = false; + private final PsiVariable objectToClose; - private CloseVisitor(PsiVariable objectToClose) { - super(); - this.objectToClose = objectToClose; - } + private CloseVisitor(PsiVariable objectToClose) { + super(); + this.objectToClose = objectToClose; + } - @Override - public void visitElement(@Nonnull PsiElement element) { - if (containsClose) { - return; - } - super.visitElement(element); - } + @Override + public void visitElement(@Nonnull PsiElement element) { + if (containsClose) { + return; + } + super.visitElement(element); + } - @Override - public void visitMethodCallExpression( - @Nonnull PsiMethodCallExpression call) { - if (containsClose) { - return; - } - super.visitMethodCallExpression(call); - final PsiReferenceExpression methodExpression = - call.getMethodExpression(); - final String methodName = methodExpression.getReferenceName(); - if (!HardcodedMethodConstants.CLOSE.equals(methodName)) { - return; - } - final PsiExpression qualifier = - methodExpression.getQualifierExpression(); - if (!(qualifier instanceof PsiReferenceExpression)) { - return; - } - final PsiReferenceExpression referenceExpression = - (PsiReferenceExpression)qualifier; - final PsiElement referent = referenceExpression.resolve(); - if (referent == null) { - return; - } - if (referent.equals(objectToClose)) { - containsClose = true; - } - } + @Override + public void visitMethodCallExpression( + @Nonnull PsiMethodCallExpression call + ) { + if (containsClose) { + return; + } + super.visitMethodCallExpression(call); + final PsiReferenceExpression methodExpression = + call.getMethodExpression(); + final String methodName = methodExpression.getReferenceName(); + if (!HardcodedMethodConstants.CLOSE.equals(methodName)) { + return; + } + final PsiExpression qualifier = + methodExpression.getQualifierExpression(); + if (!(qualifier instanceof PsiReferenceExpression)) { + return; + } + final PsiReferenceExpression referenceExpression = + (PsiReferenceExpression) qualifier; + final PsiElement referent = referenceExpression.resolve(); + if (referent == null) { + return; + } + if (referent.equals(objectToClose)) { + containsClose = true; + } + } - public boolean containsStreamClose() { - return containsClose; + public boolean containsStreamClose() { + return containsClose; + } } - } } diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/j2me/InterfaceWithOnlyOneDirectInheritorInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/j2me/InterfaceWithOnlyOneDirectInheritorInspection.java index 0302bfcd5e..122c28ec79 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/j2me/InterfaceWithOnlyOneDirectInheritorInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/j2me/InterfaceWithOnlyOneDirectInheritorInspection.java @@ -21,36 +21,37 @@ import com.siyeh.ig.BaseInspectionVisitor; import com.siyeh.localize.InspectionGadgetsLocalize; import consulo.annotation.component.ExtensionImpl; +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; @ExtensionImpl public class InterfaceWithOnlyOneDirectInheritorInspection extends BaseInspection { + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.interfaceOneInheritorDisplayName(); + } - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.interfaceOneInheritorDisplayName().get(); - } - - @Nonnull - public String buildErrorString(Object... infos) { - return InspectionGadgetsLocalize.interfaceOneInheritorProblemDescriptor().get(); - } + @Nonnull + public String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.interfaceOneInheritorProblemDescriptor().get(); + } - public BaseInspectionVisitor buildVisitor() { - return new InterfaceWithOnlyOneDirectInheritorVisitor(); - } + public BaseInspectionVisitor buildVisitor() { + return new InterfaceWithOnlyOneDirectInheritorVisitor(); + } - private static class InterfaceWithOnlyOneDirectInheritorVisitor extends BaseInspectionVisitor { + private static class InterfaceWithOnlyOneDirectInheritorVisitor extends BaseInspectionVisitor { - @Override - public void visitClass(@Nonnull PsiClass aClass) { - if (!aClass.isInterface() || aClass.isAnnotationType()) { - return; - } - if (!InheritanceUtil.hasOneInheritor(aClass)) { - return; - } - registerClassError(aClass); + @Override + public void visitClass(@Nonnull PsiClass aClass) { + if (!aClass.isInterface() || aClass.isAnnotationType()) { + return; + } + if (!InheritanceUtil.hasOneInheritor(aClass)) { + return; + } + registerClassError(aClass); + } } - } } diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/j2me/MethodCallInLoopConditionInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/j2me/MethodCallInLoopConditionInspection.java index 4b639df2a9..33e6517215 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/j2me/MethodCallInLoopConditionInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/j2me/MethodCallInLoopConditionInspection.java @@ -23,83 +23,84 @@ import com.siyeh.localize.InspectionGadgetsLocalize; import consulo.annotation.component.ExtensionImpl; import consulo.language.psi.PsiElementVisitor; +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; @ExtensionImpl public class MethodCallInLoopConditionInspection extends BaseInspection { + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.methodCallInLoopConditionDisplayName(); + } - @Override - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.methodCallInLoopConditionDisplayName().get(); - } - - @Override - @Nonnull - public String buildErrorString(Object... infos) { - return InspectionGadgetsLocalize.methodCallInLoopConditionProblemDescriptor().get(); - } - - @Override - protected boolean buildQuickFixesOnlyForOnTheFlyErrors() { - return true; - } - - @Nullable - @Override - protected InspectionGadgetsFix buildFix(Object... infos) { - return new IntroduceVariableFix(true); - } - - @Override - public BaseInspectionVisitor buildVisitor() { - return new MethodCallInLoopConditionVisitor(); - } - - private static class MethodCallInLoopConditionVisitor extends BaseInspectionVisitor { + @Override + @Nonnull + public String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.methodCallInLoopConditionProblemDescriptor().get(); + } @Override - public void visitForStatement(@Nonnull PsiForStatement statement) { - super.visitForStatement(statement); - final PsiExpression condition = statement.getCondition(); - if (condition == null) { - return; - } - checkForMethodCalls(condition); + protected boolean buildQuickFixesOnlyForOnTheFlyErrors() { + return true; } + @Nullable @Override - public void visitWhileStatement(@Nonnull PsiWhileStatement statement) { - super.visitWhileStatement(statement); - final PsiExpression condition = statement.getCondition(); - if (condition == null) { - return; - } - checkForMethodCalls(condition); + protected InspectionGadgetsFix buildFix(Object... infos) { + return new IntroduceVariableFix(true); } @Override - public void visitDoWhileStatement(@Nonnull PsiDoWhileStatement statement) { - super.visitDoWhileStatement(statement); - final PsiExpression condition = statement.getCondition(); - if (condition == null) { - return; - } - checkForMethodCalls(condition); + public BaseInspectionVisitor buildVisitor() { + return new MethodCallInLoopConditionVisitor(); } - private void checkForMethodCalls(PsiExpression condition) { - final PsiElementVisitor visitor = new JavaRecursiveElementVisitor() { + private static class MethodCallInLoopConditionVisitor extends BaseInspectionVisitor { + + @Override + public void visitForStatement(@Nonnull PsiForStatement statement) { + super.visitForStatement(statement); + final PsiExpression condition = statement.getCondition(); + if (condition == null) { + return; + } + checkForMethodCalls(condition); + } + + @Override + public void visitWhileStatement(@Nonnull PsiWhileStatement statement) { + super.visitWhileStatement(statement); + final PsiExpression condition = statement.getCondition(); + if (condition == null) { + return; + } + checkForMethodCalls(condition); + } + + @Override + public void visitDoWhileStatement(@Nonnull PsiDoWhileStatement statement) { + super.visitDoWhileStatement(statement); + final PsiExpression condition = statement.getCondition(); + if (condition == null) { + return; + } + checkForMethodCalls(condition); + } + + private void checkForMethodCalls(PsiExpression condition) { + final PsiElementVisitor visitor = new JavaRecursiveElementVisitor() { - @Override - public void visitMethodCallExpression( - @Nonnull PsiMethodCallExpression expression) { - super.visitMethodCallExpression(expression); - registerMethodCallError(expression); - } - }; - condition.accept(visitor); + @Override + public void visitMethodCallExpression( + @Nonnull PsiMethodCallExpression expression + ) { + super.visitMethodCallExpression(expression); + registerMethodCallError(expression); + } + }; + condition.accept(visitor); + } } - } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/j2me/MultiplyOrDivideByPowerOfTwoInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/j2me/MultiplyOrDivideByPowerOfTwoInspection.java index f6fc6fa19a..e2219e9229 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/j2me/MultiplyOrDivideByPowerOfTwoInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/j2me/MultiplyOrDivideByPowerOfTwoInspection.java @@ -37,176 +37,177 @@ import javax.swing.*; @ExtensionImpl -public class MultiplyOrDivideByPowerOfTwoInspection - extends BaseInspection { +public class MultiplyOrDivideByPowerOfTwoInspection extends BaseInspection { + /** + * @noinspection PublicField + */ + public boolean checkDivision = false; - /** - * @noinspection PublicField - */ - public boolean checkDivision = false; - - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.multiplyOrDivideByPowerOfTwoDisplayName().get(); - } - - @Nullable - public JComponent createOptionsPanel() { - LocalizeValue message = InspectionGadgetsLocalize.multiplyOrDivideByPowerOfTwoDivideOption(); - return new SingleCheckboxOptionsPanel(message.get(), this, "checkDivision"); - } - - @Nonnull - public String buildErrorString(Object... infos) { - return InspectionGadgetsLocalize.expressionCanBeReplacedProblemDescriptor(calculateReplacementShift((PsiExpression)infos[0])).get(); - } - - static String calculateReplacementShift(PsiExpression expression) { - final PsiExpression lhs; - final PsiExpression rhs; - final String operator; - if (expression instanceof PsiAssignmentExpression) { - final PsiAssignmentExpression exp = (PsiAssignmentExpression)expression; - lhs = exp.getLExpression(); - rhs = exp.getRExpression(); - final IElementType tokenType = exp.getOperationTokenType(); - if (tokenType.equals(JavaTokenType.ASTERISKEQ)) { - operator = "<<="; - } - else { - operator = ">>="; - } - } - else { - final PsiBinaryExpression exp = (PsiBinaryExpression)expression; - lhs = exp.getLOperand(); - rhs = exp.getROperand(); - final IElementType tokenType = exp.getOperationTokenType(); - if (tokenType.equals(JavaTokenType.ASTERISK)) { - operator = "<<"; - } - else { - operator = ">>"; - } - } - final String lhsText; - if (ParenthesesUtils.getPrecedence(lhs) > - ParenthesesUtils.SHIFT_PRECEDENCE) { - lhsText = '(' + lhs.getText() + ')'; - } - else { - lhsText = lhs.getText(); - } - String expString = - lhsText + operator + ShiftUtils.getLogBaseTwo(rhs); - final PsiElement parent = expression.getParent(); - if (parent instanceof PsiExpression) { - if (!(parent instanceof PsiParenthesizedExpression) && - ParenthesesUtils.getPrecedence((PsiExpression)parent) < - ParenthesesUtils.SHIFT_PRECEDENCE) { - expString = '(' + expString + ')'; - } + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.multiplyOrDivideByPowerOfTwoDisplayName(); } - return expString; - } - public InspectionGadgetsFix buildFix(Object... infos) { - final PsiExpression expression = (PsiExpression)infos[0]; - if (expression instanceof PsiBinaryExpression) { - final PsiBinaryExpression binaryExpression = - (PsiBinaryExpression)expression; - final IElementType operationTokenType = - binaryExpression.getOperationTokenType(); - if (JavaTokenType.DIV.equals(operationTokenType)) { - return null; - } - } - else if (expression instanceof PsiAssignmentExpression) { - final PsiAssignmentExpression assignmentExpression = - (PsiAssignmentExpression)expression; - final IElementType operationTokenType = - assignmentExpression.getOperationTokenType(); - if (JavaTokenType.DIVEQ.equals(operationTokenType)) { - return null; - } + @Nullable + public JComponent createOptionsPanel() { + LocalizeValue message = InspectionGadgetsLocalize.multiplyOrDivideByPowerOfTwoDivideOption(); + return new SingleCheckboxOptionsPanel(message.get(), this, "checkDivision"); } - return new MultiplyByPowerOfTwoFix(); - } - - private static class MultiplyByPowerOfTwoFix extends InspectionGadgetsFix { @Nonnull - public String getName() { - return InspectionGadgetsLocalize.multiplyOrDivideByPowerOfTwoReplaceQuickfix().get(); + public String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.expressionCanBeReplacedProblemDescriptor(calculateReplacementShift((PsiExpression) infos[0])) + .get(); + } + + static String calculateReplacementShift(PsiExpression expression) { + final PsiExpression lhs; + final PsiExpression rhs; + final String operator; + if (expression instanceof PsiAssignmentExpression) { + final PsiAssignmentExpression exp = (PsiAssignmentExpression) expression; + lhs = exp.getLExpression(); + rhs = exp.getRExpression(); + final IElementType tokenType = exp.getOperationTokenType(); + if (tokenType.equals(JavaTokenType.ASTERISKEQ)) { + operator = "<<="; + } + else { + operator = ">>="; + } + } + else { + final PsiBinaryExpression exp = (PsiBinaryExpression) expression; + lhs = exp.getLOperand(); + rhs = exp.getROperand(); + final IElementType tokenType = exp.getOperationTokenType(); + if (tokenType.equals(JavaTokenType.ASTERISK)) { + operator = "<<"; + } + else { + operator = ">>"; + } + } + final String lhsText; + if (ParenthesesUtils.getPrecedence(lhs) > + ParenthesesUtils.SHIFT_PRECEDENCE) { + lhsText = '(' + lhs.getText() + ')'; + } + else { + lhsText = lhs.getText(); + } + String expString = + lhsText + operator + ShiftUtils.getLogBaseTwo(rhs); + final PsiElement parent = expression.getParent(); + if (parent instanceof PsiExpression) { + if (!(parent instanceof PsiParenthesizedExpression) && + ParenthesesUtils.getPrecedence((PsiExpression) parent) < + ParenthesesUtils.SHIFT_PRECEDENCE) { + expString = '(' + expString + ')'; + } + } + return expString; } - public void doFix(Project project, ProblemDescriptor descriptor) - throws IncorrectOperationException { - final PsiExpression expression = (PsiExpression)descriptor.getPsiElement(); - final String newExpression = calculateReplacementShift(expression); - replaceExpression(expression, newExpression); + public InspectionGadgetsFix buildFix(Object... infos) { + final PsiExpression expression = (PsiExpression) infos[0]; + if (expression instanceof PsiBinaryExpression) { + final PsiBinaryExpression binaryExpression = + (PsiBinaryExpression) expression; + final IElementType operationTokenType = + binaryExpression.getOperationTokenType(); + if (JavaTokenType.DIV.equals(operationTokenType)) { + return null; + } + } + else if (expression instanceof PsiAssignmentExpression) { + final PsiAssignmentExpression assignmentExpression = + (PsiAssignmentExpression) expression; + final IElementType operationTokenType = + assignmentExpression.getOperationTokenType(); + if (JavaTokenType.DIVEQ.equals(operationTokenType)) { + return null; + } + } + return new MultiplyByPowerOfTwoFix(); } - } - public BaseInspectionVisitor buildVisitor() { - return new ConstantShiftVisitor(); - } + private static class MultiplyByPowerOfTwoFix extends InspectionGadgetsFix { + @Nonnull + @Override + public LocalizeValue getName() { + return InspectionGadgetsLocalize.multiplyOrDivideByPowerOfTwoReplaceQuickfix(); + } - private class ConstantShiftVisitor extends BaseInspectionVisitor { + public void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { + final PsiExpression expression = (PsiExpression) descriptor.getPsiElement(); + final String newExpression = calculateReplacementShift(expression); + replaceExpression(expression, newExpression); + } + } - @Override - public void visitBinaryExpression( - @Nonnull PsiBinaryExpression expression) { - super.visitBinaryExpression(expression); - final PsiExpression rhs = expression.getROperand(); - if (rhs == null) { - return; - } + public BaseInspectionVisitor buildVisitor() { + return new ConstantShiftVisitor(); + } - final IElementType tokenType = expression.getOperationTokenType(); - if (!tokenType.equals(JavaTokenType.ASTERISK)) { - if (!checkDivision || !tokenType.equals(JavaTokenType.DIV)) { - return; + private class ConstantShiftVisitor extends BaseInspectionVisitor { + + @Override + public void visitBinaryExpression( + @Nonnull PsiBinaryExpression expression + ) { + super.visitBinaryExpression(expression); + final PsiExpression rhs = expression.getROperand(); + if (rhs == null) { + return; + } + + final IElementType tokenType = expression.getOperationTokenType(); + if (!tokenType.equals(JavaTokenType.ASTERISK)) { + if (!checkDivision || !tokenType.equals(JavaTokenType.DIV)) { + return; + } + } + if (!ShiftUtils.isPowerOfTwo(rhs)) { + return; + } + final PsiType type = expression.getType(); + if (type == null) { + return; + } + if (!ClassUtils.isIntegral(type)) { + return; + } + registerError(expression, expression); } - } - if (!ShiftUtils.isPowerOfTwo(rhs)) { - return; - } - final PsiType type = expression.getType(); - if (type == null) { - return; - } - if (!ClassUtils.isIntegral(type)) { - return; - } - registerError(expression, expression); - } - @Override - public void visitAssignmentExpression( - @Nonnull PsiAssignmentExpression expression) { - super.visitAssignmentExpression(expression); - if (!WellFormednessUtils.isWellFormed(expression)) { - return; - } - final IElementType tokenType = expression.getOperationTokenType(); - if (!tokenType.equals(JavaTokenType.ASTERISKEQ)) { - if (!checkDivision || !tokenType.equals(JavaTokenType.DIVEQ)) { - return; + @Override + public void visitAssignmentExpression( + @Nonnull PsiAssignmentExpression expression + ) { + super.visitAssignmentExpression(expression); + if (!WellFormednessUtils.isWellFormed(expression)) { + return; + } + final IElementType tokenType = expression.getOperationTokenType(); + if (!tokenType.equals(JavaTokenType.ASTERISKEQ)) { + if (!checkDivision || !tokenType.equals(JavaTokenType.DIVEQ)) { + return; + } + } + final PsiExpression rhs = expression.getRExpression(); + if (!ShiftUtils.isPowerOfTwo(rhs)) { + return; + } + final PsiType type = expression.getType(); + if (type == null) { + return; + } + if (!ClassUtils.isIntegral(type)) { + return; + } + registerError(expression, expression); } - } - final PsiExpression rhs = expression.getRExpression(); - if (!ShiftUtils.isPowerOfTwo(rhs)) { - return; - } - final PsiType type = expression.getType(); - if (type == null) { - return; - } - if (!ClassUtils.isIntegral(type)) { - return; - } - registerError(expression, expression); } - } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/j2me/OverlyLargePrimitiveArrayInitializerInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/j2me/OverlyLargePrimitiveArrayInitializerInspection.java index 3d82e94ab9..66b1716a58 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/j2me/OverlyLargePrimitiveArrayInitializerInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/j2me/OverlyLargePrimitiveArrayInitializerInspection.java @@ -29,61 +29,62 @@ import javax.swing.*; public abstract class OverlyLargePrimitiveArrayInitializerInspection extends BaseInspection { - /** - * @noinspection PublicField - */ - public int m_limit = 64; + /** + * @noinspection PublicField + */ + public int m_limit = 64; - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.largeInitializerPrimitiveTypeArrayDisplayName().get(); - } - - @Nonnull - public String buildErrorString(Object... infos) { - final Integer numElements = (Integer)infos[0]; - return InspectionGadgetsLocalize.largeInitializerPrimitiveTypeArrayProblemDescriptor(numElements).get(); - } + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.largeInitializerPrimitiveTypeArrayDisplayName(); + } - public JComponent createOptionsPanel() { - LocalizeValue message = InspectionGadgetsLocalize.largeInitializerPrimitiveTypeArrayMaximumNumberOfElementsOption(); - return new SingleIntegerFieldOptionsPanel(message.get(), this, "m_limit"); - } + @Nonnull + public String buildErrorString(Object... infos) { + final Integer numElements = (Integer) infos[0]; + return InspectionGadgetsLocalize.largeInitializerPrimitiveTypeArrayProblemDescriptor(numElements).get(); + } - public BaseInspectionVisitor buildVisitor() { - return new OverlyLargePrimitiveArrayInitializerVisitor(); - } + public JComponent createOptionsPanel() { + LocalizeValue message = InspectionGadgetsLocalize.largeInitializerPrimitiveTypeArrayMaximumNumberOfElementsOption(); + return new SingleIntegerFieldOptionsPanel(message.get(), this, "m_limit"); + } - private class OverlyLargePrimitiveArrayInitializerVisitor extends BaseInspectionVisitor { - @Override - public void visitArrayInitializerExpression(PsiArrayInitializerExpression expression) { - super.visitArrayInitializerExpression(expression); - final PsiType type = expression.getType(); - if (type == null) { - return; - } - final PsiType componentType = type.getDeepComponentType(); - if (!(componentType instanceof PsiPrimitiveType)) { - return; - } - final int numElements = calculateNumElements(expression); - if (numElements <= m_limit) { - return; - } - registerError(expression, Integer.valueOf(numElements)); + public BaseInspectionVisitor buildVisitor() { + return new OverlyLargePrimitiveArrayInitializerVisitor(); } - private int calculateNumElements(PsiExpression expression) { - if (expression instanceof PsiArrayInitializerExpression) { - final PsiArrayInitializerExpression arrayExpression = (PsiArrayInitializerExpression)expression; - final PsiExpression[] initializers = arrayExpression.getInitializers(); - int out = 0; - for (final PsiExpression initializer : initializers) { - out += calculateNumElements(initializer); + private class OverlyLargePrimitiveArrayInitializerVisitor extends BaseInspectionVisitor { + @Override + public void visitArrayInitializerExpression(PsiArrayInitializerExpression expression) { + super.visitArrayInitializerExpression(expression); + final PsiType type = expression.getType(); + if (type == null) { + return; + } + final PsiType componentType = type.getDeepComponentType(); + if (!(componentType instanceof PsiPrimitiveType)) { + return; + } + final int numElements = calculateNumElements(expression); + if (numElements <= m_limit) { + return; + } + registerError(expression, Integer.valueOf(numElements)); + } + + private int calculateNumElements(PsiExpression expression) { + if (expression instanceof PsiArrayInitializerExpression) { + final PsiArrayInitializerExpression arrayExpression = (PsiArrayInitializerExpression) expression; + final PsiExpression[] initializers = arrayExpression.getInitializers(); + int out = 0; + for (final PsiExpression initializer : initializers) { + out += calculateNumElements(initializer); + } + return out; + } + return 1; } - return out; - } - return 1; } - } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/j2me/PrivateMemberAccessBetweenOuterAndInnerClassInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/j2me/PrivateMemberAccessBetweenOuterAndInnerClassInspection.java index 313d716599..677d2ccefd 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/j2me/PrivateMemberAccessBetweenOuterAndInnerClassInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/j2me/PrivateMemberAccessBetweenOuterAndInnerClassInspection.java @@ -27,240 +27,245 @@ import consulo.language.psi.PsiElement; import consulo.language.psi.util.PsiTreeUtil; import consulo.language.util.IncorrectOperationException; +import consulo.localize.LocalizeValue; import consulo.project.Project; import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; import org.jetbrains.annotations.NonNls; @ExtensionImpl -public class PrivateMemberAccessBetweenOuterAndInnerClassInspection - extends BaseInspection { - - @Override - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.privateMemberAccessBetweenOuterAndInnerClassesDisplayName().get(); - } - - @Override - @Nonnull - @RequiredReadAction - protected String buildErrorString(Object... infos) { - final PsiClass aClass = (PsiClass)infos[0]; - return InspectionGadgetsLocalize.privateMemberAccessBetweenOuterAndInnerClassesProblemDescriptor(aClass.getName()).get(); - } +public class PrivateMemberAccessBetweenOuterAndInnerClassInspection extends BaseInspection { + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.privateMemberAccessBetweenOuterAndInnerClassesDisplayName(); + } - @Override - public InspectionGadgetsFix buildFix(Object... infos) { - final PsiClass aClass = (PsiClass)infos[0]; - final String className = aClass.getName(); - if (infos.length == 1) { - return new MakePackagePrivateFix(className, true); + @Nonnull + @Override + @RequiredReadAction + protected String buildErrorString(Object... infos) { + final PsiClass aClass = (PsiClass) infos[0]; + return InspectionGadgetsLocalize.privateMemberAccessBetweenOuterAndInnerClassesProblemDescriptor(aClass.getName()).get(); } - final PsiMember member = (PsiMember)infos[1]; - @NonNls final String memberName; - if (member instanceof PsiMethod) { - final PsiMethod method = (PsiMethod)member; - if (method.isConstructor()) { - } + @Override + public InspectionGadgetsFix buildFix(Object... infos) { + final PsiClass aClass = (PsiClass) infos[0]; + final String className = aClass.getName(); + if (infos.length == 1) { + return new MakePackagePrivateFix(className, true); + } + final PsiMember member = (PsiMember) infos[1]; + @NonNls final String memberName; + if (member instanceof PsiMethod) { + final PsiMethod method = (PsiMethod) member; + if (method.isConstructor()) { + } - memberName = member.getName() + "()"; - } - else { - memberName = member.getName(); + memberName = member.getName() + "()"; + } + else { + memberName = member.getName(); + } + @NonNls final String elementName = className + '.' + memberName; + return new MakePackagePrivateFix(elementName, false); } - @NonNls final String elementName = className + '.' + memberName; - return new MakePackagePrivateFix(elementName, false); - } - private static class MakePackagePrivateFix extends InspectionGadgetsFix { + private static class MakePackagePrivateFix extends InspectionGadgetsFix { - private final String elementName; - private final boolean constructor; + private final String elementName; + private final boolean constructor; - private MakePackagePrivateFix(String elementName, boolean constructor) { - this.elementName = elementName; - this.constructor = constructor; - } + private MakePackagePrivateFix(String elementName, boolean constructor) { + this.elementName = elementName; + this.constructor = constructor; + } - @Override - @Nonnull - public String getName() { - return constructor - ? InspectionGadgetsLocalize.privateMemberAccessBetweenOuterAndInnerClassesMakeConstructorPackageLocalQuickfix(elementName).get() - : InspectionGadgetsLocalize.privateMemberAccessBetweenOuterAndInnerClassesMakeLocalQuickfix(elementName).get(); - } + @Nonnull + @Override + public LocalizeValue getName() { + return constructor + ? InspectionGadgetsLocalize.privateMemberAccessBetweenOuterAndInnerClassesMakeConstructorPackageLocalQuickfix(elementName) + : InspectionGadgetsLocalize.privateMemberAccessBetweenOuterAndInnerClassesMakeLocalQuickfix(elementName); + } - @Override - public void doFix(Project project, ProblemDescriptor descriptor) - throws IncorrectOperationException { - final PsiElement element = descriptor.getPsiElement(); - if (constructor) { - makeConstructorPackageLocal(project, element); - } - else { - makeMemberPackageLocal(element); - } - } + @Override + public void doFix(Project project, ProblemDescriptor descriptor) + throws IncorrectOperationException { + final PsiElement element = descriptor.getPsiElement(); + if (constructor) { + makeConstructorPackageLocal(project, element); + } + else { + makeMemberPackageLocal(element); + } + } - private static void makeMemberPackageLocal(PsiElement element) { - final PsiElement parent = element.getParent(); - final PsiReferenceExpression reference = - (PsiReferenceExpression)parent; - final PsiModifierListOwner member = - (PsiModifierListOwner)reference.resolve(); - if (member == null) { - return; - } - final PsiModifierList modifiers = member.getModifierList(); - if (modifiers == null) { - return; - } - modifiers.setModifierProperty(PsiModifier.PUBLIC, false); - modifiers.setModifierProperty(PsiModifier.PROTECTED, false); - modifiers.setModifierProperty(PsiModifier.PRIVATE, false); - } + private static void makeMemberPackageLocal(PsiElement element) { + final PsiElement parent = element.getParent(); + final PsiReferenceExpression reference = + (PsiReferenceExpression) parent; + final PsiModifierListOwner member = + (PsiModifierListOwner) reference.resolve(); + if (member == null) { + return; + } + final PsiModifierList modifiers = member.getModifierList(); + if (modifiers == null) { + return; + } + modifiers.setModifierProperty(PsiModifier.PUBLIC, false); + modifiers.setModifierProperty(PsiModifier.PROTECTED, false); + modifiers.setModifierProperty(PsiModifier.PRIVATE, false); + } - private static void makeConstructorPackageLocal(Project project, - PsiElement element) { - final PsiNewExpression newExpression = - PsiTreeUtil.getParentOfType(element, - PsiNewExpression.class); - if (newExpression == null) { - return; - } - final PsiMethod constructor = - newExpression.resolveConstructor(); - if (constructor != null) { - final PsiModifierList modifierList = - constructor.getModifierList(); - modifierList.setModifierProperty(PsiModifier.PRIVATE, - false); - return; - } - final PsiJavaCodeReferenceElement referenceElement = - (PsiJavaCodeReferenceElement)element; - final PsiElement target = referenceElement.resolve(); - if (!(target instanceof PsiClass)) { - return; - } - final PsiClass aClass = (PsiClass)target; - final PsiElementFactory elementFactory = - JavaPsiFacade.getElementFactory(project); - final PsiMethod newConstructor = elementFactory.createConstructor(); - final PsiModifierList modifierList = - newConstructor.getModifierList(); - modifierList.setModifierProperty(PsiModifier.PACKAGE_LOCAL, true); - aClass.add(newConstructor); + private static void makeConstructorPackageLocal( + Project project, + PsiElement element + ) { + final PsiNewExpression newExpression = + PsiTreeUtil.getParentOfType( + element, + PsiNewExpression.class + ); + if (newExpression == null) { + return; + } + final PsiMethod constructor = + newExpression.resolveConstructor(); + if (constructor != null) { + final PsiModifierList modifierList = + constructor.getModifierList(); + modifierList.setModifierProperty( + PsiModifier.PRIVATE, + false + ); + return; + } + final PsiJavaCodeReferenceElement referenceElement = + (PsiJavaCodeReferenceElement) element; + final PsiElement target = referenceElement.resolve(); + if (!(target instanceof PsiClass)) { + return; + } + final PsiClass aClass = (PsiClass) target; + final PsiElementFactory elementFactory = + JavaPsiFacade.getElementFactory(project); + final PsiMethod newConstructor = elementFactory.createConstructor(); + final PsiModifierList modifierList = + newConstructor.getModifierList(); + modifierList.setModifierProperty(PsiModifier.PACKAGE_LOCAL, true); + aClass.add(newConstructor); + } } - } - @Override - public BaseInspectionVisitor buildVisitor() { - return new PrivateMemberAccessFromInnerClassVisior(); - } + @Override + public BaseInspectionVisitor buildVisitor() { + return new PrivateMemberAccessFromInnerClassVisior(); + } - private static class PrivateMemberAccessFromInnerClassVisior - extends BaseInspectionVisitor { + private static class PrivateMemberAccessFromInnerClassVisior + extends BaseInspectionVisitor { - @Override - public void visitNewExpression(PsiNewExpression expression) { + @Override + public void visitNewExpression(PsiNewExpression expression) { /* if (JspPsiUtil.isInJspFile(expression)) { return; } */ - super.visitNewExpression(expression); - final PsiClass containingClass = - getContainingContextClass(expression); - if (containingClass == null) { - return; - } - final PsiMethod constructor = expression.resolveConstructor(); - if (constructor == null) { - final PsiJavaCodeReferenceElement classReference = - expression.getClassOrAnonymousClassReference(); - if (classReference == null) { - return; - } - final PsiElement target = classReference.resolve(); - if (!(target instanceof PsiClass)) { - return; - } - final PsiClass aClass = (PsiClass)target; - if (!aClass.hasModifierProperty(PsiModifier.PRIVATE)) { - return; - } - if (aClass.equals(containingClass)) { - return; - } - registerNewExpressionError(expression, aClass); - } - else { - if (!constructor.hasModifierProperty(PsiModifier.PRIVATE)) { - return; + super.visitNewExpression(expression); + final PsiClass containingClass = + getContainingContextClass(expression); + if (containingClass == null) { + return; + } + final PsiMethod constructor = expression.resolveConstructor(); + if (constructor == null) { + final PsiJavaCodeReferenceElement classReference = + expression.getClassOrAnonymousClassReference(); + if (classReference == null) { + return; + } + final PsiElement target = classReference.resolve(); + if (!(target instanceof PsiClass)) { + return; + } + final PsiClass aClass = (PsiClass) target; + if (!aClass.hasModifierProperty(PsiModifier.PRIVATE)) { + return; + } + if (aClass.equals(containingClass)) { + return; + } + registerNewExpressionError(expression, aClass); + } + else { + if (!constructor.hasModifierProperty(PsiModifier.PRIVATE)) { + return; + } + final PsiClass aClass = constructor.getContainingClass(); + if (containingClass.equals(aClass)) { + return; + } + registerNewExpressionError(expression, aClass); + } } - final PsiClass aClass = constructor.getContainingClass(); - if (containingClass.equals(aClass)) { - return; - } - registerNewExpressionError(expression, aClass); - } - } - @Override - public void visitReferenceExpression( - @Nonnull PsiReferenceExpression expression) { + @Override + public void visitReferenceExpression( + @Nonnull PsiReferenceExpression expression + ) { /* if (JspPsiUtil.isInJspFile(expression)) { // disable for jsp files IDEADEV-12957 return; } */ - super.visitReferenceExpression(expression); - if (expression.getQualifierExpression() == null) { - return; - } - final PsiElement referenceNameElement = - expression.getReferenceNameElement(); - if (referenceNameElement == null) { - return; - } - final PsiElement containingClass = - getContainingContextClass(expression); - if (containingClass == null) { - return; - } - final PsiElement element = expression.resolve(); - if (!(element instanceof PsiMethod || element instanceof PsiField)) { - return; - } - final PsiMember member = (PsiMember)element; - if (!member.hasModifierProperty(PsiModifier.PRIVATE)) { - return; - } - final PsiClass memberClass = - ClassUtils.getContainingClass(member); - if (memberClass == null) { - return; - } - if (memberClass.equals(containingClass)) { - return; - } - registerError(referenceNameElement, memberClass, member); - } + super.visitReferenceExpression(expression); + if (expression.getQualifierExpression() == null) { + return; + } + final PsiElement referenceNameElement = + expression.getReferenceNameElement(); + if (referenceNameElement == null) { + return; + } + final PsiElement containingClass = + getContainingContextClass(expression); + if (containingClass == null) { + return; + } + final PsiElement element = expression.resolve(); + if (!(element instanceof PsiMethod || element instanceof PsiField)) { + return; + } + final PsiMember member = (PsiMember) element; + if (!member.hasModifierProperty(PsiModifier.PRIVATE)) { + return; + } + final PsiClass memberClass = + ClassUtils.getContainingClass(member); + if (memberClass == null) { + return; + } + if (memberClass.equals(containingClass)) { + return; + } + registerError(referenceNameElement, memberClass, member); + } - @Nullable - private static PsiClass getContainingContextClass(PsiElement element) { - final PsiClass aClass = - ClassUtils.getContainingClass(element); - if (aClass instanceof PsiAnonymousClass) { - final PsiAnonymousClass anonymousClass = - (PsiAnonymousClass)aClass; - final PsiExpressionList args = anonymousClass.getArgumentList(); - if (args != null && - PsiTreeUtil.isAncestor(args, element, true)) { - return ClassUtils.getContainingClass(aClass); + @Nullable + private static PsiClass getContainingContextClass(PsiElement element) { + final PsiClass aClass = + ClassUtils.getContainingClass(element); + if (aClass instanceof PsiAnonymousClass) { + final PsiAnonymousClass anonymousClass = + (PsiAnonymousClass) aClass; + final PsiExpressionList args = anonymousClass.getArgumentList(); + if (args != null && + PsiTreeUtil.isAncestor(args, element, true)) { + return ClassUtils.getContainingClass(aClass); + } + } + return aClass; } - } - return aClass; } - } } diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/j2me/RecordStoreResourceInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/j2me/RecordStoreResourceInspection.java index 9043334d2f..41fbdf73a2 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/j2me/RecordStoreResourceInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/j2me/RecordStoreResourceInspection.java @@ -23,177 +23,191 @@ import consulo.language.psi.PsiElement; import consulo.language.psi.PsiReference; import consulo.language.psi.util.PsiTreeUtil; +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; +import org.intellij.lang.annotations.Pattern; import org.jetbrains.annotations.NonNls; @ExtensionImpl public class RecordStoreResourceInspection extends BaseInspection { - - @Nonnull - public String getID() { - return "RecordStoreOpenedButNotSafelyClosed"; - } - - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.recordstoreOpenedNotSafelyClosedDisplayName().get(); - } - - @Nonnull - public String buildErrorString(Object... infos) { - final PsiExpression expression = (PsiExpression)infos[0]; - final PsiType type = expression.getType(); - assert type != null; - final String text = type.getPresentableText(); - return InspectionGadgetsLocalize.resourceOpenedNotClosedProblemDescriptor(text).get(); - } - - public BaseInspectionVisitor buildVisitor() { - return new RecordStoreResourceVisitor(); - } - - private static class RecordStoreResourceVisitor - extends BaseInspectionVisitor { - + @Nonnull @Override - public void visitMethodCallExpression( - @Nonnull PsiMethodCallExpression expression) { - super.visitMethodCallExpression(expression); - if (!isRecordStoreFactoryMethod(expression)) { - return; - } - final PsiElement parent = expression.getParent(); - if (!(parent instanceof PsiAssignmentExpression)) { - registerError(expression, expression); - return; - } - final PsiAssignmentExpression assignment = - (PsiAssignmentExpression)parent; - final PsiExpression lhs = assignment.getLExpression(); - if (!(lhs instanceof PsiReferenceExpression)) { - return; - } - final PsiElement referent = - ((PsiReference)lhs).resolve(); - if (!(referent instanceof PsiVariable)) { - return; - } - final PsiVariable boundVariable = (PsiVariable)referent; - PsiElement currentContext = expression; - while (true) { - final PsiTryStatement tryStatement = - PsiTreeUtil.getParentOfType(currentContext, - PsiTryStatement.class); - if (tryStatement == null) { - registerError(expression, expression); - return; - } - if (resourceIsOpenedInTryAndClosedInFinally(tryStatement, - expression, - boundVariable)) { - return; - } - currentContext = tryStatement; - } + @Pattern(VALID_ID_PATTERN) + public String getID() { + return "RecordStoreOpenedButNotSafelyClosed"; } - private static boolean resourceIsOpenedInTryAndClosedInFinally( - PsiTryStatement tryStatement, PsiExpression lhs, - PsiVariable boundVariable) { - final PsiCodeBlock finallyBlock = tryStatement.getFinallyBlock(); - if (finallyBlock == null) { - return false; - } - final PsiCodeBlock tryBlock = tryStatement.getTryBlock(); - if (tryBlock == null) { - return false; - } - if (!PsiTreeUtil.isAncestor(tryBlock, lhs, true)) { - return false; - } - return containsResourceClose(finallyBlock, boundVariable); + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.recordstoreOpenedNotSafelyClosedDisplayName(); } - private static boolean containsResourceClose(PsiCodeBlock finallyBlock, - PsiVariable boundVariable) { - final CloseVisitor visitor = - new CloseVisitor(boundVariable); - finallyBlock.accept(visitor); - return visitor.containsStreamClose(); + @Nonnull + public String buildErrorString(Object... infos) { + final PsiExpression expression = (PsiExpression) infos[0]; + final PsiType type = expression.getType(); + assert type != null; + final String text = type.getPresentableText(); + return InspectionGadgetsLocalize.resourceOpenedNotClosedProblemDescriptor(text).get(); } - private static boolean isRecordStoreFactoryMethod( - @Nonnull PsiMethodCallExpression expression) { - final PsiReferenceExpression methodExpression = - expression.getMethodExpression(); - final String methodName = methodExpression.getReferenceName(); - @NonNls final String openStore = "openRecordStore"; - if (!openStore.equals(methodName)) { - return false; - } - final PsiMethod method = expression.resolveMethod(); - if (method == null) { - return false; - } - final PsiClass containingClass = method.getContainingClass(); - if (containingClass == null) { - return false; - } - final String className = containingClass.getQualifiedName(); - @NonNls final String recordStore = - "javax.microedition.rms.RecordStore"; - return recordStore.equals(className); + public BaseInspectionVisitor buildVisitor() { + return new RecordStoreResourceVisitor(); } - } - private static class CloseVisitor extends JavaRecursiveElementVisitor { + private static class RecordStoreResourceVisitor + extends BaseInspectionVisitor { + + @Override + public void visitMethodCallExpression( + @Nonnull PsiMethodCallExpression expression + ) { + super.visitMethodCallExpression(expression); + if (!isRecordStoreFactoryMethod(expression)) { + return; + } + final PsiElement parent = expression.getParent(); + if (!(parent instanceof PsiAssignmentExpression)) { + registerError(expression, expression); + return; + } + final PsiAssignmentExpression assignment = + (PsiAssignmentExpression) parent; + final PsiExpression lhs = assignment.getLExpression(); + if (!(lhs instanceof PsiReferenceExpression)) { + return; + } + final PsiElement referent = + ((PsiReference) lhs).resolve(); + if (!(referent instanceof PsiVariable)) { + return; + } + final PsiVariable boundVariable = (PsiVariable) referent; + PsiElement currentContext = expression; + while (true) { + final PsiTryStatement tryStatement = + PsiTreeUtil.getParentOfType( + currentContext, + PsiTryStatement.class + ); + if (tryStatement == null) { + registerError(expression, expression); + return; + } + if (resourceIsOpenedInTryAndClosedInFinally( + tryStatement, + expression, + boundVariable + )) { + return; + } + currentContext = tryStatement; + } + } - private boolean containsClose = false; - private final PsiVariable objectToClose; + private static boolean resourceIsOpenedInTryAndClosedInFinally( + PsiTryStatement tryStatement, PsiExpression lhs, + PsiVariable boundVariable + ) { + final PsiCodeBlock finallyBlock = tryStatement.getFinallyBlock(); + if (finallyBlock == null) { + return false; + } + final PsiCodeBlock tryBlock = tryStatement.getTryBlock(); + if (tryBlock == null) { + return false; + } + if (!PsiTreeUtil.isAncestor(tryBlock, lhs, true)) { + return false; + } + return containsResourceClose(finallyBlock, boundVariable); + } - private CloseVisitor(PsiVariable objectToClose) { - super(); - this.objectToClose = objectToClose; - } + private static boolean containsResourceClose( + PsiCodeBlock finallyBlock, + PsiVariable boundVariable + ) { + final CloseVisitor visitor = + new CloseVisitor(boundVariable); + finallyBlock.accept(visitor); + return visitor.containsStreamClose(); + } - @Override - public void visitElement(@Nonnull PsiElement element) { - if (!containsClose) { - super.visitElement(element); - } + private static boolean isRecordStoreFactoryMethod( + @Nonnull PsiMethodCallExpression expression + ) { + final PsiReferenceExpression methodExpression = + expression.getMethodExpression(); + final String methodName = methodExpression.getReferenceName(); + @NonNls final String openStore = "openRecordStore"; + if (!openStore.equals(methodName)) { + return false; + } + final PsiMethod method = expression.resolveMethod(); + if (method == null) { + return false; + } + final PsiClass containingClass = method.getContainingClass(); + if (containingClass == null) { + return false; + } + final String className = containingClass.getQualifiedName(); + @NonNls final String recordStore = + "javax.microedition.rms.RecordStore"; + return recordStore.equals(className); + } } - @Override - public void visitMethodCallExpression( - @Nonnull PsiMethodCallExpression call) { - if (containsClose) { - return; - } - super.visitMethodCallExpression(call); - final PsiReferenceExpression methodExpression = - call.getMethodExpression(); - final String methodName = methodExpression.getReferenceName(); - @NonNls final String closeStore = "closeRecordStore"; - if (!closeStore.equals(methodName)) { - return; - } - final PsiExpression qualifier = - methodExpression.getQualifierExpression(); - if (!(qualifier instanceof PsiReferenceExpression)) { - return; - } - final PsiElement referent = - ((PsiReference)qualifier).resolve(); - if (referent == null) { - return; - } - if (referent.equals(objectToClose)) { - containsClose = true; - } - } + private static class CloseVisitor extends JavaRecursiveElementVisitor { + + private boolean containsClose = false; + private final PsiVariable objectToClose; + + private CloseVisitor(PsiVariable objectToClose) { + super(); + this.objectToClose = objectToClose; + } + + @Override + public void visitElement(@Nonnull PsiElement element) { + if (!containsClose) { + super.visitElement(element); + } + } - public boolean containsStreamClose() { - return containsClose; + @Override + public void visitMethodCallExpression( + @Nonnull PsiMethodCallExpression call + ) { + if (containsClose) { + return; + } + super.visitMethodCallExpression(call); + final PsiReferenceExpression methodExpression = + call.getMethodExpression(); + final String methodName = methodExpression.getReferenceName(); + @NonNls final String closeStore = "closeRecordStore"; + if (!closeStore.equals(methodName)) { + return; + } + final PsiExpression qualifier = + methodExpression.getQualifierExpression(); + if (!(qualifier instanceof PsiReferenceExpression)) { + return; + } + final PsiElement referent = + ((PsiReference) qualifier).resolve(); + if (referent == null) { + return; + } + if (referent.equals(objectToClose)) { + containsClose = true; + } + } + + public boolean containsStreamClose() { + return containsClose; + } } - } } diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/j2me/SimplifiableIfStatementInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/j2me/SimplifiableIfStatementInspection.java index aa831ba586..b146f3d4eb 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/j2me/SimplifiableIfStatementInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/j2me/SimplifiableIfStatementInspection.java @@ -29,6 +29,7 @@ import consulo.language.psi.PsiWhiteSpace; import consulo.language.psi.util.PsiTreeUtil; import consulo.language.util.IncorrectOperationException; +import consulo.localize.LocalizeValue; import consulo.project.Project; import consulo.util.lang.StringUtil; import jakarta.annotation.Nonnull; @@ -37,371 +38,374 @@ @ExtensionImpl public class SimplifiableIfStatementInspection extends BaseInspection { - - @Override - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.simplifiableIfStatementDisplayName().get(); - } - - @Override - public boolean isEnabledByDefault() { - return true; - } - - @Override - public BaseInspectionVisitor buildVisitor() { - return new SimplifiableIfStatementVisitor(); - } - - @Override - @Nonnull - public String buildErrorString(Object... infos) { - final PsiIfStatement statement = (PsiIfStatement)infos[0]; - return InspectionGadgetsLocalize.simplifiableIfStatementProblemDescriptor( - StringUtil.escapeXml(calculateReplacementStatement(statement)) - ).get(); - } - - @Nullable - @NonNls - static String calculateReplacementStatement(PsiIfStatement statement) { - final PsiStatement thenBranch = ControlFlowUtils.stripBraces(statement.getThenBranch()); - if (thenBranch == null) { - return null; + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.simplifiableIfStatementDisplayName(); } - PsiStatement elseBranch = statement.getElseBranch(); - if (elseBranch == null) { - final PsiElement nextStatement = PsiTreeUtil.skipSiblingsForward(statement, PsiWhiteSpace.class); - if (nextStatement instanceof PsiStatement) { - elseBranch = (PsiStatement)nextStatement; - } - } else { - elseBranch = ControlFlowUtils.stripBraces(elseBranch); + + @Override + public boolean isEnabledByDefault() { + return true; } - if (elseBranch == null) { - return null; + + @Override + public BaseInspectionVisitor buildVisitor() { + return new SimplifiableIfStatementVisitor(); } - final PsiExpression condition = statement.getCondition(); - if (condition == null) { - return null; + + @Override + @Nonnull + public String buildErrorString(Object... infos) { + final PsiIfStatement statement = (PsiIfStatement) infos[0]; + return InspectionGadgetsLocalize.simplifiableIfStatementProblemDescriptor( + StringUtil.escapeXml(calculateReplacementStatement(statement)) + ).get(); } - if (thenBranch instanceof PsiReturnStatement && elseBranch instanceof PsiReturnStatement) { - return calculateReplacementReturnStatement(thenBranch, elseBranch, condition); - } else if (thenBranch instanceof PsiExpressionStatement && elseBranch instanceof PsiExpressionStatement) { - final PsiExpressionStatement thenStatement = (PsiExpressionStatement)thenBranch; - final PsiExpressionStatement elseStatement = (PsiExpressionStatement)elseBranch; - final PsiExpression thenExpression = thenStatement.getExpression(); - final PsiExpression elseExpression = elseStatement.getExpression(); - if (!(thenExpression instanceof PsiAssignmentExpression) || !(elseExpression instanceof PsiAssignmentExpression)) { + + @Nullable + @NonNls + static String calculateReplacementStatement(PsiIfStatement statement) { + final PsiStatement thenBranch = ControlFlowUtils.stripBraces(statement.getThenBranch()); + if (thenBranch == null) { + return null; + } + PsiStatement elseBranch = statement.getElseBranch(); + if (elseBranch == null) { + final PsiElement nextStatement = PsiTreeUtil.skipSiblingsForward(statement, PsiWhiteSpace.class); + if (nextStatement instanceof PsiStatement) { + elseBranch = (PsiStatement) nextStatement; + } + } + else { + elseBranch = ControlFlowUtils.stripBraces(elseBranch); + } + if (elseBranch == null) { + return null; + } + final PsiExpression condition = statement.getCondition(); + if (condition == null) { + return null; + } + if (thenBranch instanceof PsiReturnStatement && elseBranch instanceof PsiReturnStatement) { + return calculateReplacementReturnStatement(thenBranch, elseBranch, condition); + } + else if (thenBranch instanceof PsiExpressionStatement && elseBranch instanceof PsiExpressionStatement) { + final PsiExpressionStatement thenStatement = (PsiExpressionStatement) thenBranch; + final PsiExpressionStatement elseStatement = (PsiExpressionStatement) elseBranch; + final PsiExpression thenExpression = thenStatement.getExpression(); + final PsiExpression elseExpression = elseStatement.getExpression(); + if (!(thenExpression instanceof PsiAssignmentExpression) || !(elseExpression instanceof PsiAssignmentExpression)) { + return null; + } + final PsiAssignmentExpression thenAssignment = (PsiAssignmentExpression) thenExpression; + final PsiAssignmentExpression elseAssignment = (PsiAssignmentExpression) elseExpression; + return calculateReplacementAssignmentStatement(thenAssignment, elseAssignment, condition); + } return null; - } - final PsiAssignmentExpression thenAssignment = (PsiAssignmentExpression)thenExpression; - final PsiAssignmentExpression elseAssignment = (PsiAssignmentExpression)elseExpression; - return calculateReplacementAssignmentStatement(thenAssignment, elseAssignment, condition); } - return null; - } - private static String calculateReplacementAssignmentStatement(PsiAssignmentExpression thenAssignment, - PsiAssignmentExpression elseAssignment, PsiExpression condition) { - final PsiExpression lhs = thenAssignment.getLExpression(); - final PsiExpression thenRhs = thenAssignment.getRExpression(); - if (thenRhs == null) { - return ""; - } - final PsiExpression elseRhs = elseAssignment.getRExpression(); - if (elseRhs == null) { - return ""; - } - final PsiJavaToken token = elseAssignment.getOperationSign(); - if (BoolUtils.isTrue(thenRhs)) { - return lhs.getText() + ' ' + token.getText() + ' ' + - buildExpressionText(condition, ParenthesesUtils.OR_PRECEDENCE) + " || " + - buildExpressionText(elseRhs, ParenthesesUtils.OR_PRECEDENCE) + ';'; - } - else if (BoolUtils.isFalse(thenRhs)) { - return lhs.getText() + ' ' + token.getText() + ' ' + - buildNegatedExpressionText(condition, ParenthesesUtils.AND_PRECEDENCE) + " && " + - buildExpressionText(elseRhs, ParenthesesUtils.AND_PRECEDENCE) + ';'; - } - if (BoolUtils.isTrue(elseRhs)) { - return lhs.getText() + ' ' + token.getText() + ' ' + - buildNegatedExpressionText(condition, ParenthesesUtils.OR_PRECEDENCE) + " || " + - buildExpressionText(thenRhs, ParenthesesUtils.OR_PRECEDENCE) + ';'; - } - else { - return lhs.getText() + ' ' + token.getText() + ' ' + - buildExpressionText(condition, ParenthesesUtils.AND_PRECEDENCE) + " && " + - buildExpressionText(thenRhs, ParenthesesUtils.AND_PRECEDENCE) + ';'; + private static String calculateReplacementAssignmentStatement( + PsiAssignmentExpression thenAssignment, + PsiAssignmentExpression elseAssignment, PsiExpression condition + ) { + final PsiExpression lhs = thenAssignment.getLExpression(); + final PsiExpression thenRhs = thenAssignment.getRExpression(); + if (thenRhs == null) { + return ""; + } + final PsiExpression elseRhs = elseAssignment.getRExpression(); + if (elseRhs == null) { + return ""; + } + final PsiJavaToken token = elseAssignment.getOperationSign(); + if (BoolUtils.isTrue(thenRhs)) { + return lhs.getText() + ' ' + token.getText() + ' ' + + buildExpressionText(condition, ParenthesesUtils.OR_PRECEDENCE) + " || " + + buildExpressionText(elseRhs, ParenthesesUtils.OR_PRECEDENCE) + ';'; + } + else if (BoolUtils.isFalse(thenRhs)) { + return lhs.getText() + ' ' + token.getText() + ' ' + + buildNegatedExpressionText(condition, ParenthesesUtils.AND_PRECEDENCE) + " && " + + buildExpressionText(elseRhs, ParenthesesUtils.AND_PRECEDENCE) + ';'; + } + if (BoolUtils.isTrue(elseRhs)) { + return lhs.getText() + ' ' + token.getText() + ' ' + + buildNegatedExpressionText(condition, ParenthesesUtils.OR_PRECEDENCE) + " || " + + buildExpressionText(thenRhs, ParenthesesUtils.OR_PRECEDENCE) + ';'; + } + else { + return lhs.getText() + ' ' + token.getText() + ' ' + + buildExpressionText(condition, ParenthesesUtils.AND_PRECEDENCE) + " && " + + buildExpressionText(thenRhs, ParenthesesUtils.AND_PRECEDENCE) + ';'; + } } - } - @NonNls - private static String calculateReplacementReturnStatement(PsiStatement thenBranch, PsiStatement elseBranch, PsiExpression condition) { - final PsiReturnStatement thenReturnStatement = (PsiReturnStatement)thenBranch; - final PsiExpression thenReturnValue = thenReturnStatement.getReturnValue(); - if (thenReturnValue == null) { - return ""; - } - final PsiReturnStatement elseReturnStatement = (PsiReturnStatement)elseBranch; - final PsiExpression elseReturnValue = elseReturnStatement.getReturnValue(); - if (elseReturnValue == null) { - return ""; - } - if (BoolUtils.isTrue(thenReturnValue)) { - return "return " + buildExpressionText(condition, ParenthesesUtils.OR_PRECEDENCE) + " || " + - buildExpressionText(elseReturnValue, ParenthesesUtils.OR_PRECEDENCE) + ';'; - } - else if (BoolUtils.isFalse(thenReturnValue)) { - return "return " + buildNegatedExpressionText(condition, ParenthesesUtils.AND_PRECEDENCE) + " && " + - buildExpressionText(elseReturnValue, ParenthesesUtils.AND_PRECEDENCE) + ';'; - } - if (BoolUtils.isTrue(elseReturnValue)) { - return "return " + buildNegatedExpressionText(condition, ParenthesesUtils.OR_PRECEDENCE) + " || " + - buildExpressionText(thenReturnValue, ParenthesesUtils.OR_PRECEDENCE) + ';'; - } - else { - return "return " + buildExpressionText(condition, ParenthesesUtils.AND_PRECEDENCE) + " && " + - buildExpressionText(thenReturnValue, ParenthesesUtils.AND_PRECEDENCE) + ';'; + @NonNls + private static String calculateReplacementReturnStatement(PsiStatement thenBranch, PsiStatement elseBranch, PsiExpression condition) { + final PsiReturnStatement thenReturnStatement = (PsiReturnStatement) thenBranch; + final PsiExpression thenReturnValue = thenReturnStatement.getReturnValue(); + if (thenReturnValue == null) { + return ""; + } + final PsiReturnStatement elseReturnStatement = (PsiReturnStatement) elseBranch; + final PsiExpression elseReturnValue = elseReturnStatement.getReturnValue(); + if (elseReturnValue == null) { + return ""; + } + if (BoolUtils.isTrue(thenReturnValue)) { + return "return " + buildExpressionText(condition, ParenthesesUtils.OR_PRECEDENCE) + " || " + + buildExpressionText(elseReturnValue, ParenthesesUtils.OR_PRECEDENCE) + ';'; + } + else if (BoolUtils.isFalse(thenReturnValue)) { + return "return " + buildNegatedExpressionText(condition, ParenthesesUtils.AND_PRECEDENCE) + " && " + + buildExpressionText(elseReturnValue, ParenthesesUtils.AND_PRECEDENCE) + ';'; + } + if (BoolUtils.isTrue(elseReturnValue)) { + return "return " + buildNegatedExpressionText(condition, ParenthesesUtils.OR_PRECEDENCE) + " || " + + buildExpressionText(thenReturnValue, ParenthesesUtils.OR_PRECEDENCE) + ';'; + } + else { + return "return " + buildExpressionText(condition, ParenthesesUtils.AND_PRECEDENCE) + " && " + + buildExpressionText(thenReturnValue, ParenthesesUtils.AND_PRECEDENCE) + ';'; + } } - } - private static String buildExpressionText(PsiExpression expression, int precedence) { - final StringBuilder builder = new StringBuilder(); - if (ParenthesesUtils.getPrecedence(expression) > precedence) { - builder.append('('); - getPresentableText(expression, builder); - builder.append(')'); - } - else { - getPresentableText(expression, builder); + private static String buildExpressionText(PsiExpression expression, int precedence) { + final StringBuilder builder = new StringBuilder(); + if (ParenthesesUtils.getPrecedence(expression) > precedence) { + builder.append('('); + getPresentableText(expression, builder); + builder.append(')'); + } + else { + getPresentableText(expression, builder); + } + return builder.toString(); } - return builder.toString(); - } - private static void getPresentableText(@Nullable PsiElement element, StringBuilder builder) { - if (element == null) { - return; - } - if (element instanceof PsiWhiteSpace) { - final PsiElement prevSibling = element.getPrevSibling(); - if (prevSibling instanceof PsiComment) { - final PsiComment comment = (PsiComment)prevSibling; - if (JavaTokenType.END_OF_LINE_COMMENT.equals(comment.getTokenType())) { - builder.append('\n'); - return; - } - } - builder.append(' '); - return; - } - final PsiElement[] children = element.getChildren(); - if (children.length == 0) { - builder.append(element.getText()); - } - else { - for (PsiElement child : children) { - getPresentableText(child, builder); - } + private static void getPresentableText(@Nullable PsiElement element, StringBuilder builder) { + if (element == null) { + return; + } + if (element instanceof PsiWhiteSpace) { + final PsiElement prevSibling = element.getPrevSibling(); + if (prevSibling instanceof PsiComment) { + final PsiComment comment = (PsiComment) prevSibling; + if (JavaTokenType.END_OF_LINE_COMMENT.equals(comment.getTokenType())) { + builder.append('\n'); + return; + } + } + builder.append(' '); + return; + } + final PsiElement[] children = element.getChildren(); + if (children.length == 0) { + builder.append(element.getText()); + } + else { + for (PsiElement child : children) { + getPresentableText(child, builder); + } + } } - } - public static String buildNegatedExpressionText(@Nullable PsiExpression expression, int precedence) { - while (expression instanceof PsiParenthesizedExpression) { - final PsiParenthesizedExpression parenthesizedExpression = (PsiParenthesizedExpression)expression; - expression = parenthesizedExpression.getExpression(); - } - if (expression == null) { - return ""; - } - final StringBuilder result = new StringBuilder(); - if (BoolUtils.isNegation(expression)) { - final PsiPrefixExpression prefixExpression = (PsiPrefixExpression)expression; - final PsiExpression operand = prefixExpression.getOperand(); - final PsiExpression negated = ParenthesesUtils.stripParentheses(operand); - if (negated == null) { - return ""; - } - if (ParenthesesUtils.getPrecedence(negated) > precedence) { - result.append('('); - getPresentableText(negated, result); - result.append(')'); - } - else { - getPresentableText(negated, result); - } - } - else if (ComparisonUtils.isComparison(expression)) { - final PsiBinaryExpression binaryExpression = (PsiBinaryExpression)expression; - final IElementType tokenType = binaryExpression.getOperationTokenType(); - final String negatedComparison = ComparisonUtils.getNegatedComparison(tokenType); - final PsiExpression lhs = binaryExpression.getLOperand(); - final PsiExpression rhs = binaryExpression.getROperand(); - if (ParenthesesUtils.getPrecedence(expression) > precedence) { - result.append('('); - getPresentableText(lhs, result); - result.append(negatedComparison); - getPresentableText(rhs, result); - result.append(')'); - } - else { - getPresentableText(lhs, result); - result.append(negatedComparison); - getPresentableText(rhs, result); - } - } - else if (ParenthesesUtils.getPrecedence(expression) > ParenthesesUtils.PREFIX_PRECEDENCE) { - result.append("!("); - getPresentableText(expression, result); - result.append(')'); - } - else { - result.append('!'); - getPresentableText(expression, result); + public static String buildNegatedExpressionText(@Nullable PsiExpression expression, int precedence) { + while (expression instanceof PsiParenthesizedExpression) { + final PsiParenthesizedExpression parenthesizedExpression = (PsiParenthesizedExpression) expression; + expression = parenthesizedExpression.getExpression(); + } + if (expression == null) { + return ""; + } + final StringBuilder result = new StringBuilder(); + if (BoolUtils.isNegation(expression)) { + final PsiPrefixExpression prefixExpression = (PsiPrefixExpression) expression; + final PsiExpression operand = prefixExpression.getOperand(); + final PsiExpression negated = ParenthesesUtils.stripParentheses(operand); + if (negated == null) { + return ""; + } + if (ParenthesesUtils.getPrecedence(negated) > precedence) { + result.append('('); + getPresentableText(negated, result); + result.append(')'); + } + else { + getPresentableText(negated, result); + } + } + else if (ComparisonUtils.isComparison(expression)) { + final PsiBinaryExpression binaryExpression = (PsiBinaryExpression) expression; + final IElementType tokenType = binaryExpression.getOperationTokenType(); + final String negatedComparison = ComparisonUtils.getNegatedComparison(tokenType); + final PsiExpression lhs = binaryExpression.getLOperand(); + final PsiExpression rhs = binaryExpression.getROperand(); + if (ParenthesesUtils.getPrecedence(expression) > precedence) { + result.append('('); + getPresentableText(lhs, result); + result.append(negatedComparison); + getPresentableText(rhs, result); + result.append(')'); + } + else { + getPresentableText(lhs, result); + result.append(negatedComparison); + getPresentableText(rhs, result); + } + } + else if (ParenthesesUtils.getPrecedence(expression) > ParenthesesUtils.PREFIX_PRECEDENCE) { + result.append("!("); + getPresentableText(expression, result); + result.append(')'); + } + else { + result.append('!'); + getPresentableText(expression, result); + } + return result.toString(); } - return result.toString(); - } - @Override - public InspectionGadgetsFix buildFix(Object... infos) { - return new SimplifiableIfStatementFix(); - } - - private static class SimplifiableIfStatementFix extends InspectionGadgetsFix { @Override - @Nonnull - public String getName() { - return InspectionGadgetsLocalize.constantConditionalExpressionSimplifyQuickfix().get(); + public InspectionGadgetsFix buildFix(Object... infos) { + return new SimplifiableIfStatementFix(); } - @Override - public void doFix(Project project, ProblemDescriptor descriptor) - throws IncorrectOperationException { - final PsiElement element = descriptor.getPsiElement(); - final PsiIfStatement ifStatement = (PsiIfStatement)element.getParent(); - final String newStatement = calculateReplacementStatement(ifStatement); - if (newStatement == null) { - return; - } - if (ifStatement.getElseBranch() == null) { - final PsiElement nextStatement = PsiTreeUtil.skipSiblingsForward(ifStatement, PsiWhiteSpace.class); - if (nextStatement != null) { - nextStatement.delete(); - } - } - replaceStatement(ifStatement, newStatement); + private static class SimplifiableIfStatementFix extends InspectionGadgetsFix { + @Nonnull + @Override + public LocalizeValue getName() { + return InspectionGadgetsLocalize.constantConditionalExpressionSimplifyQuickfix(); + } + + @Override + public void doFix(Project project, ProblemDescriptor descriptor) + throws IncorrectOperationException { + final PsiElement element = descriptor.getPsiElement(); + final PsiIfStatement ifStatement = (PsiIfStatement) element.getParent(); + final String newStatement = calculateReplacementStatement(ifStatement); + if (newStatement == null) { + return; + } + if (ifStatement.getElseBranch() == null) { + final PsiElement nextStatement = PsiTreeUtil.skipSiblingsForward(ifStatement, PsiWhiteSpace.class); + if (nextStatement != null) { + nextStatement.delete(); + } + } + replaceStatement(ifStatement, newStatement); + } } - } - private static class SimplifiableIfStatementVisitor extends BaseInspectionVisitor { + private static class SimplifiableIfStatementVisitor extends BaseInspectionVisitor { - @Override - public void visitIfStatement(PsiIfStatement statement) { - super.visitIfStatement(statement); - if (statement.getCondition() == null) { - return; - } - if (!(isReplaceableAssignment(statement) || isReplaceableReturn(statement))) { - return; - } - registerStatementError(statement, statement); - } + @Override + public void visitIfStatement(PsiIfStatement statement) { + super.visitIfStatement(statement); + if (statement.getCondition() == null) { + return; + } + if (!(isReplaceableAssignment(statement) || isReplaceableReturn(statement))) { + return; + } + registerStatementError(statement, statement); + } - public static boolean isReplaceableReturn(PsiIfStatement ifStatement) { - PsiStatement thenBranch = ifStatement.getThenBranch(); - thenBranch = ControlFlowUtils.stripBraces(thenBranch); - PsiStatement elseBranch = ifStatement.getElseBranch(); - elseBranch = ControlFlowUtils.stripBraces(elseBranch); - if (elseBranch == null) { - final PsiElement nextStatement = PsiTreeUtil.skipSiblingsForward(ifStatement, PsiWhiteSpace.class); - if (nextStatement instanceof PsiStatement) { - elseBranch = (PsiStatement)nextStatement; - } - } - if (!(thenBranch instanceof PsiReturnStatement) || !(elseBranch instanceof PsiReturnStatement)) { - return false; - } - final PsiExpression thenReturn = ((PsiReturnStatement)thenBranch).getReturnValue(); - if (thenReturn == null) { - return false; - } - final PsiType thenType = thenReturn.getType(); - if (!PsiType.BOOLEAN.equals(thenType)) { - return false; - } - final PsiExpression elseReturn = ((PsiReturnStatement)elseBranch).getReturnValue(); - if (elseReturn == null) { - return false; - } - final PsiType elseType = elseReturn.getType(); - if (!PsiType.BOOLEAN.equals(elseType)) { - return false; - } - final boolean thenConstant = BoolUtils.isFalse(thenReturn) || BoolUtils.isTrue(thenReturn); - final boolean elseConstant = BoolUtils.isFalse(elseReturn) || BoolUtils.isTrue(elseReturn); - return thenConstant != elseConstant; - } + public static boolean isReplaceableReturn(PsiIfStatement ifStatement) { + PsiStatement thenBranch = ifStatement.getThenBranch(); + thenBranch = ControlFlowUtils.stripBraces(thenBranch); + PsiStatement elseBranch = ifStatement.getElseBranch(); + elseBranch = ControlFlowUtils.stripBraces(elseBranch); + if (elseBranch == null) { + final PsiElement nextStatement = PsiTreeUtil.skipSiblingsForward(ifStatement, PsiWhiteSpace.class); + if (nextStatement instanceof PsiStatement) { + elseBranch = (PsiStatement) nextStatement; + } + } + if (!(thenBranch instanceof PsiReturnStatement) || !(elseBranch instanceof PsiReturnStatement)) { + return false; + } + final PsiExpression thenReturn = ((PsiReturnStatement) thenBranch).getReturnValue(); + if (thenReturn == null) { + return false; + } + final PsiType thenType = thenReturn.getType(); + if (!PsiType.BOOLEAN.equals(thenType)) { + return false; + } + final PsiExpression elseReturn = ((PsiReturnStatement) elseBranch).getReturnValue(); + if (elseReturn == null) { + return false; + } + final PsiType elseType = elseReturn.getType(); + if (!PsiType.BOOLEAN.equals(elseType)) { + return false; + } + final boolean thenConstant = BoolUtils.isFalse(thenReturn) || BoolUtils.isTrue(thenReturn); + final boolean elseConstant = BoolUtils.isFalse(elseReturn) || BoolUtils.isTrue(elseReturn); + return thenConstant != elseConstant; + } - public static boolean isReplaceableAssignment(PsiIfStatement ifStatement) { - PsiStatement thenBranch = ifStatement.getThenBranch(); - if (thenBranch == null) { - return false; - } - thenBranch = ControlFlowUtils.stripBraces(thenBranch); - if (thenBranch == null || !isAssignment(thenBranch)) { - return false; - } - PsiStatement elseBranch = ifStatement.getElseBranch(); - if (elseBranch == null) { - return false; - } - elseBranch = ControlFlowUtils.stripBraces(elseBranch); - if (elseBranch == null || !isAssignment(elseBranch)) { - return false; - } - final PsiExpressionStatement thenStatement = (PsiExpressionStatement)thenBranch; - final PsiAssignmentExpression thenExpression = (PsiAssignmentExpression)thenStatement.getExpression(); - final PsiExpressionStatement elseStatement = (PsiExpressionStatement)elseBranch; - final PsiAssignmentExpression elseExpression = (PsiAssignmentExpression)elseStatement.getExpression(); - final IElementType elseTokenType = elseExpression.getOperationTokenType(); - if (!thenExpression.getOperationTokenType().equals(elseTokenType)) { - return false; - } - final PsiExpression thenRhs = thenExpression.getRExpression(); - if (thenRhs == null) { - return false; - } - final PsiType thenRhsType = thenRhs.getType(); - if (!PsiType.BOOLEAN.equals(thenRhsType)) { - return false; - } - final PsiExpression elseRhs = elseExpression.getRExpression(); - if (elseRhs == null) { - return false; - } - final PsiType elseRhsType = elseRhs.getType(); - if (!PsiType.BOOLEAN.equals(elseRhsType)) { - return false; - } - final boolean thenConstant = BoolUtils.isFalse(thenRhs) || BoolUtils.isTrue(thenRhs); - final boolean elseConstant = BoolUtils.isFalse(elseRhs) || BoolUtils.isTrue(elseRhs); - if (thenConstant == elseConstant) { - return false; - } - final PsiExpression thenLhs = thenExpression.getLExpression(); - final PsiExpression elseLhs = elseExpression.getLExpression(); - return EquivalenceChecker.getCanonicalPsiEquivalence().expressionsAreEquivalent(thenLhs, elseLhs); - } + public static boolean isReplaceableAssignment(PsiIfStatement ifStatement) { + PsiStatement thenBranch = ifStatement.getThenBranch(); + if (thenBranch == null) { + return false; + } + thenBranch = ControlFlowUtils.stripBraces(thenBranch); + if (thenBranch == null || !isAssignment(thenBranch)) { + return false; + } + PsiStatement elseBranch = ifStatement.getElseBranch(); + if (elseBranch == null) { + return false; + } + elseBranch = ControlFlowUtils.stripBraces(elseBranch); + if (elseBranch == null || !isAssignment(elseBranch)) { + return false; + } + final PsiExpressionStatement thenStatement = (PsiExpressionStatement) thenBranch; + final PsiAssignmentExpression thenExpression = (PsiAssignmentExpression) thenStatement.getExpression(); + final PsiExpressionStatement elseStatement = (PsiExpressionStatement) elseBranch; + final PsiAssignmentExpression elseExpression = (PsiAssignmentExpression) elseStatement.getExpression(); + final IElementType elseTokenType = elseExpression.getOperationTokenType(); + if (!thenExpression.getOperationTokenType().equals(elseTokenType)) { + return false; + } + final PsiExpression thenRhs = thenExpression.getRExpression(); + if (thenRhs == null) { + return false; + } + final PsiType thenRhsType = thenRhs.getType(); + if (!PsiType.BOOLEAN.equals(thenRhsType)) { + return false; + } + final PsiExpression elseRhs = elseExpression.getRExpression(); + if (elseRhs == null) { + return false; + } + final PsiType elseRhsType = elseRhs.getType(); + if (!PsiType.BOOLEAN.equals(elseRhsType)) { + return false; + } + final boolean thenConstant = BoolUtils.isFalse(thenRhs) || BoolUtils.isTrue(thenRhs); + final boolean elseConstant = BoolUtils.isFalse(elseRhs) || BoolUtils.isTrue(elseRhs); + if (thenConstant == elseConstant) { + return false; + } + final PsiExpression thenLhs = thenExpression.getLExpression(); + final PsiExpression elseLhs = elseExpression.getLExpression(); + return EquivalenceChecker.getCanonicalPsiEquivalence().expressionsAreEquivalent(thenLhs, elseLhs); + } - public static boolean isAssignment(@Nullable PsiStatement statement) { - if (!(statement instanceof PsiExpressionStatement)) { - return false; - } - final PsiExpressionStatement expressionStatement = (PsiExpressionStatement)statement; - final PsiExpression expression = expressionStatement.getExpression(); - return expression instanceof PsiAssignmentExpression; + public static boolean isAssignment(@Nullable PsiStatement statement) { + if (!(statement instanceof PsiExpressionStatement)) { + return false; + } + final PsiExpressionStatement expressionStatement = (PsiExpressionStatement) statement; + final PsiExpression expression = expressionStatement.getExpression(); + return expression instanceof PsiAssignmentExpression; + } } - } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/j2me/SingleCharacterStartsWithInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/j2me/SingleCharacterStartsWithInspection.java index 2f3134f821..8ade42194d 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/j2me/SingleCharacterStartsWithInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/j2me/SingleCharacterStartsWithInspection.java @@ -26,6 +26,7 @@ import consulo.language.editor.inspection.ProblemDescriptor; import consulo.language.psi.PsiElement; import consulo.language.util.IncorrectOperationException; +import consulo.localize.LocalizeValue; import consulo.project.Project; import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; @@ -33,119 +34,109 @@ @ExtensionImpl public class SingleCharacterStartsWithInspection extends BaseInspection { - - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.singleCharacterStartswithDisplayName().get(); - } - - @Nonnull - protected String buildErrorString(Object... infos) { - return InspectionGadgetsLocalize.singleCharacterStartswithProblemDescriptor().get(); - } - - @Nullable - protected InspectionGadgetsFix buildFix(Object... infos) { - return new SingleCharacterStartsWithFix(); - } - - private static class SingleCharacterStartsWithFix - extends InspectionGadgetsFix { + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.singleCharacterStartswithDisplayName(); + } @Nonnull - public String getName() { - return InspectionGadgetsLocalize.singleCharacterStartswithQuickfix().get(); + protected String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.singleCharacterStartswithProblemDescriptor().get(); } - protected void doFix(Project project, ProblemDescriptor descriptor) - throws IncorrectOperationException { - final PsiElement element = descriptor.getPsiElement(); - final PsiReferenceExpression methodExpression = - (PsiReferenceExpression)element.getParent(); - final PsiMethodCallExpression methodCall = - (PsiMethodCallExpression)methodExpression.getParent(); - final PsiElement qualifier = methodExpression.getQualifier(); - if (qualifier == null) { - return; - } - final PsiExpressionList argumentList = methodCall.getArgumentList(); - final PsiExpression[] expressions = argumentList.getExpressions(); - final PsiExpression expression = expressions[0]; - final String expressionText = expression.getText(); - String character = expressionText.substring(1, - expressionText.length() - 1); - if (character.equals("'")) { - character = "\\'"; - } - final String qualifierText = qualifier.getText(); - @NonNls final String newExpression; - final String referenceName = methodExpression.getReferenceName(); - if (HardcodedMethodConstants.STARTS_WITH.equals(referenceName)) { - newExpression = qualifierText + ".length() > 0 && " + - qualifierText + ".charAt(0) == '" + character + '\''; - } - else { - newExpression = qualifierText + ".length() > 0 && " + - qualifierText + ".charAt(" + qualifierText + - ".length() - 1) == '" + character + '\''; - } - replaceExpression(methodCall, newExpression); + @Nullable + protected InspectionGadgetsFix buildFix(Object... infos) { + return new SingleCharacterStartsWithFix(); } - } - public BaseInspectionVisitor buildVisitor() { - return new SingleCharacterStartsWithVisitor(); - } + private static class SingleCharacterStartsWithFix extends InspectionGadgetsFix { + @Nonnull + @Override + public LocalizeValue getName() { + return InspectionGadgetsLocalize.singleCharacterStartswithQuickfix(); + } - private static class SingleCharacterStartsWithVisitor - extends BaseInspectionVisitor { + protected void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { + final PsiElement element = descriptor.getPsiElement(); + final PsiReferenceExpression methodExpression = (PsiReferenceExpression) element.getParent(); + final PsiMethodCallExpression methodCall = (PsiMethodCallExpression) methodExpression.getParent(); + final PsiElement qualifier = methodExpression.getQualifier(); + if (qualifier == null) { + return; + } + final PsiExpressionList argumentList = methodCall.getArgumentList(); + final PsiExpression[] expressions = argumentList.getExpressions(); + final PsiExpression expression = expressions[0]; + final String expressionText = expression.getText(); + String character = expressionText.substring(1, expressionText.length() - 1); + if (character.equals("'")) { + character = "\\'"; + } + final String qualifierText = qualifier.getText(); + @NonNls final String newExpression; + final String referenceName = methodExpression.getReferenceName(); + if (HardcodedMethodConstants.STARTS_WITH.equals(referenceName)) { + newExpression = qualifierText + ".length() > 0 && " + + qualifierText + ".charAt(0) == '" + character + '\''; + } + else { + newExpression = qualifierText + ".length() > 0 && " + + qualifierText + ".charAt(" + qualifierText + + ".length() - 1) == '" + character + '\''; + } + replaceExpression(methodCall, newExpression); + } + } - @Override - public void visitMethodCallExpression( - @Nonnull PsiMethodCallExpression call) { - super.visitMethodCallExpression(call); - final PsiReferenceExpression methodExpression = - call.getMethodExpression(); - final String methodName = methodExpression.getReferenceName(); - if (!HardcodedMethodConstants.STARTS_WITH.equals(methodName) && - !HardcodedMethodConstants.ENDS_WITH.equals(methodName)) { - return; - } - final PsiExpressionList argumentList = call.getArgumentList(); - final PsiExpression[] args = argumentList.getExpressions(); - if (args.length != 1 && args.length != 2) { - return; - } - if (!isSingleCharacterStringLiteral(args[0])) { - return; - } - final PsiExpression qualifier = - methodExpression.getQualifierExpression(); - if (qualifier == null) { - return; - } - final PsiType type = qualifier.getType(); - if (!TypeUtils.isJavaLangString(type)) { - return; - } - registerMethodCallError(call); + public BaseInspectionVisitor buildVisitor() { + return new SingleCharacterStartsWithVisitor(); } - private static boolean isSingleCharacterStringLiteral( - PsiExpression arg) { - final PsiType type = arg.getType(); - if (!TypeUtils.isJavaLangString(type)) { - return false; - } - if (!(arg instanceof PsiLiteralExpression)) { - return false; - } - final PsiLiteralExpression literal = (PsiLiteralExpression)arg; - final String value = (String)literal.getValue(); - if (value == null) { - return false; - } - return value.length() == 1; + private static class SingleCharacterStartsWithVisitor extends BaseInspectionVisitor { + @Override + public void visitMethodCallExpression(@Nonnull PsiMethodCallExpression call) { + super.visitMethodCallExpression(call); + final PsiReferenceExpression methodExpression = call.getMethodExpression(); + final String methodName = methodExpression.getReferenceName(); + if (!HardcodedMethodConstants.STARTS_WITH.equals(methodName) && + !HardcodedMethodConstants.ENDS_WITH.equals(methodName)) { + return; + } + final PsiExpressionList argumentList = call.getArgumentList(); + final PsiExpression[] args = argumentList.getExpressions(); + if (args.length != 1 && args.length != 2) { + return; + } + if (!isSingleCharacterStringLiteral(args[0])) { + return; + } + final PsiExpression qualifier = + methodExpression.getQualifierExpression(); + if (qualifier == null) { + return; + } + final PsiType type = qualifier.getType(); + if (!TypeUtils.isJavaLangString(type)) { + return; + } + registerMethodCallError(call); + } + + private static boolean isSingleCharacterStringLiteral(PsiExpression arg) { + final PsiType type = arg.getType(); + if (!TypeUtils.isJavaLangString(type)) { + return false; + } + if (!(arg instanceof PsiLiteralExpression)) { + return false; + } + final PsiLiteralExpression literal = (PsiLiteralExpression) arg; + final String value = (String) literal.getValue(); + if (value == null) { + return false; + } + return value.length() == 1; + } } - } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/javabeans/ClassWithoutConstructorInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/javabeans/ClassWithoutConstructorInspection.java index e5084b8b89..c49c418607 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/javabeans/ClassWithoutConstructorInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/javabeans/ClassWithoutConstructorInspection.java @@ -25,95 +25,90 @@ import consulo.language.editor.inspection.ProblemDescriptor; import consulo.language.psi.PsiElement; import consulo.language.util.IncorrectOperationException; +import consulo.localize.LocalizeValue; import consulo.project.Project; import jakarta.annotation.Nonnull; @ExtensionImpl public class ClassWithoutConstructorInspection extends BaseInspection { + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.classWithoutConstructorDisplayName(); + } - @Override - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.classWithoutConstructorDisplayName().get(); - } - - @Override - @Nonnull - protected String buildErrorString(Object... infos) { - return InspectionGadgetsLocalize.classWithoutConstructorProblemDescriptor().get(); - } - - @Override - protected InspectionGadgetsFix buildFix(Object... infos) { - return new ClassWithoutConstructorFix(); - } - - private static class ClassWithoutConstructorFix - extends InspectionGadgetsFix { - + @Override @Nonnull - public String getName() { - return InspectionGadgetsLocalize.classWithoutConstructorCreateQuickfix().get(); + protected String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.classWithoutConstructorProblemDescriptor().get(); } @Override - public void doFix(Project project, ProblemDescriptor descriptor) - throws IncorrectOperationException { - final PsiElement classIdentifier = descriptor.getPsiElement(); - final PsiClass aClass = (PsiClass)classIdentifier.getParent(); - final PsiElementFactory factory = - JavaPsiFacade.getElementFactory(project); - final PsiMethod constructor = factory.createConstructor(); - final PsiModifierList modifierList = constructor.getModifierList(); - if (aClass == null) { - return; - } - if (aClass.hasModifierProperty(PsiModifier.PRIVATE)) { - modifierList.setModifierProperty(PsiModifier.PUBLIC, false); - modifierList.setModifierProperty(PsiModifier.PRIVATE, true); - } - else if (aClass.hasModifierProperty(PsiModifier.PROTECTED)) { - modifierList.setModifierProperty(PsiModifier.PUBLIC, false); - modifierList.setModifierProperty(PsiModifier.PROTECTED, true); - } - else if (aClass.hasModifierProperty(PsiModifier.ABSTRACT)) { - modifierList.setModifierProperty(PsiModifier.PUBLIC, false); - modifierList.setModifierProperty(PsiModifier.PROTECTED, true); - } - else if (!aClass.hasModifierProperty(PsiModifier.PUBLIC)) { - modifierList.setModifierProperty(PsiModifier.PUBLIC, false); - } - aClass.add(constructor); - final CodeStyleManager styleManager = - CodeStyleManager.getInstance(project); - styleManager.reformat(constructor); + protected InspectionGadgetsFix buildFix(Object... infos) { + return new ClassWithoutConstructorFix(); } - } - @Override - public BaseInspectionVisitor buildVisitor() { - return new ClassWithoutConstructorVisitor(); - } + private static class ClassWithoutConstructorFix extends InspectionGadgetsFix { + @Nonnull + public LocalizeValue getName() { + return InspectionGadgetsLocalize.classWithoutConstructorCreateQuickfix(); + } - private static class ClassWithoutConstructorVisitor - extends BaseInspectionVisitor { + @Override + public void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { + final PsiElement classIdentifier = descriptor.getPsiElement(); + final PsiClass aClass = (PsiClass) classIdentifier.getParent(); + final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project); + final PsiMethod constructor = factory.createConstructor(); + final PsiModifierList modifierList = constructor.getModifierList(); + if (aClass == null) { + return; + } + if (aClass.hasModifierProperty(PsiModifier.PRIVATE)) { + modifierList.setModifierProperty(PsiModifier.PUBLIC, false); + modifierList.setModifierProperty(PsiModifier.PRIVATE, true); + } + else if (aClass.hasModifierProperty(PsiModifier.PROTECTED)) { + modifierList.setModifierProperty(PsiModifier.PUBLIC, false); + modifierList.setModifierProperty(PsiModifier.PROTECTED, true); + } + else if (aClass.hasModifierProperty(PsiModifier.ABSTRACT)) { + modifierList.setModifierProperty(PsiModifier.PUBLIC, false); + modifierList.setModifierProperty(PsiModifier.PROTECTED, true); + } + else if (!aClass.hasModifierProperty(PsiModifier.PUBLIC)) { + modifierList.setModifierProperty(PsiModifier.PUBLIC, false); + } + aClass.add(constructor); + final CodeStyleManager styleManager = CodeStyleManager.getInstance(project); + styleManager.reformat(constructor); + } + } @Override - public void visitClass(@Nonnull PsiClass aClass) { - // no call to super, so it doesn't drill down - if (aClass.isInterface() || aClass.isEnum() || - aClass.isAnnotationType() /*|| JspPsiUtil.isInJspFile(aClass)*/) { - return; - } - if (aClass instanceof PsiTypeParameter || - aClass instanceof PsiAnonymousClass) { - return; - } - final PsiMethod[] constructors = aClass.getConstructors(); - if (constructors.length > 0) { - return; - } - registerClassError(aClass); + public BaseInspectionVisitor buildVisitor() { + return new ClassWithoutConstructorVisitor(); + } + + private static class ClassWithoutConstructorVisitor + extends BaseInspectionVisitor { + + @Override + public void visitClass(@Nonnull PsiClass aClass) { + // no call to super, so it doesn't drill down + if (aClass.isInterface() || aClass.isEnum() || + aClass.isAnnotationType() /*|| JspPsiUtil.isInJspFile(aClass)*/) { + return; + } + if (aClass instanceof PsiTypeParameter || + aClass instanceof PsiAnonymousClass) { + return; + } + final PsiMethod[] constructors = aClass.getConstructors(); + if (constructors.length > 0) { + return; + } + registerClassError(aClass); + } } - } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/javabeans/ClassWithoutNoArgConstructorInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/javabeans/ClassWithoutNoArgConstructorInspection.java index 155a5706ac..a679cea6bb 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/javabeans/ClassWithoutNoArgConstructorInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/javabeans/ClassWithoutNoArgConstructorInspection.java @@ -31,69 +31,69 @@ @ExtensionImpl public class ClassWithoutNoArgConstructorInspection extends BaseInspection { + /** + * @noinspection PublicField + */ + public boolean m_ignoreClassesWithNoConstructors = true; - /** - * @noinspection PublicField - */ - public boolean m_ignoreClassesWithNoConstructors = true; - - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.classWithoutNoArgConstructorDisplayName().get(); - } + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.classWithoutNoArgConstructorDisplayName(); + } - public JComponent createOptionsPanel() { - LocalizeValue message = InspectionGadgetsLocalize.classWithoutNoArgConstructorIgnoreOption(); - return new SingleCheckboxOptionsPanel(message.get(), this, "m_ignoreClassesWithNoConstructors"); - } + public JComponent createOptionsPanel() { + LocalizeValue message = InspectionGadgetsLocalize.classWithoutNoArgConstructorIgnoreOption(); + return new SingleCheckboxOptionsPanel(message.get(), this, "m_ignoreClassesWithNoConstructors"); + } - @Nonnull - protected String buildErrorString(Object... infos) { - return InspectionGadgetsLocalize.classWithoutNoArgConstructorProblemDescriptor().get(); - } + @Nonnull + protected String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.classWithoutNoArgConstructorProblemDescriptor().get(); + } - public BaseInspectionVisitor buildVisitor() { - return new ClassWithoutNoArgConstructorVisitor(); - } + public BaseInspectionVisitor buildVisitor() { + return new ClassWithoutNoArgConstructorVisitor(); + } - private class ClassWithoutNoArgConstructorVisitor - extends BaseInspectionVisitor { + private class ClassWithoutNoArgConstructorVisitor + extends BaseInspectionVisitor { - @Override - public void visitClass(@Nonnull PsiClass aClass) { - // no call to super, so it doesn't drill down - if (aClass.isInterface() || aClass.isEnum() || - aClass.isAnnotationType()) { - return; - } - if (aClass instanceof PsiTypeParameter) { - return; - } - if (m_ignoreClassesWithNoConstructors && - !classHasConstructor(aClass)) { - return; - } - if (classHasNoArgConstructor(aClass)) { - return; - } - registerClassError(aClass); - } + @Override + public void visitClass(@Nonnull PsiClass aClass) { + // no call to super, so it doesn't drill down + if (aClass.isInterface() || aClass.isEnum() || + aClass.isAnnotationType()) { + return; + } + if (aClass instanceof PsiTypeParameter) { + return; + } + if (m_ignoreClassesWithNoConstructors && + !classHasConstructor(aClass)) { + return; + } + if (classHasNoArgConstructor(aClass)) { + return; + } + registerClassError(aClass); + } - private boolean classHasNoArgConstructor(PsiClass aClass) { - final PsiMethod[] constructors = aClass.getConstructors(); - for (final PsiMethod constructor : constructors) { - final PsiParameterList parameterList = - constructor.getParameterList(); - if (parameterList.getParametersCount() == 0) { - return true; + private boolean classHasNoArgConstructor(PsiClass aClass) { + final PsiMethod[] constructors = aClass.getConstructors(); + for (final PsiMethod constructor : constructors) { + final PsiParameterList parameterList = + constructor.getParameterList(); + if (parameterList.getParametersCount() == 0) { + return true; + } + } + return false; } - } - return false; - } - private boolean classHasConstructor(PsiClass aClass) { - final PsiMethod[] constructors = aClass.getConstructors(); - return constructors.length != 0; + private boolean classHasConstructor(PsiClass aClass) { + final PsiMethod[] constructors = aClass.getConstructors(); + return constructors.length != 0; + } } - } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/javabeans/FieldHasSetterButNoGetterInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/javabeans/FieldHasSetterButNoGetterInspection.java index 4712ac02f4..78e458e364 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/javabeans/FieldHasSetterButNoGetterInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/javabeans/FieldHasSetterButNoGetterInspection.java @@ -24,43 +24,43 @@ import com.siyeh.ig.BaseInspectionVisitor; import com.siyeh.localize.InspectionGadgetsLocalize; import consulo.annotation.component.ExtensionImpl; +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; @ExtensionImpl public class FieldHasSetterButNoGetterInspection extends BaseInspection { + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.fieldHasSetterButNoGetterDisplayName(); + } - @Override - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.fieldHasSetterButNoGetterDisplayName().get(); - } - - @Override - @Nonnull - protected String buildErrorString(Object... infos) { - return InspectionGadgetsLocalize.fieldHasSetterButNoGetterProblemDescriptor().get(); - } - - @Override - public BaseInspectionVisitor buildVisitor() { - return new FieldHasSetterButNoGetterVisitor(); - } + @Override + @Nonnull + protected String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.fieldHasSetterButNoGetterProblemDescriptor().get(); + } - private static class FieldHasSetterButNoGetterVisitor extends BaseInspectionVisitor { @Override - public void visitField(@Nonnull PsiField field) { - final String propertyName = PropertyUtil.suggestPropertyName(field); - final boolean isStatic = field.hasModifierProperty(PsiModifier.STATIC); - final PsiClass containingClass = field.getContainingClass(); - final PsiMethod setter = PropertyUtil.findPropertySetter(containingClass, propertyName, isStatic, false); - if (setter == null) { - return; - } - final PsiMethod getter = PropertyUtil.findPropertyGetter(containingClass, propertyName, isStatic, false); - if (getter != null) { - return; - } - registerFieldError(field); + public BaseInspectionVisitor buildVisitor() { + return new FieldHasSetterButNoGetterVisitor(); + } + + private static class FieldHasSetterButNoGetterVisitor extends BaseInspectionVisitor { + @Override + public void visitField(@Nonnull PsiField field) { + final String propertyName = PropertyUtil.suggestPropertyName(field); + final boolean isStatic = field.hasModifierProperty(PsiModifier.STATIC); + final PsiClass containingClass = field.getContainingClass(); + final PsiMethod setter = PropertyUtil.findPropertySetter(containingClass, propertyName, isStatic, false); + if (setter == null) { + return; + } + final PsiMethod getter = PropertyUtil.findPropertyGetter(containingClass, propertyName, isStatic, false); + if (getter != null) { + return; + } + registerFieldError(field); + } } - } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/javadoc/HtmlTagCanBeJavadocTagInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/javadoc/HtmlTagCanBeJavadocTagInspection.java index 1f727013f9..20cf150c89 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/javadoc/HtmlTagCanBeJavadocTagInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/javadoc/HtmlTagCanBeJavadocTagInspection.java @@ -31,155 +31,154 @@ import consulo.language.psi.PsiElement; import consulo.language.psi.util.PsiTreeUtil; import consulo.language.util.IncorrectOperationException; +import consulo.localize.LocalizeValue; import consulo.project.Project; import jakarta.annotation.Nonnull; -import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NonNls; @ExtensionImpl public class HtmlTagCanBeJavadocTagInspection extends BaseInspection { - - @Nls - @Nonnull - @Override - public String getDisplayName() { - return InspectionGadgetsLocalize.htmlTagCanBeJavadocTagDisplayName().get(); - } - - @Nonnull - @Override - protected String buildErrorString(Object... infos) { - return InspectionGadgetsLocalize.htmlTagCanBeJavadocTagProblemDescriptor().get(); - } - - @Override - protected InspectionGadgetsFix buildFix(Object... infos) { - final int offset = ((Integer)infos[0]).intValue(); - return new HtmlTagCanBeJavaDocTagFix(offset); - } - - private static class HtmlTagCanBeJavaDocTagFix extends InspectionGadgetsFix { - - private final int startIndex; - - public HtmlTagCanBeJavaDocTagFix(int startIndex) { - this.startIndex = startIndex; + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.htmlTagCanBeJavadocTagDisplayName(); } - @Override @Nonnull - public String getName() { - return InspectionGadgetsLocalize.htmlTagCanBeJavadocTagQuickfix().get(); + @Override + protected String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.htmlTagCanBeJavadocTagProblemDescriptor().get(); } @Override - protected void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { - final PsiElement element = descriptor.getPsiElement(); - final PsiDocComment comment = PsiTreeUtil.getParentOfType(element, PsiDocComment.class); - if (comment == null) { - return; - } - @NonNls final StringBuilder newCommentText = new StringBuilder(); - buildNewCommentText(comment, element, false, newCommentText); - final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project); - final PsiDocComment newComment = factory.createDocCommentFromText(newCommentText.toString()); - comment.replace(newComment); + protected InspectionGadgetsFix buildFix(Object... infos) { + final int offset = ((Integer) infos[0]).intValue(); + return new HtmlTagCanBeJavaDocTagFix(offset); } - private boolean buildNewCommentText(PsiElement element, PsiElement elementToReplace, boolean missingEndTag, - @NonNls StringBuilder newCommentText) { - final PsiElement[] children = element.getChildren(); - if (children.length != 0) { - for (PsiElement child : children) { - missingEndTag = buildNewCommentText(child, elementToReplace, missingEndTag, newCommentText); + private static class HtmlTagCanBeJavaDocTagFix extends InspectionGadgetsFix { + private final int startIndex; + + public HtmlTagCanBeJavaDocTagFix(int startIndex) { + this.startIndex = startIndex; } - return missingEndTag; - } - @NonNls final String text = element.getText(); - if (element != elementToReplace) { - if (missingEndTag) { - final int endIndex = text.indexOf(""); - if (endIndex >= 0) { - final String codeText = text.substring(0, endIndex); - newCommentText.append(codeText); - newCommentText.append('}'); - newCommentText.append(text.substring(endIndex + 7)); - return false; - } + + @Nonnull + @Override + public LocalizeValue getName() { + return InspectionGadgetsLocalize.htmlTagCanBeJavadocTagQuickfix(); } - newCommentText.append(text); - } - else { - newCommentText.append(text.substring(0, startIndex)); - newCommentText.append("{@code "); - final int endIndex = text.indexOf("", startIndex); - if (endIndex >= 0) { - final String codeText = text.substring(startIndex + 6, endIndex); - newCommentText.append(codeText); - //StringUtil.replace(codeText, "}", "}")); - newCommentText.append('}'); - newCommentText.append(text.substring(endIndex + 7)); + + @Override + protected void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { + final PsiElement element = descriptor.getPsiElement(); + final PsiDocComment comment = PsiTreeUtil.getParentOfType(element, PsiDocComment.class); + if (comment == null) { + return; + } + @NonNls final StringBuilder newCommentText = new StringBuilder(); + buildNewCommentText(comment, element, false, newCommentText); + final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project); + final PsiDocComment newComment = factory.createDocCommentFromText(newCommentText.toString()); + comment.replace(newComment); } - else { - final String codeText = text.substring(startIndex + 6); - newCommentText.append(codeText); - //StringUtil.replace(codeText, "}", "}")); - return true; + + private boolean buildNewCommentText( + PsiElement element, PsiElement elementToReplace, boolean missingEndTag, + @NonNls StringBuilder newCommentText + ) { + final PsiElement[] children = element.getChildren(); + if (children.length != 0) { + for (PsiElement child : children) { + missingEndTag = buildNewCommentText(child, elementToReplace, missingEndTag, newCommentText); + } + return missingEndTag; + } + @NonNls final String text = element.getText(); + if (element != elementToReplace) { + if (missingEndTag) { + final int endIndex = text.indexOf(""); + if (endIndex >= 0) { + final String codeText = text.substring(0, endIndex); + newCommentText.append(codeText); + newCommentText.append('}'); + newCommentText.append(text.substring(endIndex + 7)); + return false; + } + } + newCommentText.append(text); + } + else { + newCommentText.append(text.substring(0, startIndex)); + newCommentText.append("{@code "); + final int endIndex = text.indexOf("", startIndex); + if (endIndex >= 0) { + final String codeText = text.substring(startIndex + 6, endIndex); + newCommentText.append(codeText); + //StringUtil.replace(codeText, "}", "}")); + newCommentText.append('}'); + newCommentText.append(text.substring(endIndex + 7)); + } + else { + final String codeText = text.substring(startIndex + 6); + newCommentText.append(codeText); + //StringUtil.replace(codeText, "}", "}")); + return true; + } + } + return missingEndTag; } - } - return missingEndTag; } - } - @Override - public BaseInspectionVisitor buildVisitor() { - return new HtmlTagCanBeJavaDocTagVisitor(); - } + @Override + public BaseInspectionVisitor buildVisitor() { + return new HtmlTagCanBeJavaDocTagVisitor(); + } - private static class HtmlTagCanBeJavaDocTagVisitor extends BaseInspectionVisitor { + private static class HtmlTagCanBeJavaDocTagVisitor extends BaseInspectionVisitor { - @Override - public void visitDocToken(PsiDocToken token) { - super.visitDocToken(token); - if (!PsiUtil.isLanguageLevel5OrHigher(token)) { - return; - } - final IElementType tokenType = token.getTokenType(); - if (!JavaDocTokenType.DOC_COMMENT_DATA.equals(tokenType)) { - return; - } - @NonNls final String text = token.getText(); - int startIndex = 0; - while (true) { - startIndex = text.indexOf("", startIndex); - if (startIndex < 0) { - return; - } - if (hasMatchingCloseTag(token, startIndex + 6)) { - registerErrorAtOffset(token, startIndex, 6, Integer.valueOf(startIndex)); + @Override + public void visitDocToken(PsiDocToken token) { + super.visitDocToken(token); + if (!PsiUtil.isLanguageLevel5OrHigher(token)) { + return; + } + final IElementType tokenType = token.getTokenType(); + if (!JavaDocTokenType.DOC_COMMENT_DATA.equals(tokenType)) { + return; + } + @NonNls final String text = token.getText(); + int startIndex = 0; + while (true) { + startIndex = text.indexOf("", startIndex); + if (startIndex < 0) { + return; + } + if (hasMatchingCloseTag(token, startIndex + 6)) { + registerErrorAtOffset(token, startIndex, 6, Integer.valueOf(startIndex)); + } + startIndex++; + } } - startIndex++; - } - } - private static boolean hasMatchingCloseTag(PsiElement element, int offset) { - final String text = element.getText(); - final int endOffset1 = text.indexOf("", offset); - if (endOffset1 >= 0) { - final int startOffset1 = text.indexOf("", offset); - return startOffset1 < 0 || startOffset1 > endOffset1; - } - PsiElement sibling = element.getNextSibling(); - while (sibling != null) { - final String text1 = sibling.getText(); - final int endOffset = text1.indexOf(""); - if (endOffset >= 0) { - final int startOffset = text1.indexOf(""); - return startOffset < 0 || startOffset > endOffset; + private static boolean hasMatchingCloseTag(PsiElement element, int offset) { + final String text = element.getText(); + final int endOffset1 = text.indexOf("", offset); + if (endOffset1 >= 0) { + final int startOffset1 = text.indexOf("", offset); + return startOffset1 < 0 || startOffset1 > endOffset1; + } + PsiElement sibling = element.getNextSibling(); + while (sibling != null) { + final String text1 = sibling.getText(); + final int endOffset = text1.indexOf(""); + if (endOffset >= 0) { + final int startOffset = text1.indexOf(""); + return startOffset < 0 || startOffset > endOffset; + } + sibling = sibling.getNextSibling(); + } + return false; } - sibling = sibling.getNextSibling(); - } - return false; } - } } diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/javadoc/PackageDotHtmlMayBePackageInfoInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/javadoc/PackageDotHtmlMayBePackageInfoInspection.java index 285de07f75..7cf640622f 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/javadoc/PackageDotHtmlMayBePackageInfoInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/javadoc/PackageDotHtmlMayBePackageInfoInspection.java @@ -34,6 +34,7 @@ import consulo.language.psi.PsiDirectory; import consulo.language.psi.PsiElement; import consulo.language.psi.PsiFile; +import consulo.localize.LocalizeValue; import consulo.module.content.ProjectFileIndex; import consulo.module.content.ProjectRootManager; import consulo.project.Project; @@ -48,201 +49,201 @@ import consulo.xml.psi.xml.XmlTagValue; import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; -import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NonNls; @ExtensionImpl public class PackageDotHtmlMayBePackageInfoInspection extends BaseInspection { - - @Nls - @Nonnull - @Override - public String getDisplayName() { - return InspectionGadgetsLocalize.packageDotHtmlMayBePackageInfoDisplayName().get(); - } - - @Nonnull - @Override - protected String buildErrorString(Object... infos) { - return (Boolean)infos[1] - ? InspectionGadgetsLocalize.packageDotHtmlMayBePackageInfoExistsProblemDescriptor().get() - : InspectionGadgetsLocalize.packageDotHtmlMayBePackageInfoProblemDescriptor().get(); - } - - @Override - protected InspectionGadgetsFix buildFix(Object... infos) { - final boolean packageInfoExists = (Boolean)infos[1]; - if (packageInfoExists) { - return new DeletePackageDotHtmlFix(); + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.packageDotHtmlMayBePackageInfoDisplayName(); } - final String aPackage = (String) infos[0]; - return new PackageDotHtmlMayBePackageInfoFix(aPackage); - } - private static class DeletePackageDotHtmlFix extends InspectionGadgetsFix { @Nonnull - public String getName() { - return InspectionGadgetsLocalize.packageDotHtmlMayBePackageInfoDeleteQuickfix().get(); + @Override + protected String buildErrorString(Object... infos) { + return (Boolean) infos[1] + ? InspectionGadgetsLocalize.packageDotHtmlMayBePackageInfoExistsProblemDescriptor().get() + : InspectionGadgetsLocalize.packageDotHtmlMayBePackageInfoProblemDescriptor().get(); } @Override - protected void doFix(Project project, ProblemDescriptor descriptor) { - final PsiElement element = descriptor.getPsiElement(); - if (!(element instanceof XmlFile)) { - return; - } - final XmlFile xmlFile = (XmlFile) element; - new WriteCommandAction.Simple(project, InspectionGadgetsBundle.message("package.dot.html.delete.command"), xmlFile) { + protected InspectionGadgetsFix buildFix(Object... infos) { + final boolean packageInfoExists = (Boolean) infos[1]; + if (packageInfoExists) { + return new DeletePackageDotHtmlFix(); + } + final String aPackage = (String) infos[0]; + return new PackageDotHtmlMayBePackageInfoFix(aPackage); + } + + private static class DeletePackageDotHtmlFix extends InspectionGadgetsFix { + @Nonnull @Override - protected void run() throws Throwable { - element.delete(); + public LocalizeValue getName() { + return InspectionGadgetsLocalize.packageDotHtmlMayBePackageInfoDeleteQuickfix(); } @Override - protected UndoConfirmationPolicy getUndoConfirmationPolicy() { - return UndoConfirmationPolicy.REQUEST_CONFIRMATION; + protected void doFix(Project project, ProblemDescriptor descriptor) { + final PsiElement element = descriptor.getPsiElement(); + if (!(element instanceof XmlFile)) { + return; + } + final XmlFile xmlFile = (XmlFile) element; + new WriteCommandAction.Simple(project, InspectionGadgetsBundle.message("package.dot.html.delete.command"), xmlFile) { + @Override + protected void run() throws Throwable { + element.delete(); + } + + @Override + protected UndoConfirmationPolicy getUndoConfirmationPolicy() { + return UndoConfirmationPolicy.REQUEST_CONFIRMATION; + } + }.execute(); } - }.execute(); } - } - private static class PackageDotHtmlMayBePackageInfoFix extends InspectionGadgetsFix { + private static class PackageDotHtmlMayBePackageInfoFix extends InspectionGadgetsFix { - private final String aPackage; + private final String aPackage; - public PackageDotHtmlMayBePackageInfoFix(String aPackage) { - this.aPackage = aPackage; - } + public PackageDotHtmlMayBePackageInfoFix(String aPackage) { + this.aPackage = aPackage; + } - @Nonnull - public String getName() { - return InspectionGadgetsLocalize.packageDotHtmlMayBePackageInfoConvertQuickfix().get(); - } + @Nonnull + @Override + public LocalizeValue getName() { + return InspectionGadgetsLocalize.packageDotHtmlMayBePackageInfoConvertQuickfix(); + } - @Override - protected void doFix(final Project project, ProblemDescriptor descriptor) { - final PsiElement element = descriptor.getPsiElement(); - if (!(element instanceof XmlFile)) { - return; - } - final XmlFile xmlFile = (XmlFile) element; - final PsiDirectory directory = xmlFile.getContainingDirectory(); - if (directory == null) { - return; - } - final PsiFile file = directory.findFile("package-info.java"); - if (file != null) { - return; - } - new WriteCommandAction.Simple(project, InspectionGadgetsBundle.message("package.dot.html.convert.command"), file) { @Override - protected void run() throws Throwable { - final PsiJavaFile file = (PsiJavaFile) directory.createFile("package-info.java"); - CommandProcessor.getInstance().addAffectedFiles(project, file.getVirtualFile()); - final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project); - String packageInfoText = getPackageInfoText(xmlFile); - if (packageInfoText == null) { - packageInfoText = xmlFile.getText(); - } - final StringBuilder commentText = new StringBuilder("/**\n"); - final String[] lines = StringUtil.splitByLines(packageInfoText); - boolean appended = false; - for (String line : lines) { - if (!appended && line.length() == 0) { - // skip empty lines at the beginning - continue; + protected void doFix(final Project project, ProblemDescriptor descriptor) { + final PsiElement element = descriptor.getPsiElement(); + if (!(element instanceof XmlFile)) { + return; } - commentText.append(" * ").append(line).append('\n'); - appended = true; - } - commentText.append("*/"); - final PsiDocComment comment = elementFactory.createDocCommentFromText(commentText.toString()); - if (aPackage.length() > 0) { - final PsiPackageStatement packageStatement = elementFactory.createPackageStatement(aPackage); - final PsiElement addedElement = file.add(packageStatement); - file.addBefore(comment, addedElement); - } else { - file.add(comment); - } - element.delete(); - if (!isOnTheFly()) { - return; - } - final AsyncResult dataContextFromFocus = DataManager.getInstance().getDataContextFromFocus(); - dataContextFromFocus.doWhenDone(dataContext -> { - final FileEditorManager editorManager = FileEditorManager.getInstance(project); - final VirtualFile virtualFile = file.getVirtualFile(); - if (virtualFile == null) { - return; + final XmlFile xmlFile = (XmlFile) element; + final PsiDirectory directory = xmlFile.getContainingDirectory(); + if (directory == null) { + return; } - editorManager.openFile(virtualFile, true); - }); + final PsiFile file = directory.findFile("package-info.java"); + if (file != null) { + return; + } + new WriteCommandAction.Simple(project, InspectionGadgetsBundle.message("package.dot.html.convert.command"), file) { + @Override + protected void run() throws Throwable { + final PsiJavaFile file = (PsiJavaFile) directory.createFile("package-info.java"); + CommandProcessor.getInstance().addAffectedFiles(project, file.getVirtualFile()); + final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project); + String packageInfoText = getPackageInfoText(xmlFile); + if (packageInfoText == null) { + packageInfoText = xmlFile.getText(); + } + final StringBuilder commentText = new StringBuilder("/**\n"); + final String[] lines = StringUtil.splitByLines(packageInfoText); + boolean appended = false; + for (String line : lines) { + if (!appended && line.length() == 0) { + // skip empty lines at the beginning + continue; + } + commentText.append(" * ").append(line).append('\n'); + appended = true; + } + commentText.append("*/"); + final PsiDocComment comment = elementFactory.createDocCommentFromText(commentText.toString()); + if (aPackage.length() > 0) { + final PsiPackageStatement packageStatement = elementFactory.createPackageStatement(aPackage); + final PsiElement addedElement = file.add(packageStatement); + file.addBefore(comment, addedElement); + } + else { + file.add(comment); + } + element.delete(); + if (!isOnTheFly()) { + return; + } + final AsyncResult dataContextFromFocus = DataManager.getInstance().getDataContextFromFocus(); + dataContextFromFocus.doWhenDone(dataContext -> { + final FileEditorManager editorManager = FileEditorManager.getInstance(project); + final VirtualFile virtualFile = file.getVirtualFile(); + if (virtualFile == null) { + return; + } + editorManager.openFile(virtualFile, true); + }); + } + + @Override + protected UndoConfirmationPolicy getUndoConfirmationPolicy() { + return UndoConfirmationPolicy.REQUEST_CONFIRMATION; + } + }.execute(); } - @Override - protected UndoConfirmationPolicy getUndoConfirmationPolicy() { - return UndoConfirmationPolicy.REQUEST_CONFIRMATION; + @Nullable + private static String getPackageInfoText(XmlFile xmlFile) { + final XmlTag rootTag = xmlFile.getRootTag(); + if (rootTag == null) { + return null; + } + final PsiElement[] children = rootTag.getChildren(); + for (PsiElement child : children) { + if (!(child instanceof HtmlTag)) { + continue; + } + final HtmlTag htmlTag = (HtmlTag) child; + @NonNls final String name = htmlTag.getName(); + if ("body".equals(name)) { + final XmlTagValue value = htmlTag.getValue(); + return value.getText(); + } + } + return null; } - }.execute(); } - @Nullable - private static String getPackageInfoText(XmlFile xmlFile) { - final XmlTag rootTag = xmlFile.getRootTag(); - if (rootTag == null) { - return null; - } - final PsiElement[] children = rootTag.getChildren(); - for (PsiElement child : children) { - if (!(child instanceof HtmlTag)) { - continue; - } - final HtmlTag htmlTag = (HtmlTag) child; - @NonNls final String name = htmlTag.getName(); - if ("body".equals(name)) { - final XmlTagValue value = htmlTag.getValue(); - return value.getText(); - } - } - return null; + @Override + public BaseInspectionVisitor buildVisitor() { + return new PackageDotHtmlMayBePackageInfoVisitor(); } - } - @Override - public BaseInspectionVisitor buildVisitor() { - return new PackageDotHtmlMayBePackageInfoVisitor(); - } + private static class PackageDotHtmlMayBePackageInfoVisitor extends BaseInspectionVisitor { - private static class PackageDotHtmlMayBePackageInfoVisitor extends BaseInspectionVisitor { - - @Override - public void visitFile(PsiFile file) { - super.visitFile(file); - if (!(file instanceof XmlFile)) { - return; - } - @NonNls final String fileName = file.getName(); - if (!"package.html".equals(fileName)) { - return; - } - final PsiDirectory directory = file.getContainingDirectory(); - if (directory == null) { - return; - } - final String aPackage = getPackage(directory); - if (aPackage == null) { - return; - } - final boolean exists = directory.findFile("package-info.java") != null; - registerError(file, aPackage, Boolean.valueOf(exists)); - } + @Override + public void visitFile(PsiFile file) { + super.visitFile(file); + if (!(file instanceof XmlFile)) { + return; + } + @NonNls final String fileName = file.getName(); + if (!"package.html".equals(fileName)) { + return; + } + final PsiDirectory directory = file.getContainingDirectory(); + if (directory == null) { + return; + } + final String aPackage = getPackage(directory); + if (aPackage == null) { + return; + } + final boolean exists = directory.findFile("package-info.java") != null; + registerError(file, aPackage, Boolean.valueOf(exists)); + } - public static String getPackage(@Nonnull PsiDirectory directory) { - final VirtualFile virtualFile = directory.getVirtualFile(); - final Project project = directory.getProject(); - final ProjectRootManager projectRootManager = ProjectRootManager.getInstance(project); - final ProjectFileIndex fileIndex = projectRootManager.getFileIndex(); - return fileIndex.getPackageNameByDirectory(virtualFile); + public static String getPackage(@Nonnull PsiDirectory directory) { + final VirtualFile virtualFile = directory.getVirtualFile(); + final Project project = directory.getProject(); + final ProjectRootManager projectRootManager = ProjectRootManager.getInstance(project); + final ProjectFileIndex fileIndex = projectRootManager.getFileIndex(); + return fileIndex.getPackageNameByDirectory(virtualFile); + } } - } } diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/javadoc/UnnecessaryInheritDocInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/javadoc/UnnecessaryInheritDocInspection.java index aefa511412..6da9c004e8 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/javadoc/UnnecessaryInheritDocInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/javadoc/UnnecessaryInheritDocInspection.java @@ -30,89 +30,87 @@ import consulo.language.psi.PsiElement; import consulo.language.psi.util.PsiTreeUtil; import consulo.language.util.IncorrectOperationException; +import consulo.localize.LocalizeValue; import consulo.project.Project; import consulo.util.lang.StringUtil; import jakarta.annotation.Nonnull; -import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NonNls; @ExtensionImpl public class UnnecessaryInheritDocInspection extends BaseInspection { - - @Nls - @Nonnull - @Override - public String getDisplayName() { - return InspectionGadgetsLocalize.unnecessaryInheritDocDisplayName().get(); - } - - @Nonnull - @Override - protected String buildErrorString(Object... infos) { - return InspectionGadgetsLocalize.unnecessaryInheritDocProblemDescriptor().get(); - } - - @Override - protected InspectionGadgetsFix buildFix(Object... infos) { - return new UnnecessaryInheritDocFix(); - } - - private static class UnnecessaryInheritDocFix extends InspectionGadgetsFix { + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.unnecessaryInheritDocDisplayName(); + } @Nonnull - public String getName() { - return InspectionGadgetsLocalize.unnecessaryInheritDocQuickfix().get(); + @Override + protected String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.unnecessaryInheritDocProblemDescriptor().get(); } @Override - protected void doFix(Project project, ProblemDescriptor descriptor) - throws IncorrectOperationException { - final PsiElement element = descriptor.getPsiElement(); - if (!(element instanceof PsiDocTag)) { - return; - } - final PsiDocTag docTag = (PsiDocTag)element; - final PsiDocComment docComment = docTag.getContainingComment(); - docComment.delete(); + protected InspectionGadgetsFix buildFix(Object... infos) { + return new UnnecessaryInheritDocFix(); } - } - @Override - public BaseInspectionVisitor buildVisitor() { - return new UnnecessaryInheritDocVisitor(); - } + private static class UnnecessaryInheritDocFix extends InspectionGadgetsFix { + @Nonnull + @Override + public LocalizeValue getName() { + return InspectionGadgetsLocalize.unnecessaryInheritDocQuickfix(); + } - private static class UnnecessaryInheritDocVisitor - extends BaseInspectionVisitor { + @Override + protected void doFix(Project project, ProblemDescriptor descriptor) + throws IncorrectOperationException { + final PsiElement element = descriptor.getPsiElement(); + if (!(element instanceof PsiDocTag)) { + return; + } + final PsiDocTag docTag = (PsiDocTag) element; + final PsiDocComment docComment = docTag.getContainingComment(); + docComment.delete(); + } + } @Override - public void visitDocTag(PsiDocTag tag) { - if (!(tag instanceof PsiInlineDocTag)) { - return; - } - @NonNls final String name = tag.getName(); - if (!"inheritDoc".equals(name)) { - return; - } - final PsiDocComment docComment = tag.getContainingComment(); - if (docComment == null) { - return; - } - final PsiDocToken[] docTokens = PsiTreeUtil.getChildrenOfType( - docComment, PsiDocToken.class); - if (docTokens == null) { - return; - } - for (PsiDocToken docToken : docTokens) { - final IElementType tokenType = docToken.getTokenType(); - if (!JavaDocTokenType.DOC_COMMENT_DATA.equals(tokenType)) { - continue; - } - if (!StringUtil.isEmptyOrSpaces(docToken.getText())) { - return; + public BaseInspectionVisitor buildVisitor() { + return new UnnecessaryInheritDocVisitor(); + } + + private static class UnnecessaryInheritDocVisitor + extends BaseInspectionVisitor { + + @Override + public void visitDocTag(PsiDocTag tag) { + if (!(tag instanceof PsiInlineDocTag)) { + return; + } + @NonNls final String name = tag.getName(); + if (!"inheritDoc".equals(name)) { + return; + } + final PsiDocComment docComment = tag.getContainingComment(); + if (docComment == null) { + return; + } + final PsiDocToken[] docTokens = PsiTreeUtil.getChildrenOfType( + docComment, PsiDocToken.class); + if (docTokens == null) { + return; + } + for (PsiDocToken docToken : docTokens) { + final IElementType tokenType = docToken.getTokenType(); + if (!JavaDocTokenType.DOC_COMMENT_DATA.equals(tokenType)) { + continue; + } + if (!StringUtil.isEmptyOrSpaces(docToken.getText())) { + return; + } + } + registerError(tag); } - } - registerError(tag); } - } } diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/javadoc/UnnecessaryJavaDocLinkInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/javadoc/UnnecessaryJavaDocLinkInspection.java index 5ff368abd9..8dd3876b3b 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/javadoc/UnnecessaryJavaDocLinkInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/javadoc/UnnecessaryJavaDocLinkInspection.java @@ -40,217 +40,224 @@ import consulo.project.Project; import consulo.util.lang.StringUtil; import jakarta.annotation.Nonnull; -import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NonNls; import javax.swing.*; @ExtensionImpl public class UnnecessaryJavaDocLinkInspection extends BaseInspection { + private static final int THIS_METHOD = 1; + private static final int THIS_CLASS = 2; + private static final int SUPER_METHOD = 3; - private static final int THIS_METHOD = 1; - private static final int THIS_CLASS = 2; - private static final int SUPER_METHOD = 3; + @SuppressWarnings({"PublicField"}) + public boolean ignoreInlineLinkToSuper = false; - @SuppressWarnings({"PublicField"}) - public boolean ignoreInlineLinkToSuper = false; - - @Nls - @Nonnull - @Override - public String getDisplayName() { - return InspectionGadgetsLocalize.unnecessaryJavadocLinkDisplayName().get(); - } - - @Nonnull - @Override - protected String buildErrorString(Object... infos) { - final int n = (Integer)infos[1]; - if (n == THIS_METHOD) { - return InspectionGadgetsLocalize.unnecessaryJavadocLinkThisMethodProblemDescriptor().get(); - } - else if (n == THIS_CLASS) { - return InspectionGadgetsLocalize.unnecessaryJavadocLinkThisClassProblemDescriptor().get(); - } - else { - return InspectionGadgetsLocalize.unnecessaryJavadocLinkSuperMethodProblemDescriptor().get(); + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.unnecessaryJavadocLinkDisplayName(); } - } - @Override - public JComponent createOptionsPanel() { - LocalizeValue message = InspectionGadgetsLocalize.unnecessaryJavadocLinkOption(); - return new SingleCheckboxOptionsPanel(message.get(), this, "ignoreInlineLinkToSuper"); - } + @Nonnull + @Override + protected String buildErrorString(Object... infos) { + final int n = (Integer) infos[1]; + if (n == THIS_METHOD) { + return InspectionGadgetsLocalize.unnecessaryJavadocLinkThisMethodProblemDescriptor().get(); + } + else if (n == THIS_CLASS) { + return InspectionGadgetsLocalize.unnecessaryJavadocLinkThisClassProblemDescriptor().get(); + } + else { + return InspectionGadgetsLocalize.unnecessaryJavadocLinkSuperMethodProblemDescriptor().get(); + } + } - @Override - protected InspectionGadgetsFix buildFix(Object... infos) { - return new UnnecessaryJavaDocLinkFix((String)infos[0]); - } + @Override + public JComponent createOptionsPanel() { + LocalizeValue message = InspectionGadgetsLocalize.unnecessaryJavadocLinkOption(); + return new SingleCheckboxOptionsPanel(message.get(), this, "ignoreInlineLinkToSuper"); + } - private static class UnnecessaryJavaDocLinkFix - extends InspectionGadgetsFix { + @Override + protected InspectionGadgetsFix buildFix(Object... infos) { + return new UnnecessaryJavaDocLinkFix((String) infos[0]); + } - private final String tagName; + private static class UnnecessaryJavaDocLinkFix + extends InspectionGadgetsFix { - public UnnecessaryJavaDocLinkFix(String tagName) { - this.tagName = tagName; - } + private final String tagName; - @Nonnull - public String getName() { - return InspectionGadgetsLocalize.unnecessaryJavadocLinkQuickfix(tagName).get(); - } + public UnnecessaryJavaDocLinkFix(String tagName) { + this.tagName = tagName; + } - @Override - protected void doFix(Project project, ProblemDescriptor descriptor) - throws IncorrectOperationException { - final PsiElement element = descriptor.getPsiElement(); - final PsiElement parent = element.getParent(); - if (!(parent instanceof PsiDocTag)) { - return; - } - final PsiDocTag docTag = (PsiDocTag)parent; - final PsiDocComment docComment = docTag.getContainingComment(); - if (docComment != null) { - if (shouldDeleteEntireComment(docComment)) { - docComment.delete(); - return; + @Nonnull + @Override + public LocalizeValue getName() { + return InspectionGadgetsLocalize.unnecessaryJavadocLinkQuickfix(tagName); } - } - docTag.delete(); - } - private static boolean shouldDeleteEntireComment( - PsiDocComment docComment) { - final PsiDocToken[] docTokens = PsiTreeUtil.getChildrenOfType( - docComment, PsiDocToken.class); - if (docTokens == null) { - return false; - } - for (PsiDocToken docToken : docTokens) { - final IElementType tokenType = docToken.getTokenType(); - if (!JavaDocTokenType.DOC_COMMENT_DATA.equals(tokenType)) { - continue; + @Override + protected void doFix(Project project, ProblemDescriptor descriptor) + throws IncorrectOperationException { + final PsiElement element = descriptor.getPsiElement(); + final PsiElement parent = element.getParent(); + if (!(parent instanceof PsiDocTag)) { + return; + } + final PsiDocTag docTag = (PsiDocTag) parent; + final PsiDocComment docComment = docTag.getContainingComment(); + if (docComment != null) { + if (shouldDeleteEntireComment(docComment)) { + docComment.delete(); + return; + } + } + docTag.delete(); } - if (!StringUtil.isEmptyOrSpaces(docToken.getText())) { - return false; + + private static boolean shouldDeleteEntireComment( + PsiDocComment docComment + ) { + final PsiDocToken[] docTokens = PsiTreeUtil.getChildrenOfType( + docComment, PsiDocToken.class); + if (docTokens == null) { + return false; + } + for (PsiDocToken docToken : docTokens) { + final IElementType tokenType = docToken.getTokenType(); + if (!JavaDocTokenType.DOC_COMMENT_DATA.equals(tokenType)) { + continue; + } + if (!StringUtil.isEmptyOrSpaces(docToken.getText())) { + return false; + } + } + return true; } - } - return true; } - } - @Override - public BaseInspectionVisitor buildVisitor() { - return new UnnecessaryJavaDocLinkVisitor(); - } + @Override + public BaseInspectionVisitor buildVisitor() { + return new UnnecessaryJavaDocLinkVisitor(); + } - private class UnnecessaryJavaDocLinkVisitor - extends BaseInspectionVisitor { + private class UnnecessaryJavaDocLinkVisitor + extends BaseInspectionVisitor { - @Override - public void visitDocTag(PsiDocTag tag) { - super.visitDocTag(tag); - @NonNls final String name = tag.getName(); - if ("link".equals(name) || "linkplain".equals(name)) { - if (!(tag instanceof PsiInlineDocTag)) { - return; - } - } - else if ("see".equals(name)) { - if (tag instanceof PsiInlineDocTag) { - return; + @Override + public void visitDocTag(PsiDocTag tag) { + super.visitDocTag(tag); + @NonNls final String name = tag.getName(); + if ("link".equals(name) || "linkplain".equals(name)) { + if (!(tag instanceof PsiInlineDocTag)) { + return; + } + } + else if ("see".equals(name)) { + if (tag instanceof PsiInlineDocTag) { + return; + } + } + final PsiReference reference = extractReference(tag); + if (reference == null) { + return; + } + final PsiElement target = reference.resolve(); + if (target == null) { + return; + } + final PsiMethod containingMethod = + PsiTreeUtil.getParentOfType(tag, PsiMethod.class); + if (containingMethod == null) { + return; + } + if (target.equals(containingMethod)) { + registerError(tag.getNameElement(), '@' + name, + Integer.valueOf(THIS_METHOD) + ); + return; + } + final PsiClass containingClass = + PsiTreeUtil.getParentOfType(tag, PsiClass.class); + if (target.equals(containingClass)) { + registerError(tag.getNameElement(), '@' + name, + Integer.valueOf(THIS_CLASS) + ); + return; + } + if (!(target instanceof PsiMethod)) { + return; + } + final PsiMethod method = (PsiMethod) target; + if (!isSuperMethod(method, containingMethod)) { + return; + } + if (ignoreInlineLinkToSuper && tag instanceof PsiInlineDocTag) { + return; + } + registerError(tag.getNameElement(), '@' + name, + Integer.valueOf(SUPER_METHOD) + ); } - } - final PsiReference reference = extractReference(tag); - if (reference == null) { - return; - } - final PsiElement target = reference.resolve(); - if (target == null) { - return; - } - final PsiMethod containingMethod = - PsiTreeUtil.getParentOfType(tag, PsiMethod.class); - if (containingMethod == null) { - return; - } - if (target.equals(containingMethod)) { - registerError(tag.getNameElement(), '@' + name, - Integer.valueOf(THIS_METHOD)); - return; - } - final PsiClass containingClass = - PsiTreeUtil.getParentOfType(tag, PsiClass.class); - if (target.equals(containingClass)) { - registerError(tag.getNameElement(), '@' + name, - Integer.valueOf(THIS_CLASS)); - return; - } - if (!(target instanceof PsiMethod)) { - return; - } - final PsiMethod method = (PsiMethod)target; - if (!isSuperMethod(method, containingMethod)) { - return; - } - if (ignoreInlineLinkToSuper && tag instanceof PsiInlineDocTag) { - return; - } - registerError(tag.getNameElement(), '@' + name, - Integer.valueOf(SUPER_METHOD)); - } - private PsiReference extractReference(PsiDocTag tag) { - final PsiDocTagValue valueElement = tag.getValueElement(); - if (valueElement != null) { - return valueElement.getReference(); - } - // hack around the fact that a reference to a class is apparently - // not a PsiDocTagValue - final PsiElement[] dataElements = tag.getDataElements(); - if (dataElements.length == 0) { - return null; - } - PsiElement salientElement = null; - for (PsiElement dataElement : dataElements) { - if (!(dataElement instanceof PsiWhiteSpace)) { - salientElement = dataElement; - break; + private PsiReference extractReference(PsiDocTag tag) { + final PsiDocTagValue valueElement = tag.getValueElement(); + if (valueElement != null) { + return valueElement.getReference(); + } + // hack around the fact that a reference to a class is apparently + // not a PsiDocTagValue + final PsiElement[] dataElements = tag.getDataElements(); + if (dataElements.length == 0) { + return null; + } + PsiElement salientElement = null; + for (PsiElement dataElement : dataElements) { + if (!(dataElement instanceof PsiWhiteSpace)) { + salientElement = dataElement; + break; + } + } + if (salientElement == null) { + return null; + } + final PsiElement child = salientElement.getFirstChild(); + if (!(child instanceof PsiReference)) { + return null; + } + return (PsiReference) child; } - } - if (salientElement == null) { - return null; - } - final PsiElement child = salientElement.getFirstChild(); - if (!(child instanceof PsiReference)) { - return null; - } - return (PsiReference)child; - } - public boolean isSuperMethod(PsiMethod superMethodCandidate, - PsiMethod derivedMethod) { - final PsiClass superClassCandidate = - superMethodCandidate.getContainingClass(); - final PsiClass derivedClass = derivedMethod.getContainingClass(); - if (derivedClass == null || superClassCandidate == null) { - return false; - } - if (!derivedClass.isInheritor(superClassCandidate, false)) { - return false; - } - final PsiSubstitutor superSubstitutor = - TypeConversionUtil.getSuperClassSubstitutor( - superClassCandidate, derivedClass, - PsiSubstitutor.EMPTY); - final MethodSignature superSignature = - superMethodCandidate.getSignature(superSubstitutor); - final MethodSignature derivedSignature = - derivedMethod.getSignature(PsiSubstitutor.EMPTY); - return MethodSignatureUtil.isSubsignature(superSignature, - derivedSignature); + public boolean isSuperMethod( + PsiMethod superMethodCandidate, + PsiMethod derivedMethod + ) { + final PsiClass superClassCandidate = + superMethodCandidate.getContainingClass(); + final PsiClass derivedClass = derivedMethod.getContainingClass(); + if (derivedClass == null || superClassCandidate == null) { + return false; + } + if (!derivedClass.isInheritor(superClassCandidate, false)) { + return false; + } + final PsiSubstitutor superSubstitutor = + TypeConversionUtil.getSuperClassSubstitutor( + superClassCandidate, derivedClass, + PsiSubstitutor.EMPTY + ); + final MethodSignature superSignature = + superMethodCandidate.getSignature(superSubstitutor); + final MethodSignature derivedSignature = + derivedMethod.getSignature(PsiSubstitutor.EMPTY); + return MethodSignatureUtil.isSubsignature( + superSignature, + derivedSignature + ); + } } - } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/jdk/AnnotationClassInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/jdk/AnnotationClassInspection.java index 1f3934e8a2..9fd61aee19 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/jdk/AnnotationClassInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/jdk/AnnotationClassInspection.java @@ -20,33 +20,34 @@ import com.siyeh.ig.BaseInspectionVisitor; import com.siyeh.localize.InspectionGadgetsLocalize; import consulo.annotation.component.ExtensionImpl; +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; @ExtensionImpl public class AnnotationClassInspection extends BaseInspection { + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.annotationClassDisplayName(); + } - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.annotationClassDisplayName().get(); - } - - @Nonnull - public String buildErrorString(Object... infos) { - return InspectionGadgetsLocalize.annotationClassProblemDescriptor().get(); - } + @Nonnull + public String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.annotationClassProblemDescriptor().get(); + } - public BaseInspectionVisitor buildVisitor() { - return new AnnotationClassVisitor(); - } + public BaseInspectionVisitor buildVisitor() { + return new AnnotationClassVisitor(); + } - private static class AnnotationClassVisitor extends BaseInspectionVisitor { + private static class AnnotationClassVisitor extends BaseInspectionVisitor { - @Override - public void visitClass(@Nonnull PsiClass aClass) { - if (!aClass.isAnnotationType()) { - return; - } - registerClassError(aClass); + @Override + public void visitClass(@Nonnull PsiClass aClass) { + if (!aClass.isAnnotationType()) { + return; + } + registerClassError(aClass); + } } - } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/jdk/AnnotationInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/jdk/AnnotationInspection.java index e33c08b633..d5f755ba63 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/jdk/AnnotationInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/jdk/AnnotationInspection.java @@ -20,34 +20,34 @@ import com.siyeh.ig.BaseInspectionVisitor; import com.siyeh.localize.InspectionGadgetsLocalize; import consulo.annotation.component.ExtensionImpl; +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; @ExtensionImpl public class AnnotationInspection extends BaseInspection { + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.annotationDisplayName(); + } - @Override - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.annotationDisplayName().get(); - } - - @Override - @Nonnull - public String buildErrorString(Object... infos) { - return InspectionGadgetsLocalize.annotationProblemDescriptor().get(); - } + @Override + @Nonnull + public String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.annotationProblemDescriptor().get(); + } - @Override - public BaseInspectionVisitor buildVisitor() { - return new AnnotationVisitor(); - } + @Override + public BaseInspectionVisitor buildVisitor() { + return new AnnotationVisitor(); + } - private static class AnnotationVisitor extends BaseInspectionVisitor { + private static class AnnotationVisitor extends BaseInspectionVisitor { - @Override - public void visitAnnotation(PsiAnnotation annotation) { - super.visitAnnotation(annotation); - registerError(annotation); + @Override + public void visitAnnotation(PsiAnnotation annotation) { + super.visitAnnotation(annotation); + registerError(annotation); + } } - } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/jdk/AssertAsNameInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/jdk/AssertAsNameInspection.java index 253146a1bc..55526c50ad 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/jdk/AssertAsNameInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/jdk/AssertAsNameInspection.java @@ -22,88 +22,90 @@ import com.siyeh.ig.InspectionGadgetsFix; import com.siyeh.localize.InspectionGadgetsLocalize; import consulo.annotation.component.ExtensionImpl; +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; +import org.intellij.lang.annotations.Pattern; @ExtensionImpl public class AssertAsNameInspection extends BaseInspection { + @Nonnull + @Override + @Pattern(VALID_ID_PATTERN) + public String getID() { + return "AssertAsIdentifier"; + } - @Override - @Nonnull - public String getID() { - return "AssertAsIdentifier"; - } - - @Override - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.useAssertAsIdentifierDisplayName().get(); - } - - @Override - @Nonnull - public String buildErrorString(Object... infos) { - return InspectionGadgetsLocalize.useAssertAsIdentifierProblemDescriptor().get(); - } - - @Override - protected InspectionGadgetsFix buildFix(Object... infos) { - return new RenameFix(); - } - - @Override - protected boolean buildQuickFixesOnlyForOnTheFlyErrors() { - return true; - } - - @Override - public BaseInspectionVisitor buildVisitor() { - return new AssertAsNameVisitor(); - } - - private static class AssertAsNameVisitor extends BaseInspectionVisitor { + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.useAssertAsIdentifierDisplayName(); + } @Override - public void visitVariable(@Nonnull PsiVariable variable) { - super.visitVariable(variable); - final String variableName = variable.getName(); - if (!PsiKeyword.ASSERT.equals(variableName)) { - return; - } - registerVariableError(variable); + @Nonnull + public String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.useAssertAsIdentifierProblemDescriptor().get(); } @Override - public void visitMethod(@Nonnull PsiMethod method) { - super.visitMethod(method); - final String name = method.getName(); - if (!PsiKeyword.ASSERT.equals(name)) { - return; - } - registerMethodError(method); + protected InspectionGadgetsFix buildFix(Object... infos) { + return new RenameFix(); } @Override - public void visitClass(@Nonnull PsiClass aClass) { - //note: no call to super, to avoid drill-down - final String name = aClass.getName(); - if (!PsiKeyword.ASSERT.equals(name)) { - return; - } - final PsiTypeParameterList params = aClass.getTypeParameterList(); - if (params != null) { - params.accept(this); - } - registerClassError(aClass); + protected boolean buildQuickFixesOnlyForOnTheFlyErrors() { + return true; } @Override - public void visitTypeParameter(PsiTypeParameter parameter) { - super.visitTypeParameter(parameter); - final String name = parameter.getName(); - if (!PsiKeyword.ASSERT.equals(name)) { - return; - } - registerTypeParameterError(parameter); + public BaseInspectionVisitor buildVisitor() { + return new AssertAsNameVisitor(); + } + + private static class AssertAsNameVisitor extends BaseInspectionVisitor { + + @Override + public void visitVariable(@Nonnull PsiVariable variable) { + super.visitVariable(variable); + final String variableName = variable.getName(); + if (!PsiKeyword.ASSERT.equals(variableName)) { + return; + } + registerVariableError(variable); + } + + @Override + public void visitMethod(@Nonnull PsiMethod method) { + super.visitMethod(method); + final String name = method.getName(); + if (!PsiKeyword.ASSERT.equals(name)) { + return; + } + registerMethodError(method); + } + + @Override + public void visitClass(@Nonnull PsiClass aClass) { + //note: no call to super, to avoid drill-down + final String name = aClass.getName(); + if (!PsiKeyword.ASSERT.equals(name)) { + return; + } + final PsiTypeParameterList params = aClass.getTypeParameterList(); + if (params != null) { + params.accept(this); + } + registerClassError(aClass); + } + + @Override + public void visitTypeParameter(PsiTypeParameter parameter) { + super.visitTypeParameter(parameter); + final String name = parameter.getName(); + if (!PsiKeyword.ASSERT.equals(name)) { + return; + } + registerTypeParameterError(parameter); + } } - } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/jdk/AssertStatementInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/jdk/AssertStatementInspection.java index 2054e1b083..c984771945 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/jdk/AssertStatementInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/jdk/AssertStatementInspection.java @@ -20,32 +20,33 @@ import com.siyeh.ig.BaseInspectionVisitor; import com.siyeh.localize.InspectionGadgetsLocalize; import consulo.annotation.component.ExtensionImpl; +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; @ExtensionImpl public class AssertStatementInspection extends BaseInspection { + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.assertStatementDisplayName(); + } - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.assertStatementDisplayName().get(); - } - - @Nonnull - public String buildErrorString(Object... infos) { - return InspectionGadgetsLocalize.statementProblemDescriptor().get(); - } + @Nonnull + public String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.statementProblemDescriptor().get(); + } - public BaseInspectionVisitor buildVisitor() { - return new AssertStatementVisitor(); - } + public BaseInspectionVisitor buildVisitor() { + return new AssertStatementVisitor(); + } - private static class AssertStatementVisitor - extends BaseInspectionVisitor { + private static class AssertStatementVisitor + extends BaseInspectionVisitor { - @Override - public void visitAssertStatement(PsiAssertStatement statement) { - super.visitAssertStatement(statement); - registerStatementError(statement); + @Override + public void visitAssertStatement(PsiAssertStatement statement) { + super.visitAssertStatement(statement); + registerStatementError(statement); + } } - } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/jdk/AutoBoxingInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/jdk/AutoBoxingInspection.java index 57f247fac3..85867756af 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/jdk/AutoBoxingInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/jdk/AutoBoxingInspection.java @@ -42,314 +42,322 @@ @ExtensionImpl public class AutoBoxingInspection extends BaseInspection { - - @SuppressWarnings({"PublicField"}) - public boolean ignoreAddedToCollection = false; - - /** - * @noinspection StaticCollection - */ - @NonNls static final Map s_boxingClasses = new HashMap(8); - - static { - s_boxingClasses.put("byte", CommonClassNames.JAVA_LANG_BYTE); - s_boxingClasses.put("short", CommonClassNames.JAVA_LANG_SHORT); - s_boxingClasses.put("int", CommonClassNames.JAVA_LANG_INTEGER); - s_boxingClasses.put("long", CommonClassNames.JAVA_LANG_LONG); - s_boxingClasses.put("float", CommonClassNames.JAVA_LANG_FLOAT); - s_boxingClasses.put("double", CommonClassNames.JAVA_LANG_DOUBLE); - s_boxingClasses.put("boolean", CommonClassNames.JAVA_LANG_BOOLEAN); - s_boxingClasses.put("char", CommonClassNames.JAVA_LANG_CHARACTER); - } - - @NonNls static final Set convertableBoxedClassNames = new HashSet(); - - static { - convertableBoxedClassNames.add(CommonClassNames.JAVA_LANG_BYTE); - convertableBoxedClassNames.add(CommonClassNames.JAVA_LANG_CHARACTER); - convertableBoxedClassNames.add(CommonClassNames.JAVA_LANG_SHORT); - } - - @Override - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.autoBoxingDisplayName().get(); - } - - @Override - public String getAlternativeID() { - return "boxing"; - } - - @Override - @Nonnull - public String buildErrorString(Object... infos) { - return InspectionGadgetsLocalize.autoBoxingProblemDescriptor().get(); - } - - @Override - @Nullable - public JComponent createOptionsPanel() { - LocalizeValue message = InspectionGadgetsLocalize.autoBoxingIgnoreAddedToCollectionOption(); - return new SingleCheckboxOptionsPanel(message.get(), this, "ignoreAddedToCollection"); - } - - @Override - public BaseInspectionVisitor buildVisitor() { - return new AutoBoxingVisitor(); - } - - @Override - public InspectionGadgetsFix buildFix(Object... infos) { - return new AutoBoxingFix(); - } - - private static class AutoBoxingFix extends InspectionGadgetsFix { - - @Nonnull - public String getName() { - return InspectionGadgetsLocalize.autoBoxingMakeBoxingExplicitQuickfix().get(); + @SuppressWarnings({"PublicField"}) + public boolean ignoreAddedToCollection = false; + + /** + * @noinspection StaticCollection + */ + static final Map s_boxingClasses = new HashMap(8); + + static { + s_boxingClasses.put("byte", CommonClassNames.JAVA_LANG_BYTE); + s_boxingClasses.put("short", CommonClassNames.JAVA_LANG_SHORT); + s_boxingClasses.put("int", CommonClassNames.JAVA_LANG_INTEGER); + s_boxingClasses.put("long", CommonClassNames.JAVA_LANG_LONG); + s_boxingClasses.put("float", CommonClassNames.JAVA_LANG_FLOAT); + s_boxingClasses.put("double", CommonClassNames.JAVA_LANG_DOUBLE); + s_boxingClasses.put("boolean", CommonClassNames.JAVA_LANG_BOOLEAN); + s_boxingClasses.put("char", CommonClassNames.JAVA_LANG_CHARACTER); } - @Override - public void doFix(Project project, ProblemDescriptor descriptor) { - final PsiExpression expression = (PsiExpression)descriptor.getPsiElement(); - final PsiType expectedType = ExpectedTypeUtils.findExpectedType(expression, false); - if (expectedType == null) { - return; - } - final String expectedTypeText = expectedType.getCanonicalText(); - final String classToConstruct; - if (s_boxingClasses.containsValue(expectedTypeText)) { - classToConstruct = expectedTypeText; - } - else { - final PsiType type = expression.getType(); - if (type == null) { - return; - } - final String expressionTypeText = type.getCanonicalText(); - classToConstruct = s_boxingClasses.get(expressionTypeText); - } - if (shortcutReplace(expression, classToConstruct)) { - return; - } - final PsiExpression strippedExpression = ParenthesesUtils.stripParentheses(expression); - if (strippedExpression == null) { - return; - } - @NonNls final String expressionText = strippedExpression.getText(); - @NonNls final String newExpression; - if ("true".equals(expressionText)) { - newExpression = "java.lang.Boolean.TRUE"; - } - else if ("false".equals(expressionText)) { - newExpression = "java.lang.Boolean.FALSE"; - } - else { - newExpression = classToConstruct + ".valueOf(" + expressionText + ')'; - } - replaceExpression(expression, newExpression); - } + static final Set convertableBoxedClassNames = new HashSet(); - private static boolean shortcutReplace(PsiExpression expression, String classToConstruct) { - if (!(expression instanceof PsiMethodCallExpression)) { - return false; - } - final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression)expression; - final PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression(); - final PsiExpression qualifierExpression = methodExpression.getQualifierExpression(); - if (qualifierExpression == null) { - return false; - } - if (classToConstruct.equals(CommonClassNames.JAVA_LANG_INTEGER)) { - if (MethodCallUtils.isCallToMethod(methodCallExpression, CommonClassNames.JAVA_LANG_INTEGER, PsiType.INT, "intValue")) { - expression.replace(qualifierExpression); - return true; - } - } - else if (classToConstruct.equals(CommonClassNames.JAVA_LANG_SHORT)) { - if (MethodCallUtils.isCallToMethod(methodCallExpression, CommonClassNames.JAVA_LANG_SHORT, PsiType.SHORT, "shortValue")) { - expression.replace(qualifierExpression); - return true; - } - } - else if (classToConstruct.equals(CommonClassNames.JAVA_LANG_BYTE)) { - if (MethodCallUtils.isCallToMethod(methodCallExpression, CommonClassNames.JAVA_LANG_BYTE, PsiType.BYTE, "byteValue")) { - expression.replace(qualifierExpression); - return true; - } - } - else if (classToConstruct.equals(CommonClassNames.JAVA_LANG_CHARACTER)) { - if (MethodCallUtils.isCallToMethod(methodCallExpression, CommonClassNames.JAVA_LANG_CHARACTER, PsiType.CHAR, "charValue")) { - expression.replace(qualifierExpression); - return true; - } - } - else if (classToConstruct.equals(CommonClassNames.JAVA_LANG_LONG)) { - if (MethodCallUtils.isCallToMethod(methodCallExpression, CommonClassNames.JAVA_LANG_LONG, PsiType.LONG, "longValue")) { - expression.replace(qualifierExpression); - return true; - } - } - else if (classToConstruct.equals(CommonClassNames.JAVA_LANG_FLOAT)) { - if (MethodCallUtils.isCallToMethod(methodCallExpression, CommonClassNames.JAVA_LANG_FLOAT, PsiType.FLOAT, "floatValue")) { - expression.replace(qualifierExpression); - return true; - } - } - else if (classToConstruct.equals(CommonClassNames.JAVA_LANG_DOUBLE)) { - if (MethodCallUtils.isCallToMethod(methodCallExpression, CommonClassNames.JAVA_LANG_DOUBLE, PsiType.DOUBLE, "doubleValue")) { - expression.replace(qualifierExpression); - return true; - } - } - return false; + static { + convertableBoxedClassNames.add(CommonClassNames.JAVA_LANG_BYTE); + convertableBoxedClassNames.add(CommonClassNames.JAVA_LANG_CHARACTER); + convertableBoxedClassNames.add(CommonClassNames.JAVA_LANG_SHORT); } - } - - private class AutoBoxingVisitor extends BaseInspectionVisitor { + @Nonnull @Override - public void visitElement(PsiElement element) { - if (element.getLanguage() != JavaLanguage.INSTANCE) { - return; - } - if (!PsiUtil.isLanguageLevel5OrHigher(element)) { - return; - } - super.visitElement(element); + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.autoBoxingDisplayName(); } @Override - public void visitArrayAccessExpression(PsiArrayAccessExpression expression) { - super.visitArrayAccessExpression(expression); - checkExpression(expression); + public String getAlternativeID() { + return "boxing"; } @Override - public void visitAssignmentExpression(PsiAssignmentExpression expression) { - super.visitAssignmentExpression(expression); - checkExpression(expression); + @Nonnull + public String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.autoBoxingProblemDescriptor().get(); } @Override - public void visitConditionalExpression(PsiConditionalExpression expression) { - super.visitConditionalExpression(expression); - checkExpression(expression); + @Nullable + public JComponent createOptionsPanel() { + LocalizeValue message = InspectionGadgetsLocalize.autoBoxingIgnoreAddedToCollectionOption(); + return new SingleCheckboxOptionsPanel(message.get(), this, "ignoreAddedToCollection"); } @Override - public void visitInstanceOfExpression(PsiInstanceOfExpression expression) { - super.visitInstanceOfExpression(expression); - checkExpression(expression); + public BaseInspectionVisitor buildVisitor() { + return new AutoBoxingVisitor(); } @Override - public void visitLiteralExpression(PsiLiteralExpression expression) { - super.visitLiteralExpression(expression); - checkExpression(expression); + public InspectionGadgetsFix buildFix(Object... infos) { + return new AutoBoxingFix(); } - @Override - public void visitMethodCallExpression(PsiMethodCallExpression expression) { - super.visitMethodCallExpression(expression); - checkExpression(expression); - } + private static class AutoBoxingFix extends InspectionGadgetsFix { + @Nonnull + @Override + public LocalizeValue getName() { + return InspectionGadgetsLocalize.autoBoxingMakeBoxingExplicitQuickfix(); + } - @Override - public void visitParenthesizedExpression(PsiParenthesizedExpression expression) { - super.visitParenthesizedExpression(expression); - checkExpression(expression); - } + @Override + public void doFix(Project project, ProblemDescriptor descriptor) { + final PsiExpression expression = (PsiExpression) descriptor.getPsiElement(); + final PsiType expectedType = ExpectedTypeUtils.findExpectedType(expression, false); + if (expectedType == null) { + return; + } + final String expectedTypeText = expectedType.getCanonicalText(); + final String classToConstruct; + if (s_boxingClasses.containsValue(expectedTypeText)) { + classToConstruct = expectedTypeText; + } + else { + final PsiType type = expression.getType(); + if (type == null) { + return; + } + final String expressionTypeText = type.getCanonicalText(); + classToConstruct = s_boxingClasses.get(expressionTypeText); + } + if (shortcutReplace(expression, classToConstruct)) { + return; + } + final PsiExpression strippedExpression = ParenthesesUtils.stripParentheses(expression); + if (strippedExpression == null) { + return; + } + @NonNls final String expressionText = strippedExpression.getText(); + @NonNls final String newExpression; + if ("true".equals(expressionText)) { + newExpression = "java.lang.Boolean.TRUE"; + } + else if ("false".equals(expressionText)) { + newExpression = "java.lang.Boolean.FALSE"; + } + else { + newExpression = classToConstruct + ".valueOf(" + expressionText + ')'; + } + replaceExpression(expression, newExpression); + } - @Override - public void visitPolyadicExpression(PsiPolyadicExpression expression) { - super.visitPolyadicExpression(expression); - checkExpression(expression); + private static boolean shortcutReplace(PsiExpression expression, String classToConstruct) { + if (!(expression instanceof PsiMethodCallExpression)) { + return false; + } + final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression) expression; + final PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression(); + final PsiExpression qualifierExpression = methodExpression.getQualifierExpression(); + if (qualifierExpression == null) { + return false; + } + if (classToConstruct.equals(CommonClassNames.JAVA_LANG_INTEGER)) { + if (MethodCallUtils.isCallToMethod(methodCallExpression, CommonClassNames.JAVA_LANG_INTEGER, PsiType.INT, "intValue")) { + expression.replace(qualifierExpression); + return true; + } + } + else if (classToConstruct.equals(CommonClassNames.JAVA_LANG_SHORT)) { + if (MethodCallUtils.isCallToMethod(methodCallExpression, CommonClassNames.JAVA_LANG_SHORT, PsiType.SHORT, "shortValue")) { + expression.replace(qualifierExpression); + return true; + } + } + else if (classToConstruct.equals(CommonClassNames.JAVA_LANG_BYTE)) { + if (MethodCallUtils.isCallToMethod(methodCallExpression, CommonClassNames.JAVA_LANG_BYTE, PsiType.BYTE, "byteValue")) { + expression.replace(qualifierExpression); + return true; + } + } + else if (classToConstruct.equals(CommonClassNames.JAVA_LANG_CHARACTER)) { + if (MethodCallUtils.isCallToMethod(methodCallExpression, CommonClassNames.JAVA_LANG_CHARACTER, PsiType.CHAR, "charValue")) { + expression.replace(qualifierExpression); + return true; + } + } + else if (classToConstruct.equals(CommonClassNames.JAVA_LANG_LONG)) { + if (MethodCallUtils.isCallToMethod(methodCallExpression, CommonClassNames.JAVA_LANG_LONG, PsiType.LONG, "longValue")) { + expression.replace(qualifierExpression); + return true; + } + } + else if (classToConstruct.equals(CommonClassNames.JAVA_LANG_FLOAT)) { + if (MethodCallUtils.isCallToMethod(methodCallExpression, CommonClassNames.JAVA_LANG_FLOAT, PsiType.FLOAT, "floatValue")) { + expression.replace(qualifierExpression); + return true; + } + } + else if (classToConstruct.equals(CommonClassNames.JAVA_LANG_DOUBLE)) { + if (MethodCallUtils.isCallToMethod( + methodCallExpression, + CommonClassNames.JAVA_LANG_DOUBLE, + PsiType.DOUBLE, + "doubleValue" + )) { + expression.replace(qualifierExpression); + return true; + } + } + return false; + } } - @Override - public void visitPostfixExpression(PsiPostfixExpression expression) { - super.visitPostfixExpression(expression); - checkExpression(expression); - } + private class AutoBoxingVisitor extends BaseInspectionVisitor { + + @Override + public void visitElement(PsiElement element) { + if (element.getLanguage() != JavaLanguage.INSTANCE) { + return; + } + if (!PsiUtil.isLanguageLevel5OrHigher(element)) { + return; + } + super.visitElement(element); + } - @Override - public void visitPrefixExpression(PsiPrefixExpression expression) { - super.visitPrefixExpression(expression); - checkExpression(expression); - } + @Override + public void visitArrayAccessExpression(PsiArrayAccessExpression expression) { + super.visitArrayAccessExpression(expression); + checkExpression(expression); + } - @Override - public void visitReferenceExpression(PsiReferenceExpression expression) { - super.visitReferenceExpression(expression); - checkExpression(expression); - } + @Override + public void visitAssignmentExpression(PsiAssignmentExpression expression) { + super.visitAssignmentExpression(expression); + checkExpression(expression); + } - @Override - public void visitTypeCastExpression(PsiTypeCastExpression expression) { - super.visitTypeCastExpression(expression); - checkExpression(expression); - } + @Override + public void visitConditionalExpression(PsiConditionalExpression expression) { + super.visitConditionalExpression(expression); + checkExpression(expression); + } - private void checkExpression(@Nonnull PsiExpression expression) { - if (expression.getParent() instanceof PsiParenthesizedExpression) { - return; - } - final PsiType expressionType = expression.getType(); - if (expressionType == null || expressionType.equals(PsiType.VOID) || !TypeConversionUtil.isPrimitiveAndNotNull(expressionType)) { - return; - } - final PsiPrimitiveType primitiveType = (PsiPrimitiveType)expressionType; - final PsiClassType boxedType = primitiveType.getBoxedType(expression); - if (boxedType == null) { - return; - } - final PsiType expectedType = ExpectedTypeUtils.findExpectedType(expression, false); - if (expectedType == null || ClassUtils.isPrimitive(expectedType)) { - return; - } - if (!expectedType.isAssignableFrom(boxedType)) { - // JLS 5.2 Assignment Conversion - // check if a narrowing primitive conversion is applicable - if (!(expectedType instanceof PsiClassType) || !PsiUtil.isConstantExpression(expression)) { - return; + @Override + public void visitInstanceOfExpression(PsiInstanceOfExpression expression) { + super.visitInstanceOfExpression(expression); + checkExpression(expression); } - final PsiClassType classType = (PsiClassType)expectedType; - final String className = classType.getCanonicalText(); - if (!convertableBoxedClassNames.contains(className)) { - return; + + @Override + public void visitLiteralExpression(PsiLiteralExpression expression) { + super.visitLiteralExpression(expression); + checkExpression(expression); } - if (!PsiType.BYTE.equals(expressionType) && !PsiType.CHAR.equals(expressionType) && - !PsiType.SHORT.equals(expressionType) && !PsiType.INT.equals(expressionType)) { - return; + + @Override + public void visitMethodCallExpression(PsiMethodCallExpression expression) { + super.visitMethodCallExpression(expression); + checkExpression(expression); + } + + @Override + public void visitParenthesizedExpression(PsiParenthesizedExpression expression) { + super.visitParenthesizedExpression(expression); + checkExpression(expression); } - } - if (ignoreAddedToCollection && isAddedToCollection(expression)) { - return; - } - registerError(expression); - } - private boolean isAddedToCollection(PsiExpression expression) { - final PsiElement parent = expression.getParent(); - if (!(parent instanceof PsiExpressionList)) { - return false; - } - final PsiExpressionList expressionList = (PsiExpressionList)parent; - final PsiElement grandParent = expressionList.getParent(); - if (!(grandParent instanceof PsiMethodCallExpression)) { - return false; - } - final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression)grandParent; - final PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression(); - @NonNls final String methodName = methodExpression.getReferenceName(); - if (!"put".equals(methodName) && !"set".equals(methodName) && !"add".equals(methodName)) { - return false; - } - final PsiExpression qualifier = methodExpression.getQualifierExpression(); - return TypeUtils.expressionHasTypeOrSubtype(qualifier, CommonClassNames.JAVA_UTIL_COLLECTION, CommonClassNames.JAVA_UTIL_MAP) != null; + @Override + public void visitPolyadicExpression(PsiPolyadicExpression expression) { + super.visitPolyadicExpression(expression); + checkExpression(expression); + } + + @Override + public void visitPostfixExpression(PsiPostfixExpression expression) { + super.visitPostfixExpression(expression); + checkExpression(expression); + } + + @Override + public void visitPrefixExpression(PsiPrefixExpression expression) { + super.visitPrefixExpression(expression); + checkExpression(expression); + } + + @Override + public void visitReferenceExpression(PsiReferenceExpression expression) { + super.visitReferenceExpression(expression); + checkExpression(expression); + } + + @Override + public void visitTypeCastExpression(PsiTypeCastExpression expression) { + super.visitTypeCastExpression(expression); + checkExpression(expression); + } + + private void checkExpression(@Nonnull PsiExpression expression) { + if (expression.getParent() instanceof PsiParenthesizedExpression) { + return; + } + final PsiType expressionType = expression.getType(); + if (expressionType == null || expressionType.equals(PsiType.VOID) || !TypeConversionUtil.isPrimitiveAndNotNull(expressionType)) { + return; + } + final PsiPrimitiveType primitiveType = (PsiPrimitiveType) expressionType; + final PsiClassType boxedType = primitiveType.getBoxedType(expression); + if (boxedType == null) { + return; + } + final PsiType expectedType = ExpectedTypeUtils.findExpectedType(expression, false); + if (expectedType == null || ClassUtils.isPrimitive(expectedType)) { + return; + } + if (!expectedType.isAssignableFrom(boxedType)) { + // JLS 5.2 Assignment Conversion + // check if a narrowing primitive conversion is applicable + if (!(expectedType instanceof PsiClassType) || !PsiUtil.isConstantExpression(expression)) { + return; + } + final PsiClassType classType = (PsiClassType) expectedType; + final String className = classType.getCanonicalText(); + if (!convertableBoxedClassNames.contains(className)) { + return; + } + if (!PsiType.BYTE.equals(expressionType) && !PsiType.CHAR.equals(expressionType) && + !PsiType.SHORT.equals(expressionType) && !PsiType.INT.equals(expressionType)) { + return; + } + } + if (ignoreAddedToCollection && isAddedToCollection(expression)) { + return; + } + registerError(expression); + } + + private boolean isAddedToCollection(PsiExpression expression) { + final PsiElement parent = expression.getParent(); + if (!(parent instanceof PsiExpressionList)) { + return false; + } + final PsiExpressionList expressionList = (PsiExpressionList) parent; + final PsiElement grandParent = expressionList.getParent(); + if (!(grandParent instanceof PsiMethodCallExpression)) { + return false; + } + final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression) grandParent; + final PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression(); + @NonNls final String methodName = methodExpression.getReferenceName(); + if (!"put".equals(methodName) && !"set".equals(methodName) && !"add".equals(methodName)) { + return false; + } + final PsiExpression qualifier = methodExpression.getQualifierExpression(); + return TypeUtils.expressionHasTypeOrSubtype( + qualifier, + CommonClassNames.JAVA_UTIL_COLLECTION, + CommonClassNames.JAVA_UTIL_MAP + ) != null; + } } - } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/jdk/AutoUnboxingInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/jdk/AutoUnboxingInspection.java index 571080c1e2..8ba5a93759 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/jdk/AutoUnboxingInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/jdk/AutoUnboxingInspection.java @@ -37,6 +37,7 @@ import consulo.language.psi.scope.LocalSearchScope; import consulo.language.psi.search.ReferencesSearch; import consulo.language.psi.util.PsiTreeUtil; +import consulo.localize.LocalizeValue; import consulo.project.Project; import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; @@ -49,349 +50,410 @@ @ExtensionImpl public class AutoUnboxingInspection extends BaseInspection { + /** + * @noinspection StaticCollection + */ + static final Map s_unboxingMethods = new HashMap<>(8); - /** - * @noinspection StaticCollection - */ - @NonNls - static final Map s_unboxingMethods = new HashMap<>(8); - - static { - s_unboxingMethods.put("byte", "byteValue"); - s_unboxingMethods.put("short", "shortValue"); - s_unboxingMethods.put("int", "intValue"); - s_unboxingMethods.put("long", "longValue"); - s_unboxingMethods.put("float", "floatValue"); - s_unboxingMethods.put("double", "doubleValue"); - s_unboxingMethods.put("boolean", "booleanValue"); - s_unboxingMethods.put("char", "charValue"); - } - - @Override - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.autoUnboxingDisplayName().get(); - } - - @Override - @Nonnull - public String buildErrorString(Object... infos) { - return InspectionGadgetsLocalize.autoUnboxingProblemDescriptor().get(); - } - - @Override - @Nullable - public InspectionGadgetsFix buildFix(Object... infos) { - if (infos.length == 0 || !isFixApplicable((PsiExpression) infos[0])) { - return null; + static { + s_unboxingMethods.put("byte", "byteValue"); + s_unboxingMethods.put("short", "shortValue"); + s_unboxingMethods.put("int", "intValue"); + s_unboxingMethods.put("long", "longValue"); + s_unboxingMethods.put("float", "floatValue"); + s_unboxingMethods.put("double", "doubleValue"); + s_unboxingMethods.put("boolean", "booleanValue"); + s_unboxingMethods.put("char", "charValue"); } - return new AutoUnboxingFix(); - } - private static boolean isFixApplicable(PsiExpression location) { - // conservative check to see if the result value of the postfix - // expression is used later in the same expression statement. - // Applying the quick fix in such a case would break the code - // because the explicit unboxing code would split the expression in - // multiple statements. - final PsiElement parent = location.getParent(); - if (!(parent instanceof PsiPostfixExpression)) { - return true; - } - final PsiReferenceExpression reference; - if (location instanceof PsiReferenceExpression) { - reference = (PsiReferenceExpression) location; - } else if (location instanceof PsiArrayAccessExpression) { - final PsiArrayAccessExpression arrayAccessExpression = (PsiArrayAccessExpression) location; - final PsiExpression expression = arrayAccessExpression.getArrayExpression(); - if (!(expression instanceof PsiReferenceExpression)) { - return true; - } - reference = (PsiReferenceExpression) expression; - } else { - return true; - } - final PsiElement element = reference.resolve(); - if (element == null) { - return true; + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.autoUnboxingDisplayName(); } - final PsiStatement statement = PsiTreeUtil.getParentOfType(parent, PsiStatement.class); - final LocalSearchScope scope = new LocalSearchScope(statement); - final Query query = ReferencesSearch.search(element, scope); - final Collection references = query.findAll(); - return references.size() <= 1; - } - private static class AutoUnboxingFix extends InspectionGadgetsFix { @Override @Nonnull - public String getFamilyName() { - return InspectionGadgetsLocalize.autoUnboxingMakeUnboxingExplicitQuickfix().get(); + public String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.autoUnboxingProblemDescriptor().get(); } @Override - public void doFix(Project project, ProblemDescriptor descriptor) { - final PsiExpression expression = (PsiExpression) descriptor.getPsiElement(); - final PsiType type = expression.getType(); - if (type == null) { - return; - } - final PsiPrimitiveType unboxedType = - (PsiPrimitiveType) ExpectedTypeUtils.findExpectedType(expression, false, true); - if (unboxedType == null) { - return; - } - final String newExpressionText = buildNewExpressionText(expression, unboxedType); - final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); - final PsiElementFactory factory = psiFacade.getElementFactory(); - final PsiElement parent = expression.getParent(); - final String expressionText = expression.getText(); - if (parent instanceof PsiTypeCastExpression) { - final PsiTypeCastExpression typeCastExpression = (PsiTypeCastExpression) parent; - PsiReplacementUtil.replaceExpression(typeCastExpression, newExpressionText); - } else if (parent instanceof PsiPrefixExpression && !unboxedType.equalsToText("boolean")) { - final PsiPrefixExpression prefixExpression = (PsiPrefixExpression) parent; - final IElementType tokenType = prefixExpression.getOperationTokenType(); - if (JavaTokenType.PLUSPLUS.equals(tokenType)) { - PsiReplacementUtil.replaceExpression(prefixExpression, expressionText + '=' + newExpressionText + "+1"); - } else if (JavaTokenType.MINUSMINUS.equals(tokenType)) { - PsiReplacementUtil.replaceExpression(prefixExpression, expressionText + '=' + newExpressionText + "-1"); - } else { - PsiReplacementUtil.replaceExpression(prefixExpression, prefixExpression.getOperationSign().getText() + newExpressionText); + @Nullable + public InspectionGadgetsFix buildFix(Object... infos) { + if (infos.length == 0 || !isFixApplicable((PsiExpression) infos[0])) { + return null; + } + return new AutoUnboxingFix(); + } + + private static boolean isFixApplicable(PsiExpression location) { + // conservative check to see if the result value of the postfix + // expression is used later in the same expression statement. + // Applying the quick fix in such a case would break the code + // because the explicit unboxing code would split the expression in + // multiple statements. + final PsiElement parent = location.getParent(); + if (!(parent instanceof PsiPostfixExpression)) { + return true; } - } else if (parent instanceof PsiPostfixExpression) { - final PsiPostfixExpression postfixExpression = (PsiPostfixExpression) parent; - final IElementType tokenType = postfixExpression.getOperationTokenType(); - final PsiElement grandParent = postfixExpression.getParent(); - if (grandParent instanceof PsiExpressionStatement) { - if (JavaTokenType.PLUSPLUS.equals(tokenType)) { - PsiReplacementUtil.replaceExpression(postfixExpression, expressionText + '=' + newExpressionText + "+1"); - } else if (JavaTokenType.MINUSMINUS.equals(tokenType)) { - PsiReplacementUtil.replaceExpression(postfixExpression, expressionText + '=' + newExpressionText + "-1"); - } - } else { - final PsiElement element = postfixExpression.replace(postfixExpression.getOperand()); - final PsiStatement statement = PsiTreeUtil.getParentOfType(element, PsiStatement.class); - if (statement == null) { - return; - } - final PsiStatement newStatement; - if (JavaTokenType.PLUSPLUS.equals(tokenType)) { - newStatement = factory.createStatementFromText(expressionText + '=' + newExpressionText + "+1;", statement); - } else { - newStatement = factory.createStatementFromText(expressionText + '=' + newExpressionText + "-1;", statement); - } - final PsiElement greatGrandParent = statement.getParent(); - greatGrandParent.addAfter(newStatement, statement); + final PsiReferenceExpression reference; + if (location instanceof PsiReferenceExpression) { + reference = (PsiReferenceExpression) location; } - } else if (parent instanceof PsiAssignmentExpression) { - final PsiAssignmentExpression assignmentExpression = (PsiAssignmentExpression) parent; - final PsiExpression lExpression = assignmentExpression.getLExpression(); - if (expression.equals(lExpression)) { - final PsiJavaToken operationSign = assignmentExpression.getOperationSign(); - final String operationSignText = operationSign.getText(); - final char sign = operationSignText.charAt(0); - final PsiExpression rExpression = assignmentExpression.getRExpression(); - if (rExpression == null) { - return; - } - final String text = lExpression.getText() + '=' + newExpressionText + sign + rExpression.getText(); - final PsiExpression newExpression = factory.createExpressionFromText(text, assignmentExpression); - assignmentExpression.replace(newExpression); - } else { - PsiReplacementUtil.replaceExpression(expression, newExpressionText); + else if (location instanceof PsiArrayAccessExpression) { + final PsiArrayAccessExpression arrayAccessExpression = (PsiArrayAccessExpression) location; + final PsiExpression expression = arrayAccessExpression.getArrayExpression(); + if (!(expression instanceof PsiReferenceExpression)) { + return true; + } + reference = (PsiReferenceExpression) expression; } - } else { - PsiReplacementUtil.replaceExpression(expression, newExpressionText); - } + else { + return true; + } + final PsiElement element = reference.resolve(); + if (element == null) { + return true; + } + final PsiStatement statement = PsiTreeUtil.getParentOfType(parent, PsiStatement.class); + final LocalSearchScope scope = new LocalSearchScope(statement); + final Query query = ReferencesSearch.search(element, scope); + final Collection references = query.findAll(); + return references.size() <= 1; } - private static String buildNewExpressionText(PsiExpression expression, PsiPrimitiveType unboxedType) { - final String unboxedTypeText = unboxedType.getCanonicalText(); - final String expressionText = expression.getText(); - final String boxMethodName = s_unboxingMethods.get(unboxedTypeText); - if (expression instanceof PsiTypeCastExpression) { - return '(' + expressionText + ")." + boxMethodName + "()"; - } - final String constantText = computeConstantBooleanText(expression); - if (constantText != null) { - return constantText; - } - if (expression instanceof PsiMethodCallExpression) { - final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression) expression; - if (isValueOfCall(methodCallExpression)) { - final PsiExpressionList argumentList = methodCallExpression.getArgumentList(); - final PsiExpression[] arguments = argumentList.getExpressions(); - final PsiExpression argument = arguments[0]; - return argument.getText(); + private static class AutoUnboxingFix extends InspectionGadgetsFix { + @Nonnull + @Override + public LocalizeValue getName() { + return InspectionGadgetsLocalize.autoUnboxingMakeUnboxingExplicitQuickfix(); } - } - final PsiType type = expression.getType(); - if (type != null && type.equalsToText(CommonClassNames.JAVA_LANG_OBJECT)) { - return "((" + unboxedType.getBoxedTypeName() + ')' + expressionText + ")." + boxMethodName + "()"; - } - return expressionText + '.' + boxMethodName + "()"; - } - private static boolean isValueOfCall(PsiMethodCallExpression methodCallExpression) { - final PsiExpressionList argumentList = methodCallExpression.getArgumentList(); - final PsiExpression[] arguments = argumentList.getExpressions(); - if (arguments.length != 1) { - return false; - } - final PsiExpression argument = arguments[0]; - final PsiType type = argument.getType(); - return (MethodCallUtils.isCallToMethod(methodCallExpression, CommonClassNames.JAVA_LANG_INTEGER, null, "valueOf", PsiType.INT) && PsiType.INT.equals(type)) || - (MethodCallUtils.isCallToMethod(methodCallExpression, CommonClassNames.JAVA_LANG_SHORT, null, "valueOf", PsiType.SHORT) && PsiType.SHORT.equals(type)) || - (MethodCallUtils.isCallToMethod(methodCallExpression, CommonClassNames.JAVA_LANG_BYTE, null, "valueOf", PsiType.BYTE) && PsiType.BYTE.equals(type)) || - (MethodCallUtils.isCallToMethod(methodCallExpression, CommonClassNames.JAVA_LANG_LONG, null, "valueOf", PsiType.LONG) && PsiType.LONG.equals(type)) || - (MethodCallUtils.isCallToMethod(methodCallExpression, CommonClassNames.JAVA_LANG_CHARACTER, null, "valueOf", PsiType.CHAR) && PsiType.CHAR.equals(type)) || - (MethodCallUtils.isCallToMethod(methodCallExpression, CommonClassNames.JAVA_LANG_DOUBLE, null, "valueOf", PsiType.DOUBLE) && PsiType.DOUBLE.equals(type)) || - (MethodCallUtils.isCallToMethod(methodCallExpression, CommonClassNames.JAVA_LANG_FLOAT, null, "valueOf", PsiType.FLOAT) && PsiType.FLOAT.equals(type)); - } + @Override + public void doFix(Project project, ProblemDescriptor descriptor) { + final PsiExpression expression = (PsiExpression) descriptor.getPsiElement(); + final PsiType type = expression.getType(); + if (type == null) { + return; + } + final PsiPrimitiveType unboxedType = + (PsiPrimitiveType) ExpectedTypeUtils.findExpectedType(expression, false, true); + if (unboxedType == null) { + return; + } + final String newExpressionText = buildNewExpressionText(expression, unboxedType); + final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); + final PsiElementFactory factory = psiFacade.getElementFactory(); + final PsiElement parent = expression.getParent(); + final String expressionText = expression.getText(); + if (parent instanceof PsiTypeCastExpression) { + final PsiTypeCastExpression typeCastExpression = (PsiTypeCastExpression) parent; + PsiReplacementUtil.replaceExpression(typeCastExpression, newExpressionText); + } + else if (parent instanceof PsiPrefixExpression && !unboxedType.equalsToText("boolean")) { + final PsiPrefixExpression prefixExpression = (PsiPrefixExpression) parent; + final IElementType tokenType = prefixExpression.getOperationTokenType(); + if (JavaTokenType.PLUSPLUS.equals(tokenType)) { + PsiReplacementUtil.replaceExpression(prefixExpression, expressionText + '=' + newExpressionText + "+1"); + } + else if (JavaTokenType.MINUSMINUS.equals(tokenType)) { + PsiReplacementUtil.replaceExpression(prefixExpression, expressionText + '=' + newExpressionText + "-1"); + } + else { + PsiReplacementUtil.replaceExpression( + prefixExpression, + prefixExpression.getOperationSign().getText() + newExpressionText + ); + } + } + else if (parent instanceof PsiPostfixExpression) { + final PsiPostfixExpression postfixExpression = (PsiPostfixExpression) parent; + final IElementType tokenType = postfixExpression.getOperationTokenType(); + final PsiElement grandParent = postfixExpression.getParent(); + if (grandParent instanceof PsiExpressionStatement) { + if (JavaTokenType.PLUSPLUS.equals(tokenType)) { + PsiReplacementUtil.replaceExpression(postfixExpression, expressionText + '=' + newExpressionText + "+1"); + } + else if (JavaTokenType.MINUSMINUS.equals(tokenType)) { + PsiReplacementUtil.replaceExpression(postfixExpression, expressionText + '=' + newExpressionText + "-1"); + } + } + else { + final PsiElement element = postfixExpression.replace(postfixExpression.getOperand()); + final PsiStatement statement = PsiTreeUtil.getParentOfType(element, PsiStatement.class); + if (statement == null) { + return; + } + final PsiStatement newStatement; + if (JavaTokenType.PLUSPLUS.equals(tokenType)) { + newStatement = factory.createStatementFromText(expressionText + '=' + newExpressionText + "+1;", statement); + } + else { + newStatement = factory.createStatementFromText(expressionText + '=' + newExpressionText + "-1;", statement); + } + final PsiElement greatGrandParent = statement.getParent(); + greatGrandParent.addAfter(newStatement, statement); + } + } + else if (parent instanceof PsiAssignmentExpression) { + final PsiAssignmentExpression assignmentExpression = (PsiAssignmentExpression) parent; + final PsiExpression lExpression = assignmentExpression.getLExpression(); + if (expression.equals(lExpression)) { + final PsiJavaToken operationSign = assignmentExpression.getOperationSign(); + final String operationSignText = operationSign.getText(); + final char sign = operationSignText.charAt(0); + final PsiExpression rExpression = assignmentExpression.getRExpression(); + if (rExpression == null) { + return; + } + final String text = lExpression.getText() + '=' + newExpressionText + sign + rExpression.getText(); + final PsiExpression newExpression = factory.createExpressionFromText(text, assignmentExpression); + assignmentExpression.replace(newExpression); + } + else { + PsiReplacementUtil.replaceExpression(expression, newExpressionText); + } + } + else { + PsiReplacementUtil.replaceExpression(expression, newExpressionText); + } + } - @NonNls - private static String computeConstantBooleanText(PsiExpression expression) { - if (!(expression instanceof PsiReferenceExpression)) { - return null; - } - final PsiReferenceExpression referenceExpression = (PsiReferenceExpression) expression; - final PsiElement target = referenceExpression.resolve(); - if (!(target instanceof PsiField)) { - return null; - } - final PsiField field = (PsiField) target; - final PsiClass containingClass = field.getContainingClass(); - if (containingClass == null) { - return null; - } - final String qualifiedName = containingClass.getQualifiedName(); - if (!CommonClassNames.JAVA_LANG_BOOLEAN.equals(qualifiedName)) { - return null; - } - @NonNls final String name = field.getName(); - if ("TRUE".equals(name)) { - return "true"; - } else if ("FALSE".equals(name)) { - return "false"; - } else { - return null; - } - } - } + private static String buildNewExpressionText(PsiExpression expression, PsiPrimitiveType unboxedType) { + final String unboxedTypeText = unboxedType.getCanonicalText(); + final String expressionText = expression.getText(); + final String boxMethodName = s_unboxingMethods.get(unboxedTypeText); + if (expression instanceof PsiTypeCastExpression) { + return '(' + expressionText + ")." + boxMethodName + "()"; + } + final String constantText = computeConstantBooleanText(expression); + if (constantText != null) { + return constantText; + } + if (expression instanceof PsiMethodCallExpression) { + final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression) expression; + if (isValueOfCall(methodCallExpression)) { + final PsiExpressionList argumentList = methodCallExpression.getArgumentList(); + final PsiExpression[] arguments = argumentList.getExpressions(); + final PsiExpression argument = arguments[0]; + return argument.getText(); + } + } + final PsiType type = expression.getType(); + if (type != null && type.equalsToText(CommonClassNames.JAVA_LANG_OBJECT)) { + return "((" + unboxedType.getBoxedTypeName() + ')' + expressionText + ")." + boxMethodName + "()"; + } + return expressionText + '.' + boxMethodName + "()"; + } - @Override - public boolean shouldInspect(PsiFile file) { - return PsiUtil.isLanguageLevel5OrHigher(file); - } + private static boolean isValueOfCall(PsiMethodCallExpression methodCallExpression) { + final PsiExpressionList argumentList = methodCallExpression.getArgumentList(); + final PsiExpression[] arguments = argumentList.getExpressions(); + if (arguments.length != 1) { + return false; + } + final PsiExpression argument = arguments[0]; + final PsiType type = argument.getType(); + return (MethodCallUtils.isCallToMethod( + methodCallExpression, + CommonClassNames.JAVA_LANG_INTEGER, + null, + "valueOf", + PsiType.INT + ) && PsiType.INT.equals(type)) || + (MethodCallUtils.isCallToMethod( + methodCallExpression, + CommonClassNames.JAVA_LANG_SHORT, + null, + "valueOf", + PsiType.SHORT + ) && PsiType.SHORT.equals(type)) || + (MethodCallUtils.isCallToMethod( + methodCallExpression, + CommonClassNames.JAVA_LANG_BYTE, + null, + "valueOf", + PsiType.BYTE + ) && PsiType.BYTE.equals(type)) || + (MethodCallUtils.isCallToMethod( + methodCallExpression, + CommonClassNames.JAVA_LANG_LONG, + null, + "valueOf", + PsiType.LONG + ) && PsiType.LONG.equals(type)) || + (MethodCallUtils.isCallToMethod( + methodCallExpression, + CommonClassNames.JAVA_LANG_CHARACTER, + null, + "valueOf", + PsiType.CHAR + ) && PsiType.CHAR.equals(type)) || + (MethodCallUtils.isCallToMethod( + methodCallExpression, + CommonClassNames.JAVA_LANG_DOUBLE, + null, + "valueOf", + PsiType.DOUBLE + ) && PsiType.DOUBLE.equals(type)) || + (MethodCallUtils.isCallToMethod( + methodCallExpression, + CommonClassNames.JAVA_LANG_FLOAT, + null, + "valueOf", + PsiType.FLOAT + ) && PsiType.FLOAT.equals(type)); + } - @Override - public BaseInspectionVisitor buildVisitor() { - return new AutoUnboxingVisitor(); - } + @NonNls + private static String computeConstantBooleanText(PsiExpression expression) { + if (!(expression instanceof PsiReferenceExpression)) { + return null; + } + final PsiReferenceExpression referenceExpression = (PsiReferenceExpression) expression; + final PsiElement target = referenceExpression.resolve(); + if (!(target instanceof PsiField)) { + return null; + } + final PsiField field = (PsiField) target; + final PsiClass containingClass = field.getContainingClass(); + if (containingClass == null) { + return null; + } + final String qualifiedName = containingClass.getQualifiedName(); + if (!CommonClassNames.JAVA_LANG_BOOLEAN.equals(qualifiedName)) { + return null; + } + @NonNls final String name = field.getName(); + if ("TRUE".equals(name)) { + return "true"; + } + else if ("FALSE".equals(name)) { + return "false"; + } + else { + return null; + } + } + } - private static class AutoUnboxingVisitor extends BaseInspectionVisitor { @Override - public void visitArrayAccessExpression(PsiArrayAccessExpression expression) { - super.visitArrayAccessExpression(expression); - checkExpression(expression); + public boolean shouldInspect(PsiFile file) { + return PsiUtil.isLanguageLevel5OrHigher(file); } @Override - public void visitConditionalExpression(PsiConditionalExpression expression) { - super.visitConditionalExpression(expression); - checkExpression(expression); + public BaseInspectionVisitor buildVisitor() { + return new AutoUnboxingVisitor(); } - @Override - public void visitReferenceExpression(PsiReferenceExpression expression) { - super.visitReferenceExpression(expression); - if (expression instanceof PsiMethodReferenceExpression) { - final PsiMethodReferenceExpression methodReferenceExpression = (PsiMethodReferenceExpression) expression; - if (methodReferenceExpression.isConstructor()) { - return; + private static class AutoUnboxingVisitor extends BaseInspectionVisitor { + @Override + public void visitArrayAccessExpression(PsiArrayAccessExpression expression) { + super.visitArrayAccessExpression(expression); + checkExpression(expression); } - final PsiElement referenceNameElement = methodReferenceExpression.getReferenceNameElement(); - if (referenceNameElement == null) { - return; - } - final PsiElement target = methodReferenceExpression.resolve(); - if (!(target instanceof PsiMethod)) { - return; - } - final PsiMethod method = (PsiMethod) target; - final PsiType returnType = method.getReturnType(); - if (!TypeConversionUtil.isAssignableFromPrimitiveWrapper(returnType)) { - return; - } - final PsiPrimitiveType unboxedType = PsiPrimitiveType.getUnboxedType(returnType); - if (unboxedType == null) { - return; + + @Override + public void visitConditionalExpression(PsiConditionalExpression expression) { + super.visitConditionalExpression(expression); + checkExpression(expression); } - final PsiType functionalInterfaceReturnType = LambdaUtil.getFunctionalInterfaceReturnType(methodReferenceExpression); - if (functionalInterfaceReturnType == null || !ClassUtils.isPrimitive(functionalInterfaceReturnType) || - !functionalInterfaceReturnType.isAssignableFrom(unboxedType)) { - return; + + @Override + public void visitReferenceExpression(PsiReferenceExpression expression) { + super.visitReferenceExpression(expression); + if (expression instanceof PsiMethodReferenceExpression) { + final PsiMethodReferenceExpression methodReferenceExpression = (PsiMethodReferenceExpression) expression; + if (methodReferenceExpression.isConstructor()) { + return; + } + final PsiElement referenceNameElement = methodReferenceExpression.getReferenceNameElement(); + if (referenceNameElement == null) { + return; + } + final PsiElement target = methodReferenceExpression.resolve(); + if (!(target instanceof PsiMethod)) { + return; + } + final PsiMethod method = (PsiMethod) target; + final PsiType returnType = method.getReturnType(); + if (!TypeConversionUtil.isAssignableFromPrimitiveWrapper(returnType)) { + return; + } + final PsiPrimitiveType unboxedType = PsiPrimitiveType.getUnboxedType(returnType); + if (unboxedType == null) { + return; + } + final PsiType functionalInterfaceReturnType = LambdaUtil.getFunctionalInterfaceReturnType(methodReferenceExpression); + if (functionalInterfaceReturnType == null || !ClassUtils.isPrimitive(functionalInterfaceReturnType) || + !functionalInterfaceReturnType.isAssignableFrom(unboxedType)) { + return; + } + registerError(referenceNameElement); + } + else { + checkExpression(expression); + } } - registerError(referenceNameElement); - } else { - checkExpression(expression); - } - } - @Override - public void visitNewExpression(PsiNewExpression expression) { - super.visitNewExpression(expression); - checkExpression(expression); - } + @Override + public void visitNewExpression(PsiNewExpression expression) { + super.visitNewExpression(expression); + checkExpression(expression); + } - @Override - public void visitMethodCallExpression(PsiMethodCallExpression expression) { - super.visitMethodCallExpression(expression); - final PsiMethod method = expression.resolveMethod(); - if (method != null && AnnotationUtil.isAnnotated(method, Collections.singletonList("java.lang.invoke.MethodHandle.PolymorphicSignature"))) { - return; - } - checkExpression(expression); - } + @Override + public void visitMethodCallExpression(PsiMethodCallExpression expression) { + super.visitMethodCallExpression(expression); + final PsiMethod method = expression.resolveMethod(); + if (method != null && AnnotationUtil.isAnnotated( + method, + Collections.singletonList("java.lang.invoke.MethodHandle.PolymorphicSignature") + )) { + return; + } + checkExpression(expression); + } - @Override - public void visitTypeCastExpression(PsiTypeCastExpression expression) { - super.visitTypeCastExpression(expression); - checkExpression(expression); - } + @Override + public void visitTypeCastExpression(PsiTypeCastExpression expression) { + super.visitTypeCastExpression(expression); + checkExpression(expression); + } - @Override - public void visitAssignmentExpression(PsiAssignmentExpression expression) { - super.visitAssignmentExpression(expression); - checkExpression(expression); - } + @Override + public void visitAssignmentExpression(PsiAssignmentExpression expression) { + super.visitAssignmentExpression(expression); + checkExpression(expression); + } - @Override - public void visitParenthesizedExpression(PsiParenthesizedExpression expression) { - super.visitParenthesizedExpression(expression); - checkExpression(expression); - } + @Override + public void visitParenthesizedExpression(PsiParenthesizedExpression expression) { + super.visitParenthesizedExpression(expression); + checkExpression(expression); + } - private void checkExpression(PsiExpression expression) { - if (expression.getParent() instanceof PsiParenthesizedExpression) { - return; - } - final PsiType expressionType = expression.getType(); - if (!TypeConversionUtil.isAssignableFromPrimitiveWrapper(expressionType)) { - return; - } - final PsiType expectedType = ExpectedTypeUtils.findExpectedType(expression, false, true); - if (!TypeConversionUtil.isPrimitiveAndNotNull(expectedType)) { - return; - } - if (!(expression.getParent() instanceof PsiTypeCastExpression)) { - final PsiPrimitiveType unboxedType = PsiPrimitiveType.getUnboxedType(expressionType); - if (unboxedType == null || !expectedType.isAssignableFrom(unboxedType)) { - return; + private void checkExpression(PsiExpression expression) { + if (expression.getParent() instanceof PsiParenthesizedExpression) { + return; + } + final PsiType expressionType = expression.getType(); + if (!TypeConversionUtil.isAssignableFromPrimitiveWrapper(expressionType)) { + return; + } + final PsiType expectedType = ExpectedTypeUtils.findExpectedType(expression, false, true); + if (!TypeConversionUtil.isPrimitiveAndNotNull(expectedType)) { + return; + } + if (!(expression.getParent() instanceof PsiTypeCastExpression)) { + final PsiPrimitiveType unboxedType = PsiPrimitiveType.getUnboxedType(expressionType); + if (unboxedType == null || !expectedType.isAssignableFrom(unboxedType)) { + return; + } + } + registerError(expression, expression); } - } - registerError(expression, expression); } - } } diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/jdk/EnumAsNameInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/jdk/EnumAsNameInspection.java index f386b68448..ff1d37b1f9 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/jdk/EnumAsNameInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/jdk/EnumAsNameInspection.java @@ -22,88 +22,90 @@ import com.siyeh.ig.InspectionGadgetsFix; import com.siyeh.localize.InspectionGadgetsLocalize; import consulo.annotation.component.ExtensionImpl; +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; +import org.intellij.lang.annotations.Pattern; @ExtensionImpl public class EnumAsNameInspection extends BaseInspection { + @Nonnull + @Override + @Pattern(VALID_ID_PATTERN) + public String getID() { + return "EnumAsIdentifier"; + } - @Override - @Nonnull - public String getID() { - return "EnumAsIdentifier"; - } - - @Override - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.useEnumAsIdentifierDisplayName().get(); - } - - @Override - @Nonnull - public String buildErrorString(Object... infos) { - return InspectionGadgetsLocalize.useEnumAsIdentifierProblemDescriptor().get(); - } - - @Override - protected InspectionGadgetsFix buildFix(Object... infos) { - return new RenameFix(); - } - - @Override - protected boolean buildQuickFixesOnlyForOnTheFlyErrors() { - return true; - } - - @Override - public BaseInspectionVisitor buildVisitor() { - return new EnumAsNameVisitor(); - } - - private static class EnumAsNameVisitor extends BaseInspectionVisitor { + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.useEnumAsIdentifierDisplayName(); + } @Override - public void visitVariable(@Nonnull PsiVariable variable) { - super.visitVariable(variable); - final String variableName = variable.getName(); - if (!PsiKeyword.ENUM.equals(variableName)) { - return; - } - registerVariableError(variable); + @Nonnull + public String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.useEnumAsIdentifierProblemDescriptor().get(); } @Override - public void visitMethod(@Nonnull PsiMethod method) { - super.visitMethod(method); - final String name = method.getName(); - if (!PsiKeyword.ENUM.equals(name)) { - return; - } - registerMethodError(method); + protected InspectionGadgetsFix buildFix(Object... infos) { + return new RenameFix(); } @Override - public void visitClass(@Nonnull PsiClass aClass) { - //note: no call to super, to avoid drill-down - final String name = aClass.getName(); - if (!PsiKeyword.ENUM.equals(name)) { - return; - } - final PsiTypeParameterList params = aClass.getTypeParameterList(); - if (params != null) { - params.accept(this); - } - registerClassError(aClass); + protected boolean buildQuickFixesOnlyForOnTheFlyErrors() { + return true; } @Override - public void visitTypeParameter(PsiTypeParameter parameter) { - super.visitTypeParameter(parameter); - final String name = parameter.getName(); - if (!PsiKeyword.ENUM.equals(name)) { - return; - } - registerTypeParameterError(parameter); + public BaseInspectionVisitor buildVisitor() { + return new EnumAsNameVisitor(); + } + + private static class EnumAsNameVisitor extends BaseInspectionVisitor { + + @Override + public void visitVariable(@Nonnull PsiVariable variable) { + super.visitVariable(variable); + final String variableName = variable.getName(); + if (!PsiKeyword.ENUM.equals(variableName)) { + return; + } + registerVariableError(variable); + } + + @Override + public void visitMethod(@Nonnull PsiMethod method) { + super.visitMethod(method); + final String name = method.getName(); + if (!PsiKeyword.ENUM.equals(name)) { + return; + } + registerMethodError(method); + } + + @Override + public void visitClass(@Nonnull PsiClass aClass) { + //note: no call to super, to avoid drill-down + final String name = aClass.getName(); + if (!PsiKeyword.ENUM.equals(name)) { + return; + } + final PsiTypeParameterList params = aClass.getTypeParameterList(); + if (params != null) { + params.accept(this); + } + registerClassError(aClass); + } + + @Override + public void visitTypeParameter(PsiTypeParameter parameter) { + super.visitTypeParameter(parameter); + final String name = parameter.getName(); + if (!PsiKeyword.ENUM.equals(name)) { + return; + } + registerTypeParameterError(parameter); + } } - } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/jdk/EnumClassInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/jdk/EnumClassInspection.java index 2da7750bb7..3722140997 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/jdk/EnumClassInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/jdk/EnumClassInspection.java @@ -20,33 +20,34 @@ import com.siyeh.ig.BaseInspectionVisitor; import com.siyeh.localize.InspectionGadgetsLocalize; import consulo.annotation.component.ExtensionImpl; +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; @ExtensionImpl public class EnumClassInspection extends BaseInspection { + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.enumeratedClassDisplayName(); + } - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.enumeratedClassDisplayName().get(); - } - - @Nonnull - public String buildErrorString(Object... infos) { - return InspectionGadgetsLocalize.enumeratedClassProblemDescriptor().get(); - } + @Nonnull + public String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.enumeratedClassProblemDescriptor().get(); + } - public BaseInspectionVisitor buildVisitor() { - return new EnumClassVisitor(); - } + public BaseInspectionVisitor buildVisitor() { + return new EnumClassVisitor(); + } - private static class EnumClassVisitor extends BaseInspectionVisitor { + private static class EnumClassVisitor extends BaseInspectionVisitor { - @Override - public void visitClass(@Nonnull PsiClass aClass) { - if (!aClass.isEnum()) { - return; - } - registerClassError(aClass); + @Override + public void visitClass(@Nonnull PsiClass aClass) { + if (!aClass.isEnum()) { + return; + } + registerClassError(aClass); + } } - } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/jdk/ForeachStatementInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/jdk/ForeachStatementInspection.java index 50aa287f13..b98f23d121 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/jdk/ForeachStatementInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/jdk/ForeachStatementInspection.java @@ -29,123 +29,130 @@ import consulo.language.editor.inspection.ProblemDescriptor; import consulo.language.psi.PsiElement; import consulo.language.util.IncorrectOperationException; +import consulo.localize.LocalizeValue; import consulo.project.Project; import jakarta.annotation.Nonnull; import org.jetbrains.annotations.NonNls; @ExtensionImpl public class ForeachStatementInspection extends BaseInspection { - - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.extendedForStatementDisplayName().get(); - } - - @Nonnull - public String buildErrorString(Object... infos) { - return InspectionGadgetsLocalize.extendedForStatementProblemDescriptor().get(); - } - - protected InspectionGadgetsFix buildFix(Object... infos) { - return new ForEachFix(); - } - - private static class ForEachFix extends InspectionGadgetsFix { + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.extendedForStatementDisplayName(); + } @Nonnull - public String getName() { - return InspectionGadgetsLocalize.extendedForStatementReplaceQuickfix().get(); + public String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.extendedForStatementProblemDescriptor().get(); } - public void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { - final PsiElement element = descriptor.getPsiElement(); - final PsiForeachStatement statement = (PsiForeachStatement)element.getParent(); - final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project); - assert statement != null; - final PsiExpression iteratedValue = statement.getIteratedValue(); - if (iteratedValue == null) { - return; - } - @NonNls final StringBuilder newStatement = new StringBuilder(); - final PsiParameter iterationParameter = statement.getIterationParameter(); - final JavaCodeStyleSettings codeStyleSettings = CodeStyleSettingsManager.getSettings(project).getCustomSettings(JavaCodeStyleSettings.class); - if (iteratedValue.getType() instanceof PsiArrayType) { - final PsiType type = iterationParameter.getType(); - final String index = codeStyleManager.suggestUniqueVariableName("i", statement, true); - newStatement.append("for(int ").append(index).append(" = 0;"); - newStatement.append(index).append('<').append(iteratedValue.getText()).append(".length;"); - newStatement.append(index).append("++)").append("{ "); - if (codeStyleSettings.GENERATE_FINAL_LOCALS) { - newStatement.append("final "); - } - newStatement.append(type.getCanonicalText()).append(' ').append(iterationParameter.getName()); - newStatement.append(" = ").append(iteratedValue.getText()).append('[').append(index).append("];"); - } - else { - @NonNls final StringBuilder methodCall = new StringBuilder(); - if (ParenthesesUtils.getPrecedence(iteratedValue) > ParenthesesUtils.METHOD_CALL_PRECEDENCE) { - methodCall.append('(').append(iteratedValue.getText()).append(')'); - } - else { - methodCall.append(iteratedValue.getText()); - } - methodCall.append(".iterator()"); - final PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory(); - final PsiExpression iteratorCall = factory.createExpressionFromText(methodCall.toString(), iteratedValue); - final PsiType variableType = GenericsUtil.getVariableTypeByExpressionType(iteratorCall.getType()); - if (variableType == null) { - return; - } - final PsiType parameterType = iterationParameter.getType(); - final String typeText = parameterType.getCanonicalText(); - newStatement.append("for(").append(variableType.getCanonicalText()).append(' '); - final String iterator = codeStyleManager.suggestUniqueVariableName("iterator", statement, true); - newStatement.append(iterator).append("=").append(iteratorCall.getText()).append(';'); - newStatement.append(iterator).append(".hasNext();){"); - if (codeStyleSettings.GENERATE_FINAL_LOCALS) { - newStatement.append("final "); - } - newStatement.append(typeText).append(' ').append(iterationParameter.getName()).append(" = ").append(iterator).append(".next();"); - } - final PsiStatement body = statement.getBody(); - if (body instanceof PsiBlockStatement) { - final PsiBlockStatement blockStatement = (PsiBlockStatement)body; - final PsiCodeBlock block = blockStatement.getCodeBlock(); - final PsiElement[] children = block.getChildren(); - for (int i = 1; i < children.length - 1; i++) { - //skip the braces - newStatement.append(children[i].getText()); - } - } - else { - final String bodyText; - if (body == null) { - bodyText = ""; + protected InspectionGadgetsFix buildFix(Object... infos) { + return new ForEachFix(); + } + + private static class ForEachFix extends InspectionGadgetsFix { + @Nonnull + @Override + public LocalizeValue getName() { + return InspectionGadgetsLocalize.extendedForStatementReplaceQuickfix(); } - else { - bodyText = body.getText(); + + public void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { + final PsiElement element = descriptor.getPsiElement(); + final PsiForeachStatement statement = (PsiForeachStatement) element.getParent(); + final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project); + assert statement != null; + final PsiExpression iteratedValue = statement.getIteratedValue(); + if (iteratedValue == null) { + return; + } + @NonNls final StringBuilder newStatement = new StringBuilder(); + final PsiParameter iterationParameter = statement.getIterationParameter(); + final JavaCodeStyleSettings codeStyleSettings = + CodeStyleSettingsManager.getSettings(project).getCustomSettings(JavaCodeStyleSettings.class); + if (iteratedValue.getType() instanceof PsiArrayType) { + final PsiType type = iterationParameter.getType(); + final String index = codeStyleManager.suggestUniqueVariableName("i", statement, true); + newStatement.append("for(int ").append(index).append(" = 0;"); + newStatement.append(index).append('<').append(iteratedValue.getText()).append(".length;"); + newStatement.append(index).append("++)").append("{ "); + if (codeStyleSettings.GENERATE_FINAL_LOCALS) { + newStatement.append("final "); + } + newStatement.append(type.getCanonicalText()).append(' ').append(iterationParameter.getName()); + newStatement.append(" = ").append(iteratedValue.getText()).append('[').append(index).append("];"); + } + else { + @NonNls final StringBuilder methodCall = new StringBuilder(); + if (ParenthesesUtils.getPrecedence(iteratedValue) > ParenthesesUtils.METHOD_CALL_PRECEDENCE) { + methodCall.append('(').append(iteratedValue.getText()).append(')'); + } + else { + methodCall.append(iteratedValue.getText()); + } + methodCall.append(".iterator()"); + final PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory(); + final PsiExpression iteratorCall = factory.createExpressionFromText(methodCall.toString(), iteratedValue); + final PsiType variableType = GenericsUtil.getVariableTypeByExpressionType(iteratorCall.getType()); + if (variableType == null) { + return; + } + final PsiType parameterType = iterationParameter.getType(); + final String typeText = parameterType.getCanonicalText(); + newStatement.append("for(").append(variableType.getCanonicalText()).append(' '); + final String iterator = codeStyleManager.suggestUniqueVariableName("iterator", statement, true); + newStatement.append(iterator).append("=").append(iteratorCall.getText()).append(';'); + newStatement.append(iterator).append(".hasNext();){"); + if (codeStyleSettings.GENERATE_FINAL_LOCALS) { + newStatement.append("final "); + } + newStatement.append(typeText) + .append(' ') + .append(iterationParameter.getName()) + .append(" = ") + .append(iterator) + .append(".next();"); + } + final PsiStatement body = statement.getBody(); + if (body instanceof PsiBlockStatement) { + final PsiBlockStatement blockStatement = (PsiBlockStatement) body; + final PsiCodeBlock block = blockStatement.getCodeBlock(); + final PsiElement[] children = block.getChildren(); + for (int i = 1; i < children.length - 1; i++) { + //skip the braces + newStatement.append(children[i].getText()); + } + } + else { + final String bodyText; + if (body == null) { + bodyText = ""; + } + else { + bodyText = body.getText(); + } + newStatement.append(bodyText); + } + newStatement.append('}'); + replaceStatementAndShortenClassNames(statement, newStatement.toString()); } - newStatement.append(bodyText); - } - newStatement.append('}'); - replaceStatementAndShortenClassNames(statement, newStatement.toString()); } - } - public BaseInspectionVisitor buildVisitor() { - return new ForeachStatementVisitor(); - } + public BaseInspectionVisitor buildVisitor() { + return new ForeachStatementVisitor(); + } - private static class ForeachStatementVisitor extends BaseInspectionVisitor { + private static class ForeachStatementVisitor extends BaseInspectionVisitor { - @Override - public void visitForeachStatement(@Nonnull PsiForeachStatement statement) { - super.visitForeachStatement(statement); - final PsiExpression iteratedValue = statement.getIteratedValue(); - if (iteratedValue == null || !InheritanceUtil.isInheritor(iteratedValue.getType(), CommonClassNames.JAVA_LANG_ITERABLE)) { - return; - } - registerStatementError(statement); + @Override + public void visitForeachStatement(@Nonnull PsiForeachStatement statement) { + super.visitForeachStatement(statement); + final PsiExpression iteratedValue = statement.getIteratedValue(); + if (iteratedValue == null || !InheritanceUtil.isInheritor(iteratedValue.getType(), CommonClassNames.JAVA_LANG_ITERABLE)) { + return; + } + registerStatementError(statement); + } } - } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/jdk/VarargParameterInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/jdk/VarargParameterInspection.java index d2abb4227e..a277ba7c6e 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/jdk/VarargParameterInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/jdk/VarargParameterInspection.java @@ -30,139 +30,142 @@ import consulo.language.psi.PsiManager; import consulo.language.psi.PsiReference; import consulo.language.psi.search.ReferencesSearch; +import consulo.localize.LocalizeValue; import consulo.project.Project; import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; +import org.intellij.lang.annotations.Pattern; import org.jetbrains.annotations.NonNls; import java.util.Collection; @ExtensionImpl public class VarargParameterInspection extends BaseInspection { + @Nonnull + @Override + @Pattern(VALID_ID_PATTERN) + public String getID() { + return "VariableArgumentMethod"; + } - @Override - @Nonnull - public String getID() { - return "VariableArgumentMethod"; - } - - @Override - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.variableArgumentMethodDisplayName().get(); - } - - @Override - @Nonnull - public String buildErrorString(Object... infos) { - return InspectionGadgetsLocalize.variableArgumentMethodProblemDescriptor().get(); - } - - @Override - @Nullable - protected InspectionGadgetsFix buildFix(Object... infos) { - return new VarargParameterFix(); - } - - private static class VarargParameterFix extends InspectionGadgetsFix { + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.variableArgumentMethodDisplayName(); + } + @Override @Nonnull - public String getName() { - return InspectionGadgetsLocalize.variableArgumentMethodQuickfix().get(); + public String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.variableArgumentMethodProblemDescriptor().get(); } @Override - protected void doFix(Project project, ProblemDescriptor descriptor) { - final PsiElement element = descriptor.getPsiElement(); - final PsiMethod method = (PsiMethod)element.getParent(); - final PsiParameterList parameterList = method.getParameterList(); - final PsiParameter[] parameters = parameterList.getParameters(); - final PsiParameter lastParameter = parameters[parameters.length - 1]; - if (!lastParameter.isVarArgs()) { - return; - } - final PsiEllipsisType type = (PsiEllipsisType)lastParameter.getType(); - final Query query = ReferencesSearch.search(method); - final PsiType componentType = type.getComponentType(); - final String typeText; - if (componentType instanceof PsiClassType) { - final PsiClassType classType = (PsiClassType)componentType; - typeText = classType.rawType().getCanonicalText(); - } else { - typeText = componentType.getCanonicalText(); - } - final Collection references = query.findAll(); - for (PsiReference reference : references) { - modifyCalls(reference, typeText, parameters.length - 1); - } - final PsiType arrayType = type.toArrayType(); - final PsiManager psiManager = lastParameter.getManager(); - final PsiElementFactory factory = JavaPsiFacade.getInstance(psiManager.getProject()).getElementFactory(); - final PsiTypeElement newTypeElement = factory.createTypeElement(arrayType); - final PsiTypeElement typeElement = lastParameter.getTypeElement(); - if (typeElement == null) { - return; - } - final PsiAnnotation annotation = AnnotationUtil.findAnnotation(method, CommonClassNames.JAVA_LANG_SAFE_VARARGS); - if (annotation != null) { - annotation.delete(); - } - typeElement.replace(newTypeElement); + @Nullable + protected InspectionGadgetsFix buildFix(Object... infos) { + return new VarargParameterFix(); } - public static void modifyCalls(PsiReference reference, String arrayTypeText, int indexOfFirstVarargArgument) { - final PsiReferenceExpression referenceExpression = (PsiReferenceExpression)reference.getElement(); - final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression)referenceExpression.getParent(); - final PsiExpressionList argumentList = methodCallExpression.getArgumentList(); - final PsiExpression[] arguments = argumentList.getExpressions(); - @NonNls final StringBuilder builder = new StringBuilder("new "); - builder.append(arrayTypeText); - builder.append("[]{"); - if (arguments.length > indexOfFirstVarargArgument) { - final PsiExpression firstArgument = arguments[indexOfFirstVarargArgument]; - final String firstArgumentText = firstArgument.getText(); - builder.append(firstArgumentText); - for (int i = indexOfFirstVarargArgument + 1; i < arguments.length; i++) { - builder.append(',').append(arguments[i].getText()); + private static class VarargParameterFix extends InspectionGadgetsFix { + @Nonnull + @Override + public LocalizeValue getName() { + return InspectionGadgetsLocalize.variableArgumentMethodQuickfix(); } - } - builder.append('}'); - final Project project = referenceExpression.getProject(); - final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project); - final PsiExpression arrayExpression = factory.createExpressionFromText(builder.toString(), referenceExpression); - if (arguments.length > indexOfFirstVarargArgument) { - final PsiExpression firstArgument = arguments[indexOfFirstVarargArgument]; - argumentList.deleteChildRange(firstArgument, arguments[arguments.length - 1]); - argumentList.add(arrayExpression); - } - else { - argumentList.add(arrayExpression); - } - final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project); - final JavaCodeStyleManager javaCodeStyleManager = JavaCodeStyleManager.getInstance(project); - javaCodeStyleManager.shortenClassReferences(argumentList); - codeStyleManager.reformat(argumentList); - } - } - @Override - public BaseInspectionVisitor buildVisitor() { - return new VarargParameterVisitor(); - } + @Override + protected void doFix(Project project, ProblemDescriptor descriptor) { + final PsiElement element = descriptor.getPsiElement(); + final PsiMethod method = (PsiMethod) element.getParent(); + final PsiParameterList parameterList = method.getParameterList(); + final PsiParameter[] parameters = parameterList.getParameters(); + final PsiParameter lastParameter = parameters[parameters.length - 1]; + if (!lastParameter.isVarArgs()) { + return; + } + final PsiEllipsisType type = (PsiEllipsisType) lastParameter.getType(); + final Query query = ReferencesSearch.search(method); + final PsiType componentType = type.getComponentType(); + final String typeText; + if (componentType instanceof PsiClassType) { + final PsiClassType classType = (PsiClassType) componentType; + typeText = classType.rawType().getCanonicalText(); + } + else { + typeText = componentType.getCanonicalText(); + } + final Collection references = query.findAll(); + for (PsiReference reference : references) { + modifyCalls(reference, typeText, parameters.length - 1); + } + final PsiType arrayType = type.toArrayType(); + final PsiManager psiManager = lastParameter.getManager(); + final PsiElementFactory factory = JavaPsiFacade.getInstance(psiManager.getProject()).getElementFactory(); + final PsiTypeElement newTypeElement = factory.createTypeElement(arrayType); + final PsiTypeElement typeElement = lastParameter.getTypeElement(); + if (typeElement == null) { + return; + } + final PsiAnnotation annotation = AnnotationUtil.findAnnotation(method, CommonClassNames.JAVA_LANG_SAFE_VARARGS); + if (annotation != null) { + annotation.delete(); + } + typeElement.replace(newTypeElement); + } - private static class VarargParameterVisitor extends BaseInspectionVisitor { + public static void modifyCalls(PsiReference reference, String arrayTypeText, int indexOfFirstVarargArgument) { + final PsiReferenceExpression referenceExpression = (PsiReferenceExpression) reference.getElement(); + final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression) referenceExpression.getParent(); + final PsiExpressionList argumentList = methodCallExpression.getArgumentList(); + final PsiExpression[] arguments = argumentList.getExpressions(); + @NonNls final StringBuilder builder = new StringBuilder("new "); + builder.append(arrayTypeText); + builder.append("[]{"); + if (arguments.length > indexOfFirstVarargArgument) { + final PsiExpression firstArgument = arguments[indexOfFirstVarargArgument]; + final String firstArgumentText = firstArgument.getText(); + builder.append(firstArgumentText); + for (int i = indexOfFirstVarargArgument + 1; i < arguments.length; i++) { + builder.append(',').append(arguments[i].getText()); + } + } + builder.append('}'); + final Project project = referenceExpression.getProject(); + final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project); + final PsiExpression arrayExpression = factory.createExpressionFromText(builder.toString(), referenceExpression); + if (arguments.length > indexOfFirstVarargArgument) { + final PsiExpression firstArgument = arguments[indexOfFirstVarargArgument]; + argumentList.deleteChildRange(firstArgument, arguments[arguments.length - 1]); + argumentList.add(arrayExpression); + } + else { + argumentList.add(arrayExpression); + } + final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project); + final JavaCodeStyleManager javaCodeStyleManager = JavaCodeStyleManager.getInstance(project); + javaCodeStyleManager.shortenClassReferences(argumentList); + codeStyleManager.reformat(argumentList); + } + } @Override - public void visitMethod(@Nonnull PsiMethod method) { - final PsiParameterList parameterList = method.getParameterList(); - if (parameterList.getParametersCount() < 1) { - return; - } - final PsiParameter[] parameters = parameterList.getParameters(); - final PsiParameter lastParameter = parameters[parameters.length - 1]; - if (lastParameter.isVarArgs()) { - registerMethodError(method); - } + public BaseInspectionVisitor buildVisitor() { + return new VarargParameterVisitor(); + } + + private static class VarargParameterVisitor extends BaseInspectionVisitor { + + @Override + public void visitMethod(@Nonnull PsiMethod method) { + final PsiParameterList parameterList = method.getParameterList(); + if (parameterList.getParametersCount() < 1) { + return; + } + final PsiParameter[] parameters = parameterList.getParameters(); + final PsiParameter lastParameter = parameters[parameters.length - 1]; + if (lastParameter.isVarArgs()) { + registerMethodError(method); + } + } } - } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/junit/AssertEqualsBetweenInconvertibleTypesInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/junit/AssertEqualsBetweenInconvertibleTypesInspection.java index af4df65c50..fb059b4e8b 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/junit/AssertEqualsBetweenInconvertibleTypesInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/junit/AssertEqualsBetweenInconvertibleTypesInspection.java @@ -23,17 +23,17 @@ import com.siyeh.ig.psiutils.TypeUtils; import com.siyeh.localize.InspectionGadgetsLocalize; import consulo.annotation.component.ExtensionImpl; +import consulo.localize.LocalizeValue; import consulo.util.lang.StringUtil; import jakarta.annotation.Nonnull; import org.jetbrains.annotations.NonNls; @ExtensionImpl public class AssertEqualsBetweenInconvertibleTypesInspection extends BaseInspection { - - @Override @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.assertequalsBetweenInconvertibleTypesDisplayName().get(); + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.assertequalsBetweenInconvertibleTypesDisplayName(); } @Override diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/junit/AssertsWithoutMessagesInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/junit/AssertsWithoutMessagesInspection.java index f672b88cc4..8eea6a413d 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/junit/AssertsWithoutMessagesInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/junit/AssertsWithoutMessagesInspection.java @@ -22,6 +22,7 @@ import com.siyeh.ig.psiutils.TypeUtils; import com.siyeh.localize.InspectionGadgetsLocalize; import consulo.annotation.component.ExtensionImpl; +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; import org.jetbrains.annotations.NonNls; @@ -30,89 +31,89 @@ @ExtensionImpl public class AssertsWithoutMessagesInspection extends BaseInspection { + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.assertsWithoutMessagesDisplayName(); + } - @Override - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.assertsWithoutMessagesDisplayName().get(); - } - - @Override - @Nonnull - public String getID() { - return "MessageMissingOnJUnitAssertion"; - } + @Override + @Nonnull + public String getID() { + return "MessageMissingOnJUnitAssertion"; + } - @Override - @Nonnull - protected String buildErrorString(Object... infos) { - return InspectionGadgetsLocalize.assertsWithoutMessagesProblemDescriptor().get(); - } + @Override + @Nonnull + protected String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.assertsWithoutMessagesProblemDescriptor().get(); + } - @Override - public BaseInspectionVisitor buildVisitor() { - return new AssertionsWithoutMessagesVisitor(); - } + @Override + public BaseInspectionVisitor buildVisitor() { + return new AssertionsWithoutMessagesVisitor(); + } - private static class AssertionsWithoutMessagesVisitor extends BaseInspectionVisitor { + private static class AssertionsWithoutMessagesVisitor extends BaseInspectionVisitor { - @NonNls private static final Set s_assertMethods = new HashSet(8); + @NonNls + private static final Set s_assertMethods = new HashSet(8); - static { - s_assertMethods.add("assertArrayEquals"); - s_assertMethods.add("assertEquals"); - s_assertMethods.add("assertFalse"); - s_assertMethods.add("assertNotNull"); - s_assertMethods.add("assertNotSame"); - s_assertMethods.add("assertNull"); - s_assertMethods.add("assertSame"); - s_assertMethods.add("assertThat"); - s_assertMethods.add("assertTrue"); - s_assertMethods.add("fail"); - } + static { + s_assertMethods.add("assertArrayEquals"); + s_assertMethods.add("assertEquals"); + s_assertMethods.add("assertFalse"); + s_assertMethods.add("assertNotNull"); + s_assertMethods.add("assertNotSame"); + s_assertMethods.add("assertNull"); + s_assertMethods.add("assertSame"); + s_assertMethods.add("assertThat"); + s_assertMethods.add("assertTrue"); + s_assertMethods.add("fail"); + } - @Override - public void visitMethodCallExpression(@Nonnull PsiMethodCallExpression expression) { - super.visitMethodCallExpression(expression); - final PsiReferenceExpression methodExpression = expression.getMethodExpression(); - final String methodName = methodExpression.getReferenceName(); - if (methodName == null || !s_assertMethods.contains(methodName)) { - return; - } - final PsiMethod method = expression.resolveMethod(); - if (method == null) { - return; - } - final PsiClass containingClass = method.getContainingClass(); - if (!InheritanceUtil.isInheritor(containingClass, "junit.framework.Assert") && - !InheritanceUtil.isInheritor(containingClass, "org.junit.Assert")) { - return; - } - final PsiParameterList parameterList = method.getParameterList(); - final int parameterCount = parameterList.getParametersCount(); - if (parameterCount < 2 && methodName.startsWith("assert")) { - registerMethodCallError(expression); - return; - } - if (parameterCount < 1) { - registerMethodCallError(expression); - return; - } - final PsiType stringType = TypeUtils.getStringType(expression); - final PsiParameter[] parameters = parameterList.getParameters(); - final PsiType parameterType1 = parameters[0].getType(); - if (!parameterType1.equals(stringType)) { - registerMethodCallError(expression); - return; - } - if (parameters.length != 2) { - return; - } - final PsiType parameterType2 = parameters[1].getType(); - if (!parameterType2.equals(stringType)) { - return; - } - registerMethodCallError(expression); + @Override + public void visitMethodCallExpression(@Nonnull PsiMethodCallExpression expression) { + super.visitMethodCallExpression(expression); + final PsiReferenceExpression methodExpression = expression.getMethodExpression(); + final String methodName = methodExpression.getReferenceName(); + if (methodName == null || !s_assertMethods.contains(methodName)) { + return; + } + final PsiMethod method = expression.resolveMethod(); + if (method == null) { + return; + } + final PsiClass containingClass = method.getContainingClass(); + if (!InheritanceUtil.isInheritor(containingClass, "junit.framework.Assert") && + !InheritanceUtil.isInheritor(containingClass, "org.junit.Assert")) { + return; + } + final PsiParameterList parameterList = method.getParameterList(); + final int parameterCount = parameterList.getParametersCount(); + if (parameterCount < 2 && methodName.startsWith("assert")) { + registerMethodCallError(expression); + return; + } + if (parameterCount < 1) { + registerMethodCallError(expression); + return; + } + final PsiType stringType = TypeUtils.getStringType(expression); + final PsiParameter[] parameters = parameterList.getParameters(); + final PsiType parameterType1 = parameters[0].getType(); + if (!parameterType1.equals(stringType)) { + registerMethodCallError(expression); + return; + } + if (parameters.length != 2) { + return; + } + final PsiType parameterType2 = parameters[1].getType(); + if (!parameterType2.equals(stringType)) { + return; + } + registerMethodCallError(expression); + } } - } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/junit/BeforeClassOrAfterClassIsPublicStaticVoidNoArgInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/junit/BeforeClassOrAfterClassIsPublicStaticVoidNoArgInspection.java index eb7831bdf5..69c111118f 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/junit/BeforeClassOrAfterClassIsPublicStaticVoidNoArgInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/junit/BeforeClassOrAfterClassIsPublicStaticVoidNoArgInspection.java @@ -21,14 +21,11 @@ import consulo.annotation.component.ExtensionImpl; @ExtensionImpl -public class BeforeClassOrAfterClassIsPublicStaticVoidNoArgInspection extends BeforeClassOrAfterClassIsPublicStaticVoidNoArgInspectionBase -{ - - @Override - protected InspectionGadgetsFix buildFix(Object... infos) - { - final PsiMethod method = (PsiMethod) infos[0]; - String targetModifier = isJunit4Annotation((String) infos[1]) ? PsiModifier.PUBLIC : PsiModifier.PACKAGE_LOCAL; - return new MakePublicStaticVoidFix(method, true, targetModifier); - } +public class BeforeClassOrAfterClassIsPublicStaticVoidNoArgInspection extends BeforeClassOrAfterClassIsPublicStaticVoidNoArgInspectionBase { + @Override + protected InspectionGadgetsFix buildFix(Object... infos) { + final PsiMethod method = (PsiMethod) infos[0]; + String targetModifier = isJunit4Annotation((String) infos[1]) ? PsiModifier.PUBLIC : PsiModifier.PACKAGE_LOCAL; + return new MakePublicStaticVoidFix(method, true, targetModifier); + } } diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/junit/BeforeClassOrAfterClassIsPublicStaticVoidNoArgInspectionBase.java b/plugin/src/main/java/com/intellij/java/impl/ig/junit/BeforeClassOrAfterClassIsPublicStaticVoidNoArgInspectionBase.java index c23d31dbc2..96e6e43d8e 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/junit/BeforeClassOrAfterClassIsPublicStaticVoidNoArgInspectionBase.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/junit/BeforeClassOrAfterClassIsPublicStaticVoidNoArgInspectionBase.java @@ -8,84 +8,78 @@ import com.siyeh.ig.psiutils.TestUtils; import com.siyeh.localize.InspectionGadgetsLocalize; import consulo.annotation.component.ExtensionImpl; +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; +import org.intellij.lang.annotations.Pattern; import java.util.Arrays; import static com.intellij.java.language.codeInsight.AnnotationUtil.CHECK_HIERARCHY; @ExtensionImpl -public class BeforeClassOrAfterClassIsPublicStaticVoidNoArgInspectionBase extends BaseInspection -{ - private static final String[] STATIC_CONFIGS = { - "org.junit.BeforeClass", - "org.junit.AfterClass", - "org.junit.jupiter.api.BeforeAll", - "org.junit.jupiter.api.AfterAll" - }; +public class BeforeClassOrAfterClassIsPublicStaticVoidNoArgInspectionBase extends BaseInspection { + private static final String[] STATIC_CONFIGS = { + "org.junit.BeforeClass", + "org.junit.AfterClass", + "org.junit.jupiter.api.BeforeAll", + "org.junit.jupiter.api.AfterAll" + }; - protected static boolean isJunit4Annotation(String annotation) - { - return annotation.endsWith("Class"); - } + protected static boolean isJunit4Annotation(String annotation) { + return annotation.endsWith("Class"); + } - @Override - @Nonnull - public String getID() - { - return "BeforeOrAfterWithIncorrectSignature"; - } + @Nonnull + @Override + @Pattern(VALID_ID_PATTERN) + public String getID() { + return "BeforeOrAfterWithIncorrectSignature"; + } - @Override - @Nonnull - public String getDisplayName() - { - return InspectionGadgetsLocalize.beforeClassOrAfterClassIsPublicStaticVoidNoArgDisplayName().get(); - } + @Override + @Nonnull + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.beforeClassOrAfterClassIsPublicStaticVoidNoArgDisplayName(); + } - @Override - @Nonnull - protected String buildErrorString(Object... infos) - { - return InspectionGadgetsLocalize.beforeClassOrAfterClassIsPublicStaticVoidNoArgProblemDescriptor(infos[1]).get(); - } + @Override + @Nonnull + protected String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.beforeClassOrAfterClassIsPublicStaticVoidNoArgProblemDescriptor(infos[1]).get(); + } - @Override - public BaseInspectionVisitor buildVisitor() - { - return new BeforeClassOrAfterClassIsPublicStaticVoidNoArgVisitor(); - } + @Override + public BaseInspectionVisitor buildVisitor() { + return new BeforeClassOrAfterClassIsPublicStaticVoidNoArgVisitor(); + } - private static class BeforeClassOrAfterClassIsPublicStaticVoidNoArgVisitor extends BaseInspectionVisitor - { + private static class BeforeClassOrAfterClassIsPublicStaticVoidNoArgVisitor extends BaseInspectionVisitor { + @Override + public void visitMethod(@Nonnull PsiMethod method) { + //note: no call to super; + String annotation = Arrays.stream(STATIC_CONFIGS) + .filter(anno -> AnnotationUtil.isAnnotated(method, anno, CHECK_HIERARCHY)) + .findFirst() + .orElse(null); + if (annotation == null) { + return; + } + final PsiType returnType = method.getReturnType(); + if (returnType == null) { + return; + } + final PsiClass targetClass = method.getContainingClass(); + if (targetClass == null) { + return; + } - @Override - public void visitMethod(@Nonnull PsiMethod method) - { - //note: no call to super; - String annotation = Arrays.stream(STATIC_CONFIGS).filter(anno -> AnnotationUtil.isAnnotated(method, anno, CHECK_HIERARCHY)).findFirst().orElse(null); - if(annotation == null) - { - return; - } - final PsiType returnType = method.getReturnType(); - if(returnType == null) - { - return; - } - final PsiClass targetClass = method.getContainingClass(); - if(targetClass == null) - { - return; - } - - final PsiParameterList parameterList = method.getParameterList(); - boolean junit4Annotation = isJunit4Annotation(annotation); - if(junit4Annotation && (parameterList.getParametersCount() != 0 || !method.hasModifierProperty(PsiModifier.PUBLIC)) || !returnType.equals(PsiType.VOID) || !method.hasModifierProperty - (PsiModifier.STATIC) && (junit4Annotation || !TestUtils.testInstancePerClass(targetClass))) - { - registerMethodError(method, method, annotation); - } - } - } + final PsiParameterList parameterList = method.getParameterList(); + boolean junit4Annotation = isJunit4Annotation(annotation); + if (junit4Annotation && (parameterList.getParametersCount() != 0 || !method.isPublic()) + || !PsiType.VOID.equals(returnType) + || !method.isStatic() && (junit4Annotation || !TestUtils.testInstancePerClass(targetClass))) { + registerMethodError(method, method, annotation); + } + } + } } diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/junit/BeforeOrAfterIsPublicVoidNoArgInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/junit/BeforeOrAfterIsPublicVoidNoArgInspection.java index 67478ec985..a0cae825d5 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/junit/BeforeOrAfterIsPublicVoidNoArgInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/junit/BeforeOrAfterIsPublicVoidNoArgInspection.java @@ -21,63 +21,66 @@ import com.siyeh.ig.psiutils.TestUtils; import com.siyeh.localize.InspectionGadgetsLocalize; import consulo.annotation.component.ExtensionImpl; +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; +import org.intellij.lang.annotations.Pattern; @ExtensionImpl public class BeforeOrAfterIsPublicVoidNoArgInspection extends BaseInspection { + @Nonnull + @Override + @Pattern(VALID_ID_PATTERN) + public String getID() { + return "BeforeOrAfterWithIncorrectSignature"; + } - @Nonnull - public String getID() { - return "BeforeOrAfterWithIncorrectSignature"; - } - - @Override - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.beforeOrAfterIsPublicVoidNoArgDisplayName().get(); - } + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.beforeOrAfterIsPublicVoidNoArgDisplayName(); + } - @Override - @Nonnull - protected String buildErrorString(Object... infos) { - return InspectionGadgetsLocalize.beforeOrAfterIsPublicVoidNoArgProblemDescriptor().get(); - } + @Override + @Nonnull + protected String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.beforeOrAfterIsPublicVoidNoArgProblemDescriptor().get(); + } - @Override - public BaseInspectionVisitor buildVisitor() { - return new BeforeOrAfterIsPublicVoidNoArgVisitor(); - } + @Override + public BaseInspectionVisitor buildVisitor() { + return new BeforeOrAfterIsPublicVoidNoArgVisitor(); + } - private static class BeforeOrAfterIsPublicVoidNoArgVisitor - extends BaseInspectionVisitor { + private static class BeforeOrAfterIsPublicVoidNoArgVisitor + extends BaseInspectionVisitor { - @Override - public void visitMethod(@Nonnull PsiMethod method) { - //note: no call to super; - if (!TestUtils.isJUnit4BeforeOrAfterMethod(method)) { - return; - } - final PsiType returnType = method.getReturnType(); - if (returnType == null) { - return; - } - final PsiClass targetClass = method.getContainingClass(); - if (targetClass == null) { - return; - } - final PsiParameterList parameterList = method.getParameterList(); - if (parameterList.getParametersCount() != 0) { - registerMethodError(method); - } - else if (!returnType.equals(PsiType.VOID)) { - registerMethodError(method); - } - else if (!method.hasModifierProperty(PsiModifier.PUBLIC)) { - registerMethodError(method); - } - else if (method.hasModifierProperty(PsiModifier.STATIC)) { - registerMethodError(method); - } + @Override + public void visitMethod(@Nonnull PsiMethod method) { + //note: no call to super; + if (!TestUtils.isJUnit4BeforeOrAfterMethod(method)) { + return; + } + final PsiType returnType = method.getReturnType(); + if (returnType == null) { + return; + } + final PsiClass targetClass = method.getContainingClass(); + if (targetClass == null) { + return; + } + final PsiParameterList parameterList = method.getParameterList(); + if (parameterList.getParametersCount() != 0) { + registerMethodError(method); + } + else if (!returnType.equals(PsiType.VOID)) { + registerMethodError(method); + } + else if (!method.hasModifierProperty(PsiModifier.PUBLIC)) { + registerMethodError(method); + } + else if (method.hasModifierProperty(PsiModifier.STATIC)) { + registerMethodError(method); + } + } } - } } diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/junit/ConstantJUnitAssertArgumentInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/junit/ConstantJUnitAssertArgumentInspection.java index 8c78700e96..1818219169 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/junit/ConstantJUnitAssertArgumentInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/junit/ConstantJUnitAssertArgumentInspection.java @@ -22,8 +22,8 @@ import com.siyeh.ig.BaseInspectionVisitor; import com.siyeh.localize.InspectionGadgetsLocalize; import consulo.annotation.component.ExtensionImpl; +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; -import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NonNls; import java.util.HashSet; @@ -31,63 +31,60 @@ @ExtensionImpl public class ConstantJUnitAssertArgumentInspection extends BaseInspection { + private static final Set ASSERT_METHODS = new HashSet<>(); - @NonNls - private static final Set ASSERT_METHODS = new HashSet<>(); - - static { - ASSERT_METHODS.add("assertTrue"); - ASSERT_METHODS.add("assertFalse"); - ASSERT_METHODS.add("assertNull"); - ASSERT_METHODS.add("assertNotNull"); - } + static { + ASSERT_METHODS.add("assertTrue"); + ASSERT_METHODS.add("assertFalse"); + ASSERT_METHODS.add("assertNull"); + ASSERT_METHODS.add("assertNotNull"); + } - @Override - @Nls - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.constantJunitAssertArgumentDisplayName().get(); - } + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.constantJunitAssertArgumentDisplayName(); + } - @Override - @Nonnull - protected String buildErrorString(Object... infos) { - return InspectionGadgetsLocalize.constantJunitAssertArgumentProblemDescriptor().get(); - } + @Override + @Nonnull + protected String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.constantJunitAssertArgumentProblemDescriptor().get(); + } - @Override - public BaseInspectionVisitor buildVisitor() { - return new ConstantJUnitAssertArgumentVisitor(); - } + @Override + public BaseInspectionVisitor buildVisitor() { + return new ConstantJUnitAssertArgumentVisitor(); + } - private static class ConstantJUnitAssertArgumentVisitor extends BaseInspectionVisitor { + private static class ConstantJUnitAssertArgumentVisitor extends BaseInspectionVisitor { - @Override - public void visitMethodCallExpression(PsiMethodCallExpression expression) { - final PsiReferenceExpression methodExpression = expression.getMethodExpression(); - @NonNls final String methodName = methodExpression.getReferenceName(); - if (!ASSERT_METHODS.contains(methodName)) { - return; - } - final PsiMethod method = expression.resolveMethod(); - if (method == null) { - return; - } - final PsiClass containingClass = method.getContainingClass(); - if (!InheritanceUtil.isInheritor(containingClass, "junit.framework.Assert") && - !InheritanceUtil.isInheritor(containingClass, "org.junit.Assert")) { - return; - } - final PsiExpressionList argumentList = expression.getArgumentList(); - final PsiExpression[] arguments = argumentList.getExpressions(); - if (arguments.length == 0) { - return; - } - final PsiExpression lastArgument = arguments[arguments.length - 1]; - if (!PsiUtil.isConstantExpression(lastArgument)) { - return; - } - registerError(lastArgument); + @Override + public void visitMethodCallExpression(PsiMethodCallExpression expression) { + final PsiReferenceExpression methodExpression = expression.getMethodExpression(); + @NonNls final String methodName = methodExpression.getReferenceName(); + if (!ASSERT_METHODS.contains(methodName)) { + return; + } + final PsiMethod method = expression.resolveMethod(); + if (method == null) { + return; + } + final PsiClass containingClass = method.getContainingClass(); + if (!InheritanceUtil.isInheritor(containingClass, "junit.framework.Assert") && + !InheritanceUtil.isInheritor(containingClass, "org.junit.Assert")) { + return; + } + final PsiExpressionList argumentList = expression.getArgumentList(); + final PsiExpression[] arguments = argumentList.getExpressions(); + if (arguments.length == 0) { + return; + } + final PsiExpression lastArgument = arguments[arguments.length - 1]; + if (!PsiUtil.isConstantExpression(lastArgument)) { + return; + } + registerError(lastArgument); + } } - } } diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/junit/ExpectedExceptionNeverThrownInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/junit/ExpectedExceptionNeverThrownInspection.java index cfee974474..928221b957 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/junit/ExpectedExceptionNeverThrownInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/junit/ExpectedExceptionNeverThrownInspection.java @@ -23,19 +23,17 @@ import com.siyeh.ig.BaseInspectionVisitor; import com.siyeh.localize.InspectionGadgetsLocalize; import consulo.annotation.component.ExtensionImpl; +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; -import org.jetbrains.annotations.Nls; import java.util.Set; @ExtensionImpl -public class ExpectedExceptionNeverThrownInspection - extends BaseInspection { - @Nls +public class ExpectedExceptionNeverThrownInspection extends BaseInspection { @Nonnull @Override - public String getDisplayName() { - return InspectionGadgetsLocalize.expectedExceptionNeverThrownDisplayName().get(); + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.expectedExceptionNeverThrownDisplayName(); } @Nonnull diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/junit/IgnoredJUnitTestInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/junit/IgnoredJUnitTestInspection.java index 877ab6819e..0966b06dc5 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/junit/IgnoredJUnitTestInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/junit/IgnoredJUnitTestInspection.java @@ -24,61 +24,62 @@ import consulo.language.psi.PsiElement; import consulo.language.psi.PsiNamedElement; import consulo.language.psi.util.PsiTreeUtil; +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; -import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NonNls; @ExtensionImpl public class IgnoredJUnitTestInspection extends BaseInspection { - @Nls - @Nonnull - @Override - public String getDisplayName() { - return InspectionGadgetsLocalize.ignoredJunitTestDisplayName().get(); - } + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.ignoredJunitTestDisplayName(); + } - @Nonnull - @Override - @RequiredReadAction - protected String buildErrorString(Object... infos) { - final PsiNamedElement info = (PsiNamedElement)infos[0]; - return info instanceof PsiClass - ? InspectionGadgetsLocalize.ignoredJunitTestClassproblemDescriptor(info.getName()).get() - : InspectionGadgetsLocalize.ignoredJunitTestMethodProblemDescriptor(info.getName()).get(); - } + @Nonnull + @Override + @RequiredReadAction + protected String buildErrorString(Object... infos) { + final PsiNamedElement info = (PsiNamedElement) infos[0]; + return info instanceof PsiClass + ? InspectionGadgetsLocalize.ignoredJunitTestClassproblemDescriptor(info.getName()).get() + : InspectionGadgetsLocalize.ignoredJunitTestMethodProblemDescriptor(info.getName()).get(); + } - @Override - public BaseInspectionVisitor buildVisitor() { - return new IgnoredJUnitTestVisitor(); - } + @Override + public BaseInspectionVisitor buildVisitor() { + return new IgnoredJUnitTestVisitor(); + } - private static class IgnoredJUnitTestVisitor extends BaseInspectionVisitor { + private static class IgnoredJUnitTestVisitor extends BaseInspectionVisitor { - @Override - public void visitAnnotation(PsiAnnotation annotation) { - super.visitAnnotation(annotation); - final PsiModifierListOwner modifierListOwner = - PsiTreeUtil.getParentOfType(annotation, - PsiModifierListOwner.class); - if (!(modifierListOwner instanceof PsiClass || - modifierListOwner instanceof PsiMethod)) { - return; - } - final PsiJavaCodeReferenceElement nameReferenceElement = - annotation.getNameReferenceElement(); - if (nameReferenceElement == null) { - return; - } - final PsiElement target = nameReferenceElement.resolve(); - if (!(target instanceof PsiClass)) { - return; - } - final PsiClass aClass = (PsiClass)target; - @NonNls final String qualifiedName = aClass.getQualifiedName(); - if (!"org.junit.Ignore".equals(qualifiedName)) { - return; - } - registerError(annotation, modifierListOwner); + @Override + public void visitAnnotation(PsiAnnotation annotation) { + super.visitAnnotation(annotation); + final PsiModifierListOwner modifierListOwner = + PsiTreeUtil.getParentOfType( + annotation, + PsiModifierListOwner.class + ); + if (!(modifierListOwner instanceof PsiClass || + modifierListOwner instanceof PsiMethod)) { + return; + } + final PsiJavaCodeReferenceElement nameReferenceElement = + annotation.getNameReferenceElement(); + if (nameReferenceElement == null) { + return; + } + final PsiElement target = nameReferenceElement.resolve(); + if (!(target instanceof PsiClass)) { + return; + } + final PsiClass aClass = (PsiClass) target; + @NonNls final String qualifiedName = aClass.getQualifiedName(); + if (!"org.junit.Ignore".equals(qualifiedName)) { + return; + } + registerError(annotation, modifierListOwner); + } } - } } diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/junit/JUnit3StyleTestMethodInJUnit4ClassInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/junit/JUnit3StyleTestMethodInJUnit4ClassInspection.java index cb4abda8d8..81456f1ef7 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/junit/JUnit3StyleTestMethodInJUnit4ClassInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/junit/JUnit3StyleTestMethodInJUnit4ClassInspection.java @@ -25,113 +25,111 @@ import com.siyeh.localize.InspectionGadgetsLocalize; import consulo.annotation.component.ExtensionImpl; import consulo.language.psi.PsiElement; +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; -import org.jetbrains.annotations.Nls; /** * @author Bas Leijdekkers */ @ExtensionImpl public class JUnit3StyleTestMethodInJUnit4ClassInspection extends BaseInspection { + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.junit3StyleTestMethodInJunit4ClassDisplayName(); + } - @Nls - @Nonnull - @Override - public String getDisplayName() { - return InspectionGadgetsLocalize.junit3StyleTestMethodInJunit4ClassDisplayName().get(); - } - - @Nonnull - @Override - protected String buildErrorString(Object... infos) { - return InspectionGadgetsLocalize.junit3StyleTestMethodInJunit4ClassProblemDescriptor().get(); - } + @Nonnull + @Override + protected String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.junit3StyleTestMethodInJunit4ClassProblemDescriptor().get(); + } - @Nullable - @Override - protected InspectionGadgetsFix buildFix(Object... infos) { - return new DelegatingFix(new AnnotateMethodFix("org.junit.Test")); - } + @Nullable + @Override + protected InspectionGadgetsFix buildFix(Object... infos) { + return new DelegatingFix(new AnnotateMethodFix("org.junit.Test")); + } - @Override - public BaseInspectionVisitor buildVisitor() { - return new JUnit3StyleTestMethodInJUnit4ClassInspectionVisitor(); - } + @Override + public BaseInspectionVisitor buildVisitor() { + return new JUnit3StyleTestMethodInJUnit4ClassInspectionVisitor(); + } - private static class JUnit3StyleTestMethodInJUnit4ClassInspectionVisitor extends BaseInspectionVisitor { + private static class JUnit3StyleTestMethodInJUnit4ClassInspectionVisitor extends BaseInspectionVisitor { - @Override - public void visitMethod(PsiMethod method) { - super.visitMethod(method); - final String name = method.getName(); - if (!name.startsWith("test")) { - return; - } - if (method.hasModifierProperty(PsiModifier.ABSTRACT) || !method.hasModifierProperty(PsiModifier.PUBLIC)) { - return; - } - if (TestUtils.isJUnit4TestMethod(method)) { - return; - } - final PsiType returnType = method.getReturnType(); - if (returnType == null || !returnType.equals(PsiType.VOID)) { - return; - } - final PsiParameterList parameterList = method.getParameterList(); - if (parameterList.getParametersCount() != 0) { - return; - } - final PsiClass containingClass = method.getContainingClass(); - if (TestUtils.isJUnitTestClass(containingClass)) { - return; - } - if (!containsReferenceToClass(containingClass, "org.junit.Test")) { - return; - } - registerMethodError(method); + @Override + public void visitMethod(PsiMethod method) { + super.visitMethod(method); + final String name = method.getName(); + if (!name.startsWith("test")) { + return; + } + if (method.hasModifierProperty(PsiModifier.ABSTRACT) || !method.hasModifierProperty(PsiModifier.PUBLIC)) { + return; + } + if (TestUtils.isJUnit4TestMethod(method)) { + return; + } + final PsiType returnType = method.getReturnType(); + if (returnType == null || !returnType.equals(PsiType.VOID)) { + return; + } + final PsiParameterList parameterList = method.getParameterList(); + if (parameterList.getParametersCount() != 0) { + return; + } + final PsiClass containingClass = method.getContainingClass(); + if (TestUtils.isJUnitTestClass(containingClass)) { + return; + } + if (!containsReferenceToClass(containingClass, "org.junit.Test")) { + return; + } + registerMethodError(method); + } } - } - public static boolean containsReferenceToClass(PsiElement element, String fullyQualifiedName) { - final ClassReferenceVisitor visitor = new ClassReferenceVisitor(fullyQualifiedName); - element.accept(visitor); - return visitor.isReferenceFound(); - } + public static boolean containsReferenceToClass(PsiElement element, String fullyQualifiedName) { + final ClassReferenceVisitor visitor = new ClassReferenceVisitor(fullyQualifiedName); + element.accept(visitor); + return visitor.isReferenceFound(); + } - private static class ClassReferenceVisitor extends JavaRecursiveElementVisitor { + private static class ClassReferenceVisitor extends JavaRecursiveElementVisitor { - private final String fullyQualifiedName; - private boolean referenceFound = false; + private final String fullyQualifiedName; + private boolean referenceFound = false; - private ClassReferenceVisitor(String fullyQualifiedName) { - this.fullyQualifiedName = fullyQualifiedName; - } + private ClassReferenceVisitor(String fullyQualifiedName) { + this.fullyQualifiedName = fullyQualifiedName; + } - @Override - public void visitReferenceElement(PsiJavaCodeReferenceElement reference) { - super.visitReferenceElement(reference); - if (referenceFound) { - return; - } - if (!(reference.getParent() instanceof PsiAnnotation)) { - // optimization - return; - } - final PsiElement element = reference.resolve(); - if (!(element instanceof PsiClass) || element instanceof PsiTypeParameter) { - return; - } - final PsiClass aClass = (PsiClass)element; - final String classQualifiedName = aClass.getQualifiedName(); - if (classQualifiedName == null || !classQualifiedName.equals(fullyQualifiedName)) { - return; - } - referenceFound = true; - } + @Override + public void visitReferenceElement(PsiJavaCodeReferenceElement reference) { + super.visitReferenceElement(reference); + if (referenceFound) { + return; + } + if (!(reference.getParent() instanceof PsiAnnotation)) { + // optimization + return; + } + final PsiElement element = reference.resolve(); + if (!(element instanceof PsiClass) || element instanceof PsiTypeParameter) { + return; + } + final PsiClass aClass = (PsiClass) element; + final String classQualifiedName = aClass.getQualifiedName(); + if (classQualifiedName == null || !classQualifiedName.equals(fullyQualifiedName)) { + return; + } + referenceFound = true; + } - public boolean isReferenceFound() { - return referenceFound; + public boolean isReferenceFound() { + return referenceFound; + } } - } } diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/junit/JUnit4AnnotatedMethodInJUnit3TestCaseInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/junit/JUnit4AnnotatedMethodInJUnit3TestCaseInspection.java index 34fd104065..29136bb450 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/junit/JUnit4AnnotatedMethodInJUnit3TestCaseInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/junit/JUnit4AnnotatedMethodInJUnit3TestCaseInspection.java @@ -27,9 +27,9 @@ import consulo.annotation.component.ExtensionImpl; import consulo.language.editor.inspection.ProblemDescriptor; import consulo.language.psi.PsiElement; +import consulo.localize.LocalizeValue; import consulo.project.Project; import jakarta.annotation.Nonnull; -import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NonNls; import java.util.ArrayList; @@ -37,262 +37,260 @@ @ExtensionImpl public class JUnit4AnnotatedMethodInJUnit3TestCaseInspection extends BaseInspection { - - private static final String IGNORE = "org.junit.Ignore"; - - @Override - @Nls - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.junit4TestMethodInClassExtendingJunit3TestcaseDisplayName().get(); - } - - @Override - @Nonnull - protected String buildErrorString(Object... infos) { - if (AnnotationUtil.isAnnotated((PsiMethod)infos[1], IGNORE, false)) { - return InspectionGadgetsLocalize.ignoreTestMethodInClassExtendingJunit3TestcaseProblemDescriptor().get(); - } - return InspectionGadgetsLocalize.junit4TestMethodInClassExtendingJunit3TestcaseProblemDescriptor().get(); - } - - @Override - public boolean isEnabledByDefault() { - return true; - } - - @Nonnull - @Override - protected InspectionGadgetsFix[] buildFixes(Object... infos) { - final List fixes = new ArrayList(3); - final PsiMethod method = (PsiMethod)infos[1]; - if (AnnotationUtil.isAnnotated(method, IGNORE, false)) { - fixes.add(new RemoveIgnoreAndRename(method)); - } - if (TestUtils.isJUnit4TestMethod(method)) { - fixes.add(new RemoveTestAnnotationFix()); - } - final PsiClass aClass = (PsiClass)infos[0]; - final String className = aClass.getName(); - fixes.add(new ConvertToJUnit4Fix(className)); - return fixes.toArray(new InspectionGadgetsFix[fixes.size()]); - } - - private static void deleteAnnotation(ProblemDescriptor descriptor, final String qualifiedName) { - final PsiElement element = descriptor.getPsiElement(); - final PsiElement parent = element.getParent(); - if (!(parent instanceof PsiModifierListOwner)) { - return; - } - final PsiModifierListOwner method = (PsiModifierListOwner)parent; - final PsiModifierList modifierList = method.getModifierList(); - if (modifierList == null) { - return; - } - final PsiAnnotation annotation = modifierList.findAnnotation(qualifiedName); - if (annotation == null) { - return; - } - annotation.delete(); - } - - private static class RemoveIgnoreAndRename extends RenameFix { - - public RemoveIgnoreAndRename(@NonNls PsiMethod method) { - super("_" + method.getName()); - } + private static final String IGNORE = "org.junit.Ignore"; @Nonnull @Override - public String getName() { - return InspectionGadgetsLocalize.ignoreTestMethodInClassExtendingJunit3TestcaseQuickfix(getTargetName()).get(); + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.junit4TestMethodInClassExtendingJunit3TestcaseDisplayName(); } @Override - public void doFix(Project project, ProblemDescriptor descriptor) { - deleteAnnotation(descriptor, IGNORE); - super.doFix(project, descriptor); - } - } - - private static class ConvertToJUnit4Fix extends InspectionGadgetsFix { - - private final String className; - - ConvertToJUnit4Fix(String className) { - this.className = className; + @Nonnull + protected String buildErrorString(Object... infos) { + if (AnnotationUtil.isAnnotated((PsiMethod) infos[1], IGNORE, false)) { + return InspectionGadgetsLocalize.ignoreTestMethodInClassExtendingJunit3TestcaseProblemDescriptor().get(); + } + return InspectionGadgetsLocalize.junit4TestMethodInClassExtendingJunit3TestcaseProblemDescriptor().get(); } @Override - @Nonnull - public String getName() { - return InspectionGadgetsLocalize.convertJunit3TestClassQuickfix(className).get(); + public boolean isEnabledByDefault() { + return true; } + @Nonnull @Override - protected void doFix(Project project, ProblemDescriptor descriptor) { - final PsiElement element = descriptor.getPsiElement(); - final PsiElement parent = element.getParent(); - if (!(parent instanceof PsiMember)) { - return; - } - final PsiMember member = (PsiMember)parent; - final PsiClass containingClass = member.getContainingClass(); - if (containingClass == null) { - return; - } - final PsiReferenceList extendsList = containingClass.getExtendsList(); - if (extendsList == null) { - return; - } - final PsiMethod[] methods = containingClass.getMethods(); - for (PsiMethod method : methods) { - @NonNls final String name = method.getName(); - if (method.hasModifierProperty(PsiModifier.STATIC)) { - continue; + protected InspectionGadgetsFix[] buildFixes(Object... infos) { + final List fixes = new ArrayList(3); + final PsiMethod method = (PsiMethod) infos[1]; + if (AnnotationUtil.isAnnotated(method, IGNORE, false)) { + fixes.add(new RemoveIgnoreAndRename(method)); } - final PsiType returnType = method.getReturnType(); - if (!PsiType.VOID.equals(returnType)) { - continue; + if (TestUtils.isJUnit4TestMethod(method)) { + fixes.add(new RemoveTestAnnotationFix()); } - final PsiModifierList modifierList = method.getModifierList(); - if (name.startsWith("test")) { - addAnnotationIfNotPresent(modifierList, "org.junit.Test"); + final PsiClass aClass = (PsiClass) infos[0]; + final String className = aClass.getName(); + fixes.add(new ConvertToJUnit4Fix(className)); + return fixes.toArray(new InspectionGadgetsFix[fixes.size()]); + } + + private static void deleteAnnotation(ProblemDescriptor descriptor, final String qualifiedName) { + final PsiElement element = descriptor.getPsiElement(); + final PsiElement parent = element.getParent(); + if (!(parent instanceof PsiModifierListOwner)) { + return; } - else if (name.equals("setUp")) { - transformSetUpOrTearDownMethod(method); - addAnnotationIfNotPresent(modifierList, "org.junit.Before"); + final PsiModifierListOwner method = (PsiModifierListOwner) parent; + final PsiModifierList modifierList = method.getModifierList(); + if (modifierList == null) { + return; } - else if (name.equals("tearDown")) { - transformSetUpOrTearDownMethod(method); - addAnnotationIfNotPresent(modifierList, "org.junit.After"); + final PsiAnnotation annotation = modifierList.findAnnotation(qualifiedName); + if (annotation == null) { + return; } - method.accept(new MethodCallModifier()); - } - final PsiJavaCodeReferenceElement[] referenceElements = extendsList.getReferenceElements(); - for (PsiJavaCodeReferenceElement referenceElement : referenceElements) { - referenceElement.delete(); - } + annotation.delete(); } - private static void addAnnotationIfNotPresent(PsiModifierList modifierList, String qualifiedAnnotationName) { - if (modifierList.findAnnotation(qualifiedAnnotationName) != null) { - return; - } - final PsiAnnotation annotation = modifierList.addAnnotation(qualifiedAnnotationName); - final Project project = modifierList.getProject(); - final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project); - codeStyleManager.shortenClassReferences(annotation); - } + private static class RemoveIgnoreAndRename extends RenameFix { - private static void transformSetUpOrTearDownMethod(PsiMethod method) { - final PsiModifierList modifierList = method.getModifierList(); - if (modifierList.hasModifierProperty(PsiModifier.PROTECTED)) { - modifierList.setModifierProperty(PsiModifier.PROTECTED, false); - } - if (!modifierList.hasModifierProperty(PsiModifier.PUBLIC)) { - modifierList.setModifierProperty(PsiModifier.PUBLIC, true); - } - final PsiAnnotation overrideAnnotation = modifierList.findAnnotation(CommonClassNames.JAVA_LANG_OVERRIDE); - if (overrideAnnotation != null) { - overrideAnnotation.delete(); - } - method.accept(new SuperLifeCycleCallRemover(method.getName())); - } + public RemoveIgnoreAndRename(@NonNls PsiMethod method) { + super("_" + method.getName()); + } - private static class SuperLifeCycleCallRemover extends JavaRecursiveElementVisitor { + @Nonnull + @Override + public String getName() { + return InspectionGadgetsLocalize.ignoreTestMethodInClassExtendingJunit3TestcaseQuickfix(getTargetName()).get(); + } - @Nonnull - private final String myLifeCycleMethodName; + @Override + public void doFix(Project project, ProblemDescriptor descriptor) { + deleteAnnotation(descriptor, IGNORE); + super.doFix(project, descriptor); + } + } - private SuperLifeCycleCallRemover(@Nonnull String lifeCycleMethodName) { - myLifeCycleMethodName = lifeCycleMethodName; - } + private static class ConvertToJUnit4Fix extends InspectionGadgetsFix { + private final String className; - @Override - public void visitMethodCallExpression(PsiMethodCallExpression expression) { - super.visitMethodCallExpression(expression); - final PsiReferenceExpression methodExpression = expression.getMethodExpression(); - final String methodName = methodExpression.getReferenceName(); - if (!myLifeCycleMethodName.equals(methodName)) { - return; + ConvertToJUnit4Fix(String className) { + this.className = className; } - final PsiExpression target = methodExpression.getQualifierExpression(); - if (!(target instanceof PsiSuperExpression)) { - return; + + @Nonnull + @Override + public LocalizeValue getName() { + return InspectionGadgetsLocalize.convertJunit3TestClassQuickfix(className); } - expression.delete(); - } - } - private static class MethodCallModifier extends JavaRecursiveElementVisitor { + @Override + protected void doFix(Project project, ProblemDescriptor descriptor) { + final PsiElement element = descriptor.getPsiElement(); + final PsiElement parent = element.getParent(); + if (!(parent instanceof PsiMember)) { + return; + } + final PsiMember member = (PsiMember) parent; + final PsiClass containingClass = member.getContainingClass(); + if (containingClass == null) { + return; + } + final PsiReferenceList extendsList = containingClass.getExtendsList(); + if (extendsList == null) { + return; + } + final PsiMethod[] methods = containingClass.getMethods(); + for (PsiMethod method : methods) { + @NonNls final String name = method.getName(); + if (method.hasModifierProperty(PsiModifier.STATIC)) { + continue; + } + final PsiType returnType = method.getReturnType(); + if (!PsiType.VOID.equals(returnType)) { + continue; + } + final PsiModifierList modifierList = method.getModifierList(); + if (name.startsWith("test")) { + addAnnotationIfNotPresent(modifierList, "org.junit.Test"); + } + else if (name.equals("setUp")) { + transformSetUpOrTearDownMethod(method); + addAnnotationIfNotPresent(modifierList, "org.junit.Before"); + } + else if (name.equals("tearDown")) { + transformSetUpOrTearDownMethod(method); + addAnnotationIfNotPresent(modifierList, "org.junit.After"); + } + method.accept(new MethodCallModifier()); + } + final PsiJavaCodeReferenceElement[] referenceElements = extendsList.getReferenceElements(); + for (PsiJavaCodeReferenceElement referenceElement : referenceElements) { + referenceElement.delete(); + } + } - @Override - public void visitMethodCallExpression(PsiMethodCallExpression expression) { - super.visitMethodCallExpression(expression); - final PsiReferenceExpression methodExpression = expression.getMethodExpression(); - if (methodExpression.getQualifierExpression() != null) { - return; + private static void addAnnotationIfNotPresent(PsiModifierList modifierList, String qualifiedAnnotationName) { + if (modifierList.findAnnotation(qualifiedAnnotationName) != null) { + return; + } + final PsiAnnotation annotation = modifierList.addAnnotation(qualifiedAnnotationName); + final Project project = modifierList.getProject(); + final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project); + codeStyleManager.shortenClassReferences(annotation); } - final PsiMethod method = expression.resolveMethod(); - if (method == null) { - return; + + private static void transformSetUpOrTearDownMethod(PsiMethod method) { + final PsiModifierList modifierList = method.getModifierList(); + if (modifierList.hasModifierProperty(PsiModifier.PROTECTED)) { + modifierList.setModifierProperty(PsiModifier.PROTECTED, false); + } + if (!modifierList.hasModifierProperty(PsiModifier.PUBLIC)) { + modifierList.setModifierProperty(PsiModifier.PUBLIC, true); + } + final PsiAnnotation overrideAnnotation = modifierList.findAnnotation(CommonClassNames.JAVA_LANG_OVERRIDE); + if (overrideAnnotation != null) { + overrideAnnotation.delete(); + } + method.accept(new SuperLifeCycleCallRemover(method.getName())); } - final PsiClass aClass = method.getContainingClass(); - if (aClass == null) { - return; + + private static class SuperLifeCycleCallRemover extends JavaRecursiveElementVisitor { + + @Nonnull + private final String myLifeCycleMethodName; + + private SuperLifeCycleCallRemover(@Nonnull String lifeCycleMethodName) { + myLifeCycleMethodName = lifeCycleMethodName; + } + + @Override + public void visitMethodCallExpression(PsiMethodCallExpression expression) { + super.visitMethodCallExpression(expression); + final PsiReferenceExpression methodExpression = expression.getMethodExpression(); + final String methodName = methodExpression.getReferenceName(); + if (!myLifeCycleMethodName.equals(methodName)) { + return; + } + final PsiExpression target = methodExpression.getQualifierExpression(); + if (!(target instanceof PsiSuperExpression)) { + return; + } + expression.delete(); + } } - final String name = aClass.getQualifiedName(); - if (!"junit.framework.Assert".equals(name)) { - return; + + private static class MethodCallModifier extends JavaRecursiveElementVisitor { + + @Override + public void visitMethodCallExpression(PsiMethodCallExpression expression) { + super.visitMethodCallExpression(expression); + final PsiReferenceExpression methodExpression = expression.getMethodExpression(); + if (methodExpression.getQualifierExpression() != null) { + return; + } + final PsiMethod method = expression.resolveMethod(); + if (method == null) { + return; + } + final PsiClass aClass = method.getContainingClass(); + if (aClass == null) { + return; + } + final String name = aClass.getQualifiedName(); + if (!"junit.framework.Assert".equals(name)) { + return; + } + @NonNls final String newExpressionText = "org.junit.Assert." + expression.getText(); + final Project project = expression.getProject(); + final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project); + final PsiExpression newExpression = factory.createExpressionFromText(newExpressionText, expression); + final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project); + final PsiElement replacedExpression = expression.replace(newExpression); + codeStyleManager.shortenClassReferences(replacedExpression); + } } - @NonNls final String newExpressionText = "org.junit.Assert." + expression.getText(); - final Project project = expression.getProject(); - final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project); - final PsiExpression newExpression = factory.createExpressionFromText(newExpressionText, expression); - final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project); - final PsiElement replacedExpression = expression.replace(newExpression); - codeStyleManager.shortenClassReferences(replacedExpression); - } } - } - private static class RemoveTestAnnotationFix extends InspectionGadgetsFix { + private static class RemoveTestAnnotationFix extends InspectionGadgetsFix { - @Override - @Nonnull - public String getName() { - return InspectionGadgetsLocalize.removeJunit4TestAnnotationQuickfix().get(); + @Override + @Nonnull + public String getName() { + return InspectionGadgetsLocalize.removeJunit4TestAnnotationQuickfix().get(); + } + + @Override + protected void doFix(Project project, ProblemDescriptor descriptor) { + deleteAnnotation(descriptor, "org.junit.Test"); + } } @Override - protected void doFix(Project project, ProblemDescriptor descriptor) { - deleteAnnotation(descriptor, "org.junit.Test"); + public BaseInspectionVisitor buildVisitor() { + return new Junit4AnnotatedMethodInJunit3TestCaseVisitor(); } - } - - @Override - public BaseInspectionVisitor buildVisitor() { - return new Junit4AnnotatedMethodInJunit3TestCaseVisitor(); - } - private static class Junit4AnnotatedMethodInJunit3TestCaseVisitor extends BaseInspectionVisitor { - - @Override - public void visitMethod(PsiMethod method) { - super.visitMethod(method); - final PsiClass containingClass = method.getContainingClass(); - if (containingClass == null) { - return; - } - if (!TestUtils.isJUnitTestClass(containingClass)) { - return; - } - if (AnnotationUtil.isAnnotated(method, IGNORE, false) && method.getName().startsWith("test")) { - registerMethodError(method, containingClass, method); - } else if (TestUtils.isJUnit4TestMethod(method)) { - registerMethodError(method, containingClass, method); - } + private static class Junit4AnnotatedMethodInJunit3TestCaseVisitor extends BaseInspectionVisitor { + + @Override + public void visitMethod(PsiMethod method) { + super.visitMethod(method); + final PsiClass containingClass = method.getContainingClass(); + if (containingClass == null) { + return; + } + if (!TestUtils.isJUnitTestClass(containingClass)) { + return; + } + if (AnnotationUtil.isAnnotated(method, IGNORE, false) && method.getName().startsWith("test")) { + registerMethodError(method, containingClass, method); + } + else if (TestUtils.isJUnit4TestMethod(method)) { + registerMethodError(method, containingClass, method); + } + } } - } } diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/junit/JUnitAbstractTestClassNamingConventionInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/junit/JUnitAbstractTestClassNamingConventionInspection.java index 7742ade3b6..4af395e20a 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/junit/JUnitAbstractTestClassNamingConventionInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/junit/JUnitAbstractTestClassNamingConventionInspection.java @@ -27,100 +27,102 @@ import com.siyeh.localize.InspectionGadgetsLocalize; import consulo.annotation.component.ExtensionImpl; import consulo.language.psi.PsiElement; +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; @ExtensionImpl -public class JUnitAbstractTestClassNamingConventionInspection - extends ConventionInspection { +public class JUnitAbstractTestClassNamingConventionInspection extends ConventionInspection { + private static final int DEFAULT_MIN_LENGTH = 12; + private static final int DEFAULT_MAX_LENGTH = 64; - private static final int DEFAULT_MIN_LENGTH = 12; - private static final int DEFAULT_MAX_LENGTH = 64; - - @Override - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.junitAbstractTestClassNamingConventionDisplayName().get(); - } - - @Override - protected InspectionGadgetsFix buildFix(Object... infos) { - return new RenameFix(); - } + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.junitAbstractTestClassNamingConventionDisplayName(); + } - @Override - protected boolean buildQuickFixesOnlyForOnTheFlyErrors() { - return true; - } + @Override + protected InspectionGadgetsFix buildFix(Object... infos) { + return new RenameFix(); + } - @Override - @Nonnull - public String buildErrorString(Object... infos) { - final String className = (String)infos[0]; - if (className.length() < getMinLength()) { - return InspectionGadgetsBundle.message( - "junit.abstract.test.class.naming.convention.problem.descriptor.short"); + @Override + protected boolean buildQuickFixesOnlyForOnTheFlyErrors() { + return true; } - else if (className.length() > getMaxLength()) { - return InspectionGadgetsBundle.message( - "junit.abstract.test.class.naming.convention.problem.descriptor.long"); + + @Override + @Nonnull + public String buildErrorString(Object... infos) { + final String className = (String) infos[0]; + if (className.length() < getMinLength()) { + return InspectionGadgetsBundle.message( + "junit.abstract.test.class.naming.convention.problem.descriptor.short"); + } + else if (className.length() > getMaxLength()) { + return InspectionGadgetsBundle.message( + "junit.abstract.test.class.naming.convention.problem.descriptor.long"); + } + return InspectionGadgetsBundle.message( + "junit.abstract.test.class.naming.convention.problem.descriptor.regex.mismatch", + getRegex() + ); } - return InspectionGadgetsBundle.message( - "junit.abstract.test.class.naming.convention.problem.descriptor.regex.mismatch", - getRegex()); - } - @Override - protected String getDefaultRegex() { - return "[A-Z][A-Za-z\\d]*TestCase"; - } + @Override + protected String getDefaultRegex() { + return "[A-Z][A-Za-z\\d]*TestCase"; + } - @Override - protected int getDefaultMinLength() { - return DEFAULT_MIN_LENGTH; - } + @Override + protected int getDefaultMinLength() { + return DEFAULT_MIN_LENGTH; + } - @Override - protected int getDefaultMaxLength() { - return DEFAULT_MAX_LENGTH; - } + @Override + protected int getDefaultMaxLength() { + return DEFAULT_MAX_LENGTH; + } - @Override - public BaseInspectionVisitor buildVisitor() { - return new NamingConventionsVisitor(); - } + @Override + public BaseInspectionVisitor buildVisitor() { + return new NamingConventionsVisitor(); + } - private class NamingConventionsVisitor extends BaseInspectionVisitor { + private class NamingConventionsVisitor extends BaseInspectionVisitor { - @Override - public void visitElement(PsiElement element) { - if (!(element instanceof PsiClass)) { - super.visitElement(element); - return; - } + @Override + public void visitElement(PsiElement element) { + if (!(element instanceof PsiClass)) { + super.visitElement(element); + return; + } - PsiClass aClass = (PsiClass)element; - if (aClass.isInterface() || aClass.isEnum() || - aClass.isAnnotationType()) { - return; - } - if (aClass instanceof PsiTypeParameter) { - return; - } - if (!aClass.hasModifierProperty(PsiModifier.ABSTRACT)) { - return; - } - if (!InheritanceUtil.isInheritor(aClass, - "junit.framework.TestCase")) { - return; - } - final String name = aClass.getName(); - if (name == null) { - return; - } - if (isValid(name)) { - return; - } - registerClassError(aClass, name); + PsiClass aClass = (PsiClass) element; + if (aClass.isInterface() || aClass.isEnum() || + aClass.isAnnotationType()) { + return; + } + if (aClass instanceof PsiTypeParameter) { + return; + } + if (!aClass.hasModifierProperty(PsiModifier.ABSTRACT)) { + return; + } + if (!InheritanceUtil.isInheritor( + aClass, + "junit.framework.TestCase" + )) { + return; + } + final String name = aClass.getName(); + if (name == null) { + return; + } + if (isValid(name)) { + return; + } + registerClassError(aClass, name); + } } - } } \ No newline at end of file From f6dc8f9d09758997b01a0650a078a2a81f3bc757 Mon Sep 17 00:00:00 2001 From: UNV Date: Sat, 11 Oct 2025 14:51:24 +0300 Subject: [PATCH 2/2] Reformatting AutoUnboxingInspection. --- .../siyeh/ig/psiutils/MethodCallUtils.java | 959 +++++++++--------- .../impl/ig/jdk/AutoUnboxingInspection.java | 60 +- 2 files changed, 508 insertions(+), 511 deletions(-) diff --git a/java-analysis-impl/src/main/java/com/siyeh/ig/psiutils/MethodCallUtils.java b/java-analysis-impl/src/main/java/com/siyeh/ig/psiutils/MethodCallUtils.java index 850dee49b1..ea578c57db 100644 --- a/java-analysis-impl/src/main/java/com/siyeh/ig/psiutils/MethodCallUtils.java +++ b/java-analysis-impl/src/main/java/com/siyeh/ig/psiutils/MethodCallUtils.java @@ -37,488 +37,527 @@ import static consulo.util.lang.ObjectUtil.tryCast; public class MethodCallUtils { + /** + * @noinspection StaticCollection + */ + @NonNls + private static final Set regexMethodNames = new HashSet<>(5); - /** - * @noinspection StaticCollection - */ - @NonNls - private static final Set regexMethodNames = new HashSet<>(5); - - static { - regexMethodNames.add("compile"); - regexMethodNames.add("matches"); - regexMethodNames.add("replaceFirst"); - regexMethodNames.add("replaceAll"); - regexMethodNames.add("split"); - } - - private MethodCallUtils() { - } - - @Nullable - public static String getMethodName(@Nonnull PsiMethodCallExpression expression) { - final PsiReferenceExpression method = expression.getMethodExpression(); - return method.getReferenceName(); - } - - @Nullable - public static PsiType getTargetType(@Nonnull PsiMethodCallExpression expression) { - final PsiReferenceExpression methodExpression = expression.getMethodExpression(); - final PsiExpression qualifierExpression = methodExpression.getQualifierExpression(); - if (qualifierExpression == null) { - return null; + static { + regexMethodNames.add("compile"); + regexMethodNames.add("matches"); + regexMethodNames.add("replaceFirst"); + regexMethodNames.add("replaceAll"); + regexMethodNames.add("split"); } - return qualifierExpression.getType(); - } - public static boolean isCompareToCall(@Nonnull PsiMethodCallExpression expression) { - final PsiReferenceExpression methodExpression = expression.getMethodExpression(); - if (!HardcodedMethodConstants.COMPARE_TO.equals(methodExpression.getReferenceName())) { - return false; + private MethodCallUtils() { } - final PsiMethod method = expression.resolveMethod(); - return MethodUtils.isCompareTo(method); - } - - public static boolean isCompareToIgnoreCaseCall(@Nonnull PsiMethodCallExpression expression) { - final PsiReferenceExpression methodExpression = expression.getMethodExpression(); - if (!"compareToIgnoreCase".equals(methodExpression.getReferenceName())) { - return false; - } - final PsiMethod method = expression.resolveMethod(); - return MethodUtils.isCompareToIgnoreCase(method); - } - - public static boolean isEqualsCall(PsiMethodCallExpression expression) { - final PsiReferenceExpression methodExpression = expression.getMethodExpression(); - final String name = methodExpression.getReferenceName(); - if (!HardcodedMethodConstants.EQUALS.equals(name)) { - return false; - } - final PsiMethod method = expression.resolveMethod(); - return MethodUtils.isEquals(method); - } - - public static boolean isEqualsIgnoreCaseCall(PsiMethodCallExpression expression) { - final PsiReferenceExpression methodExpression = expression.getMethodExpression(); - final String name = methodExpression.getReferenceName(); - if (!HardcodedMethodConstants.EQUALS_IGNORE_CASE.equals(name)) { - return false; - } - final PsiMethod method = expression.resolveMethod(); - return MethodUtils.isEqualsIgnoreCase(method); - } - - public static boolean isSimpleCallToMethod(@Nonnull PsiMethodCallExpression expression, - @NonNls @Nullable String calledOnClassName, - @Nullable PsiType returnType, - @NonNls @Nullable String methodName, - @NonNls @Nullable String... parameterTypeStrings) { - if (parameterTypeStrings == null) { - return isCallToMethod(expression, calledOnClassName, returnType, methodName, (PsiType[]) null); - } - final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(expression.getProject()); - final PsiElementFactory factory = psiFacade.getElementFactory(); - final PsiType[] parameterTypes = PsiType.createArray(parameterTypeStrings.length); - final GlobalSearchScope scope = expression.getResolveScope(); - for (int i = 0; i < parameterTypeStrings.length; i++) { - final String parameterTypeString = parameterTypeStrings[i]; - parameterTypes[i] = factory.createTypeByFQClassName(parameterTypeString, scope); - } - return isCallToMethod(expression, calledOnClassName, returnType, methodName, parameterTypes); - } - public static boolean isCallToStaticMethod(@Nonnull PsiMethodCallExpression expression, @NonNls @Nonnull String calledOnClassName, @NonNls @Nonnull String methodName, int parameterCount) { - PsiExpression[] args = expression.getArgumentList().getExpressions(); - if (!methodName.equals(getMethodName(expression)) || args.length < parameterCount) { - return false; - } - PsiMethod method = expression.resolveMethod(); - if (method == null || !method.hasModifierProperty(PsiModifier.STATIC) || method.getParameterList().getParametersCount() != parameterCount || !method.isVarArgs() && args.length != - parameterCount) { - return false; - } - PsiClass aClass = method.getContainingClass(); - return aClass != null && calledOnClassName.equals(aClass.getQualifiedName()); - } - - public static boolean isCallToMethod(@Nonnull PsiMethodCallExpression expression, - @NonNls @Nullable String calledOnClassName, - @Nullable PsiType returnType, - @Nullable Pattern methodNamePattern, - @Nullable PsiType... parameterTypes) { - final PsiReferenceExpression methodExpression = expression.getMethodExpression(); - if (methodNamePattern != null) { - final String referenceName = methodExpression.getReferenceName(); - if (referenceName == null) { - return false; - } - final Matcher matcher = methodNamePattern.matcher(referenceName); - if (!matcher.matches()) { - return false; - } - } - final PsiMethod method = expression.resolveMethod(); - if (method == null) { - return false; - } - if (calledOnClassName != null) { - final PsiExpression qualifier = methodExpression.getQualifierExpression(); - if (qualifier != null) { - if (!TypeUtils.expressionHasTypeOrSubtype(qualifier, calledOnClassName)) { - return false; - } - return MethodUtils.methodMatches(method, null, returnType, methodNamePattern, parameterTypes); - } + @Nullable + public static String getMethodName(@Nonnull PsiMethodCallExpression expression) { + final PsiReferenceExpression method = expression.getMethodExpression(); + return method.getReferenceName(); } - return MethodUtils.methodMatches(method, calledOnClassName, returnType, methodNamePattern, parameterTypes); - } - - public static boolean isCallToMethod(@Nonnull PsiMethodCallExpression expression, - @NonNls @Nullable String calledOnClassName, - @Nullable PsiType returnType, - @NonNls @Nullable String methodName, - @Nullable PsiType... parameterTypes) { - final PsiReferenceExpression methodExpression = expression.getMethodExpression(); - if (methodName != null) { - final String referenceName = methodExpression.getReferenceName(); - if (!methodName.equals(referenceName)) { - return false; - } + + @Nullable + public static PsiType getTargetType(@Nonnull PsiMethodCallExpression expression) { + final PsiReferenceExpression methodExpression = expression.getMethodExpression(); + final PsiExpression qualifierExpression = methodExpression.getQualifierExpression(); + if (qualifierExpression == null) { + return null; + } + return qualifierExpression.getType(); } - final PsiMethod method = expression.resolveMethod(); - if (method == null) { - return false; + + public static boolean isCompareToCall(@Nonnull PsiMethodCallExpression expression) { + final PsiReferenceExpression methodExpression = expression.getMethodExpression(); + if (!HardcodedMethodConstants.COMPARE_TO.equals(methodExpression.getReferenceName())) { + return false; + } + final PsiMethod method = expression.resolveMethod(); + return MethodUtils.isCompareTo(method); } - return MethodUtils.methodMatches(method, calledOnClassName, returnType, methodName, parameterTypes); - } - - public static boolean isCallToRegexMethod(PsiMethodCallExpression expression) { - final PsiReferenceExpression methodExpression = expression.getMethodExpression(); - final String name = methodExpression.getReferenceName(); - if (!regexMethodNames.contains(name)) { - return false; + + public static boolean isCompareToIgnoreCaseCall(@Nonnull PsiMethodCallExpression expression) { + final PsiReferenceExpression methodExpression = expression.getMethodExpression(); + if (!"compareToIgnoreCase".equals(methodExpression.getReferenceName())) { + return false; + } + final PsiMethod method = expression.resolveMethod(); + return MethodUtils.isCompareToIgnoreCase(method); } - final PsiMethod method = expression.resolveMethod(); - if (method == null) { - return false; + + public static boolean isEqualsCall(PsiMethodCallExpression expression) { + final PsiReferenceExpression methodExpression = expression.getMethodExpression(); + final String name = methodExpression.getReferenceName(); + if (!HardcodedMethodConstants.EQUALS.equals(name)) { + return false; + } + final PsiMethod method = expression.resolveMethod(); + return MethodUtils.isEquals(method); } - final PsiClass containingClass = method.getContainingClass(); - if (containingClass == null) { - return false; + + public static boolean isEqualsIgnoreCaseCall(PsiMethodCallExpression expression) { + final PsiReferenceExpression methodExpression = expression.getMethodExpression(); + final String name = methodExpression.getReferenceName(); + if (!HardcodedMethodConstants.EQUALS_IGNORE_CASE.equals(name)) { + return false; + } + final PsiMethod method = expression.resolveMethod(); + return MethodUtils.isEqualsIgnoreCase(method); + } + + public static boolean isSimpleCallToMethod( + @Nonnull PsiMethodCallExpression expression, + @NonNls @Nullable String calledOnClassName, + @Nullable PsiType returnType, + @NonNls @Nullable String methodName, + @NonNls @Nullable String... parameterTypeStrings + ) { + if (parameterTypeStrings == null) { + return isCallToMethod(expression, calledOnClassName, returnType, methodName, (PsiType[]) null); + } + final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(expression.getProject()); + final PsiElementFactory factory = psiFacade.getElementFactory(); + final PsiType[] parameterTypes = PsiType.createArray(parameterTypeStrings.length); + final GlobalSearchScope scope = expression.getResolveScope(); + for (int i = 0; i < parameterTypeStrings.length; i++) { + final String parameterTypeString = parameterTypeStrings[i]; + parameterTypes[i] = factory.createTypeByFQClassName(parameterTypeString, scope); + } + return isCallToMethod(expression, calledOnClassName, returnType, methodName, parameterTypes); + } + + public static boolean isCallToStaticMethod( + @Nonnull PsiMethodCallExpression expression, + @NonNls @Nonnull String calledOnClassName, + @NonNls @Nonnull String methodName, + int parameterCount + ) { + PsiExpression[] args = expression.getArgumentList().getExpressions(); + if (!methodName.equals(getMethodName(expression)) || args.length < parameterCount) { + return false; + } + PsiMethod method = expression.resolveMethod(); + if (method == null || !method.hasModifierProperty(PsiModifier.STATIC) || method.getParameterList() + .getParametersCount() != parameterCount || !method.isVarArgs() && args.length != + parameterCount) { + return false; + } + PsiClass aClass = method.getContainingClass(); + return aClass != null && calledOnClassName.equals(aClass.getQualifiedName()); + } + + public static boolean isCallToMethod( + @Nonnull PsiMethodCallExpression expression, + @NonNls @Nullable String calledOnClassName, + @Nullable PsiType returnType, + @Nullable Pattern methodNamePattern, + @Nullable PsiType... parameterTypes + ) { + final PsiReferenceExpression methodExpression = expression.getMethodExpression(); + if (methodNamePattern != null) { + final String referenceName = methodExpression.getReferenceName(); + if (referenceName == null) { + return false; + } + final Matcher matcher = methodNamePattern.matcher(referenceName); + if (!matcher.matches()) { + return false; + } + } + final PsiMethod method = expression.resolveMethod(); + if (method == null) { + return false; + } + if (calledOnClassName != null) { + final PsiExpression qualifier = methodExpression.getQualifierExpression(); + if (qualifier != null) { + if (!TypeUtils.expressionHasTypeOrSubtype(qualifier, calledOnClassName)) { + return false; + } + return MethodUtils.methodMatches(method, null, returnType, methodNamePattern, parameterTypes); + } + } + return MethodUtils.methodMatches(method, calledOnClassName, returnType, methodNamePattern, parameterTypes); + } + + public static boolean isCallToMethod( + @Nonnull PsiMethodCallExpression expression, + @NonNls @Nullable String calledOnClassName, + @Nullable PsiType returnType, + @NonNls @Nullable String methodName, + @Nullable PsiType... parameterTypes + ) { + final PsiReferenceExpression methodExpression = expression.getMethodExpression(); + if (methodName != null) { + final String referenceName = methodExpression.getReferenceName(); + if (!methodName.equals(referenceName)) { + return false; + } + } + final PsiMethod method = expression.resolveMethod(); + if (method == null) { + return false; + } + return MethodUtils.methodMatches(method, calledOnClassName, returnType, methodName, parameterTypes); } - final String className = containingClass.getQualifiedName(); - return CommonClassNames.JAVA_LANG_STRING.equals(className) || "java.util.regex.Pattern".equals(className); - } - - public static boolean isCallDuringObjectConstruction(PsiMethodCallExpression expression) { - final PsiMember member = PsiTreeUtil.getParentOfType(expression, PsiMember.class, true, PsiClass.class, PsiLambdaExpression.class); - if (member == null) { - return false; + + public static boolean isCallToRegexMethod(PsiMethodCallExpression expression) { + final PsiReferenceExpression methodExpression = expression.getMethodExpression(); + final String name = methodExpression.getReferenceName(); + if (!regexMethodNames.contains(name)) { + return false; + } + final PsiMethod method = expression.resolveMethod(); + if (method == null) { + return false; + } + final PsiClass containingClass = method.getContainingClass(); + if (containingClass == null) { + return false; + } + final String className = containingClass.getQualifiedName(); + return CommonClassNames.JAVA_LANG_STRING.equals(className) || "java.util.regex.Pattern".equals(className); } - final PsiReferenceExpression methodExpression = expression.getMethodExpression(); - final PsiExpression qualifier = methodExpression.getQualifierExpression(); - if (qualifier != null) { - if (!(qualifier instanceof PsiThisExpression || qualifier instanceof PsiSuperExpression)) { + + public static boolean isCallDuringObjectConstruction(PsiMethodCallExpression expression) { + final PsiMember member = PsiTreeUtil.getParentOfType(expression, PsiMember.class, true, PsiClass.class, PsiLambdaExpression.class); + if (member == null) { + return false; + } + final PsiReferenceExpression methodExpression = expression.getMethodExpression(); + final PsiExpression qualifier = methodExpression.getQualifierExpression(); + if (qualifier != null) { + if (!(qualifier instanceof PsiThisExpression || qualifier instanceof PsiSuperExpression)) { + return false; + } + } + final PsiClass containingClass = member.getContainingClass(); + if (containingClass == null || containingClass.hasModifierProperty(PsiModifier.FINAL)) { + return false; + } + if (member instanceof PsiClassInitializer) { + final PsiClassInitializer classInitializer = (PsiClassInitializer) member; + if (!classInitializer.hasModifierProperty(PsiModifier.STATIC)) { + return true; + } + } + else if (member instanceof PsiMethod) { + final PsiMethod method = (PsiMethod) member; + if (method.isConstructor()) { + return true; + } + if (CloneUtils.isClone(method)) { + return true; + } + if (MethodUtils.simpleMethodMatches(method, null, "void", "readObject", "java.io.ObjectInputStream")) { + return true; + } + return MethodUtils.simpleMethodMatches(method, null, "void", "readObjectNoData"); + } + else if (member instanceof PsiField) { + final PsiField field = (PsiField) member; + if (!field.hasModifierProperty(PsiModifier.STATIC)) { + return true; + } + } return false; - } - } - final PsiClass containingClass = member.getContainingClass(); - if (containingClass == null || containingClass.hasModifierProperty(PsiModifier.FINAL)) { - return false; - } - if (member instanceof PsiClassInitializer) { - final PsiClassInitializer classInitializer = (PsiClassInitializer) member; - if (!classInitializer.hasModifierProperty(PsiModifier.STATIC)) { - return true; - } - } else if (member instanceof PsiMethod) { - final PsiMethod method = (PsiMethod) member; - if (method.isConstructor()) { - return true; - } - if (CloneUtils.isClone(method)) { - return true; - } - if (MethodUtils.simpleMethodMatches(method, null, "void", "readObject", "java.io.ObjectInputStream")) { - return true; - } - return MethodUtils.simpleMethodMatches(method, null, "void", "readObjectNoData"); - } else if (member instanceof PsiField) { - final PsiField field = (PsiField) member; - if (!field.hasModifierProperty(PsiModifier.STATIC)) { - return true; - } - } - return false; - } - - public static boolean isMethodCallOnVariable(@Nonnull PsiMethodCallExpression expression, @Nonnull PsiVariable variable, @Nonnull String methodName) { - final PsiReferenceExpression methodExpression = expression.getMethodExpression(); - @NonNls final String name = methodExpression.getReferenceName(); - if (!methodName.equals(name)) { - return false; - } - final PsiExpression qualifier = ParenthesesUtils.stripParentheses(methodExpression.getQualifierExpression()); - if (!(qualifier instanceof PsiReferenceExpression)) { - return false; - } - final PsiReferenceExpression referenceExpression = (PsiReferenceExpression) qualifier; - final PsiElement element = referenceExpression.resolve(); - return variable.equals(element); - } - - @Nullable - public static PsiMethod findMethodWithReplacedArgument(@Nonnull PsiCall call, @Nonnull PsiExpression target, @Nonnull PsiExpression replacement) { - final PsiExpressionList argumentList = call.getArgumentList(); - if (argumentList == null) { - return null; - } - final PsiExpression[] expressions = argumentList.getExpressions(); - int index = -1; - for (int i = 0; i < expressions.length; i++) { - final PsiExpression expression = expressions[i]; - if (expression == target) { - index = i; - } - } - if (index < 0) { - return null; - } - final PsiCall copy = (PsiCall) call.copy(); - final PsiExpressionList copyArgumentList = copy.getArgumentList(); - assert copyArgumentList != null; - final PsiExpression[] arguments = copyArgumentList.getExpressions(); - arguments[index].replace(replacement); - if (call instanceof PsiEnumConstant) { - final PsiClass containingClass = ((PsiEnumConstant) call).getContainingClass(); - assert containingClass != null; - final JavaPsiFacade facade = JavaPsiFacade.getInstance(call.getProject()); - final PsiClassType type = facade.getElementFactory().createType(containingClass); - final JavaResolveResult resolveResult = facade.getResolveHelper().resolveConstructor(type, copy.getArgumentList(), call); - return (PsiMethod) resolveResult.getElement(); - } - return copy.resolveMethod(); - } - - /** - * Checks if the specified expression is an argument for any method call (skipping parentheses in between). - * If the method call is found, checks if same method is called when argument is replaced with replacement. - * - * @param expression the expression to check - * @param replacement the replacement to replace expression with - * @return true, if method was found and a different method was called with replacement. false, otherwise. - */ - public static boolean isNecessaryForSurroundingMethodCall(PsiExpression expression, PsiExpression replacement) { - PsiElement parent = expression.getParent(); - while (parent instanceof PsiParenthesizedExpression) { - expression = (PsiExpression) parent; - parent = parent.getParent(); - } - if (!(parent instanceof PsiExpressionList)) { - return false; - } - final PsiElement grandParent = parent.getParent(); - if (!(grandParent instanceof PsiCall)) { - return false; - } - final PsiCall call = (PsiCall) grandParent; - return call.resolveMethod() != findMethodWithReplacedArgument(call, expression, replacement); - } - - public static boolean isSuperMethodCall(@Nonnull PsiMethodCallExpression expression, @Nonnull PsiMethod method) { - final PsiReferenceExpression methodExpression = expression.getMethodExpression(); - final PsiExpression target = ParenthesesUtils.stripParentheses(methodExpression.getQualifierExpression()); - if (!(target instanceof PsiSuperExpression)) { - return false; - } - final PsiMethod targetMethod = expression.resolveMethod(); - return targetMethod != null && MethodSignatureUtil.isSuperMethod(targetMethod, method); - } - - /** - * Returns true if given method call is a var-arg call - * - * @param call a call to test - * @return true if call is resolved to the var-arg method and var-arg form is actually used - */ - public static boolean isVarArgCall(PsiCall call) { - JavaResolveResult result = call.resolveMethodGenerics(); - PsiMethod method = tryCast(result.getElement(), PsiMethod.class); - if (method == null || !method.isVarArgs()) { - return false; - } - PsiSubstitutor substitutor = result.getSubstitutor(); - return MethodCallInstruction.isVarArgCall(method, substitutor, call.getArgumentList().getExpressions(), method.getParameterList().getParameters()); - } - - public static boolean containsSuperMethodCall(@Nonnull PsiMethod method) { - final SuperCallVisitor visitor = new SuperCallVisitor(method); - method.accept(visitor); - return visitor.isSuperCallFound(); - } - - public static boolean callWithNonConstantString(@Nonnull PsiMethodCallExpression expression, boolean considerStaticFinalConstant, String className, String... methodNames) { - final PsiReferenceExpression methodExpression = expression.getMethodExpression(); - final String methodName = methodExpression.getReferenceName(); - boolean found = false; - for (String name : methodNames) { - if (name.equals(methodName)) { - found = true; - break; - } - } - if (!found) { - return false; - } - final PsiMethod method = expression.resolveMethod(); - if (method == null) { - return false; - } - final PsiClass aClass = method.getContainingClass(); - if (aClass == null) { - return false; - } - if (!InheritanceUtil.isInheritor(aClass, className)) { - return false; - } - final PsiExpressionList argumentList = expression.getArgumentList(); - final PsiExpression argument = ParenthesesUtils.stripParentheses(ExpressionUtils.getFirstExpressionInList(argumentList)); - if (argument == null) { - return false; - } - final PsiType type = argument.getType(); - if (type == null || !type.equalsToText(CommonClassNames.JAVA_LANG_STRING)) { - return false; - } - if (considerStaticFinalConstant && argument instanceof PsiReferenceExpression) { - final PsiReferenceExpression referenceExpression = (PsiReferenceExpression) argument; - final PsiElement target = referenceExpression.resolve(); - if (target instanceof PsiField) { - final PsiField field = (PsiField) target; - if (field.hasModifierProperty(PsiModifier.STATIC) && field.hasModifierProperty(PsiModifier.FINAL)) { - return false; - } - } - } - return !PsiUtil.isConstantExpression(argument); - } - - /** - * For given method call, returns a qualifier if it's also a method call, or null otherwise - * - * @param methodCall call to check - * @return a qualifier call - */ - @Nullable - public static PsiMethodCallExpression getQualifierMethodCall(@Nonnull PsiMethodCallExpression methodCall) { - return tryCast(PsiUtil.skipParenthesizedExprDown(methodCall.getMethodExpression().getQualifierExpression()), PsiMethodCallExpression.class); - } - - - /** - * Returns a method/constructor parameter which corresponds to given argument - * - * @param argument an argument to find the corresponding parameter - * @return a parameter or null if supplied expression is not a call argument, call is not resolved or expression is a var-arg - * argument. - */ - @Nullable - public static PsiParameter getParameterForArgument(@Nonnull PsiExpression argument) { - PsiExpressionList argList = tryCast(argument.getParent(), PsiExpressionList.class); - if (argList == null) - return null; - PsiElement parent = argList.getParent(); - if (parent instanceof PsiAnonymousClass) { - parent = parent.getParent(); - } - PsiCall call = tryCast(parent, PsiCall.class); - if (call == null) - return null; - PsiExpression[] args = argList.getExpressions(); - int index = ArrayUtil.indexOf(args, argument); - if (index == -1) - return null; - PsiMethod method = call.resolveMethod(); - if (method == null) - return null; - PsiParameter[] parameters = method.getParameterList().getParameters(); - if (index >= parameters.length) - return null; - if (isVarArgCall(call) && index >= parameters.length - 1) - return null; - return parameters[index]; - } - - private static class SuperCallVisitor extends JavaRecursiveElementWalkingVisitor { - - private final PsiMethod myMethod; - private boolean mySuperCallFound; - - public SuperCallVisitor(@Nonnull PsiMethod method) { - this.myMethod = method; } - @Override - public void visitElement(@Nonnull PsiElement element) { - if (!mySuperCallFound) { - super.visitElement(element); - } + public static boolean isMethodCallOnVariable( + @Nonnull PsiMethodCallExpression expression, + @Nonnull PsiVariable variable, + @Nonnull String methodName + ) { + final PsiReferenceExpression methodExpression = expression.getMethodExpression(); + @NonNls final String name = methodExpression.getReferenceName(); + if (!methodName.equals(name)) { + return false; + } + final PsiExpression qualifier = ParenthesesUtils.stripParentheses(methodExpression.getQualifierExpression()); + if (!(qualifier instanceof PsiReferenceExpression)) { + return false; + } + final PsiReferenceExpression referenceExpression = (PsiReferenceExpression) qualifier; + final PsiElement element = referenceExpression.resolve(); + return variable.equals(element); + } + + @Nullable + public static PsiMethod findMethodWithReplacedArgument( + @Nonnull PsiCall call, + @Nonnull PsiExpression target, + @Nonnull PsiExpression replacement + ) { + final PsiExpressionList argumentList = call.getArgumentList(); + if (argumentList == null) { + return null; + } + final PsiExpression[] expressions = argumentList.getExpressions(); + int index = -1; + for (int i = 0; i < expressions.length; i++) { + final PsiExpression expression = expressions[i]; + if (expression == target) { + index = i; + } + } + if (index < 0) { + return null; + } + final PsiCall copy = (PsiCall) call.copy(); + final PsiExpressionList copyArgumentList = copy.getArgumentList(); + assert copyArgumentList != null; + final PsiExpression[] arguments = copyArgumentList.getExpressions(); + arguments[index].replace(replacement); + if (call instanceof PsiEnumConstant) { + final PsiClass containingClass = ((PsiEnumConstant) call).getContainingClass(); + assert containingClass != null; + final JavaPsiFacade facade = JavaPsiFacade.getInstance(call.getProject()); + final PsiClassType type = facade.getElementFactory().createType(containingClass); + final JavaResolveResult resolveResult = facade.getResolveHelper().resolveConstructor(type, copy.getArgumentList(), call); + return (PsiMethod) resolveResult.getElement(); + } + return copy.resolveMethod(); + } + + /** + * Checks if the specified expression is an argument for any method call (skipping parentheses in between). + * If the method call is found, checks if same method is called when argument is replaced with replacement. + * + * @param expression the expression to check + * @param replacement the replacement to replace expression with + * @return true, if method was found and a different method was called with replacement. false, otherwise. + */ + public static boolean isNecessaryForSurroundingMethodCall(PsiExpression expression, PsiExpression replacement) { + PsiElement parent = expression.getParent(); + while (parent instanceof PsiParenthesizedExpression) { + expression = (PsiExpression) parent; + parent = parent.getParent(); + } + if (!(parent instanceof PsiExpressionList)) { + return false; + } + final PsiElement grandParent = parent.getParent(); + if (!(grandParent instanceof PsiCall)) { + return false; + } + final PsiCall call = (PsiCall) grandParent; + return call.resolveMethod() != findMethodWithReplacedArgument(call, expression, replacement); } - @Override - public void visitClass(PsiClass aClass) { - // anonymous and inner classes inside methods are visited to reduce false positives - super.visitClass(aClass); + public static boolean isSuperMethodCall(@Nonnull PsiMethodCallExpression expression, @Nonnull PsiMethod method) { + final PsiReferenceExpression methodExpression = expression.getMethodExpression(); + final PsiExpression target = ParenthesesUtils.stripParentheses(methodExpression.getQualifierExpression()); + if (!(target instanceof PsiSuperExpression)) { + return false; + } + final PsiMethod targetMethod = expression.resolveMethod(); + return targetMethod != null && MethodSignatureUtil.isSuperMethod(targetMethod, method); + } + + /** + * Returns true if given method call is a var-arg call + * + * @param call a call to test + * @return true if call is resolved to the var-arg method and var-arg form is actually used + */ + public static boolean isVarArgCall(PsiCall call) { + JavaResolveResult result = call.resolveMethodGenerics(); + PsiMethod method = tryCast(result.getElement(), PsiMethod.class); + if (method == null || !method.isVarArgs()) { + return false; + } + PsiSubstitutor substitutor = result.getSubstitutor(); + return MethodCallInstruction.isVarArgCall( + method, + substitutor, + call.getArgumentList().getExpressions(), + method.getParameterList().getParameters() + ); + } + + public static boolean containsSuperMethodCall(@Nonnull PsiMethod method) { + final SuperCallVisitor visitor = new SuperCallVisitor(method); + method.accept(visitor); + return visitor.isSuperCallFound(); + } + + public static boolean callWithNonConstantString( + @Nonnull PsiMethodCallExpression expression, + boolean considerStaticFinalConstant, + String className, + String... methodNames + ) { + final PsiReferenceExpression methodExpression = expression.getMethodExpression(); + final String methodName = methodExpression.getReferenceName(); + boolean found = false; + for (String name : methodNames) { + if (name.equals(methodName)) { + found = true; + break; + } + } + if (!found) { + return false; + } + final PsiMethod method = expression.resolveMethod(); + if (method == null) { + return false; + } + final PsiClass aClass = method.getContainingClass(); + if (aClass == null) { + return false; + } + if (!InheritanceUtil.isInheritor(aClass, className)) { + return false; + } + final PsiExpressionList argumentList = expression.getArgumentList(); + final PsiExpression argument = ParenthesesUtils.stripParentheses(ExpressionUtils.getFirstExpressionInList(argumentList)); + if (argument == null) { + return false; + } + final PsiType type = argument.getType(); + if (type == null || !type.equalsToText(CommonClassNames.JAVA_LANG_STRING)) { + return false; + } + if (considerStaticFinalConstant && argument instanceof PsiReferenceExpression) { + final PsiReferenceExpression referenceExpression = (PsiReferenceExpression) argument; + final PsiElement target = referenceExpression.resolve(); + if (target instanceof PsiField) { + final PsiField field = (PsiField) target; + if (field.hasModifierProperty(PsiModifier.STATIC) && field.hasModifierProperty(PsiModifier.FINAL)) { + return false; + } + } + } + return !PsiUtil.isConstantExpression(argument); + } + + /** + * For given method call, returns a qualifier if it's also a method call, or null otherwise + * + * @param methodCall call to check + * @return a qualifier call + */ + @Nullable + public static PsiMethodCallExpression getQualifierMethodCall(@Nonnull PsiMethodCallExpression methodCall) { + return tryCast( + PsiUtil.skipParenthesizedExprDown(methodCall.getMethodExpression().getQualifierExpression()), + PsiMethodCallExpression.class + ); + } + + + /** + * Returns a method/constructor parameter which corresponds to given argument + * + * @param argument an argument to find the corresponding parameter + * @return a parameter or null if supplied expression is not a call argument, call is not resolved or expression is a var-arg + * argument. + */ + @Nullable + public static PsiParameter getParameterForArgument(@Nonnull PsiExpression argument) { + PsiExpressionList argList = tryCast(argument.getParent(), PsiExpressionList.class); + if (argList == null) { + return null; + } + PsiElement parent = argList.getParent(); + if (parent instanceof PsiAnonymousClass) { + parent = parent.getParent(); + } + PsiCall call = tryCast(parent, PsiCall.class); + if (call == null) { + return null; + } + PsiExpression[] args = argList.getExpressions(); + int index = ArrayUtil.indexOf(args, argument); + if (index == -1) { + return null; + } + PsiMethod method = call.resolveMethod(); + if (method == null) { + return null; + } + PsiParameter[] parameters = method.getParameterList().getParameters(); + if (index >= parameters.length) { + return null; + } + if (isVarArgCall(call) && index >= parameters.length - 1) { + return null; + } + return parameters[index]; } - @Override - public void visitLambdaExpression(PsiLambdaExpression expression) { - // lambda's are visited to reduce false positives - super.visitLambdaExpression(expression); - } + private static class SuperCallVisitor extends JavaRecursiveElementWalkingVisitor { + private final PsiMethod myMethod; + private boolean mySuperCallFound; - @Override - public void visitIfStatement(PsiIfStatement statement) { - final PsiExpression condition = statement.getCondition(); - final Object result = ExpressionUtils.computeConstantExpression(condition); - if (result != null && result.equals(Boolean.FALSE)) { - return; - } - super.visitIfStatement(statement); - } + public SuperCallVisitor(@Nonnull PsiMethod method) { + this.myMethod = method; + } - @Override - public void visitMethodCallExpression(@Nonnull PsiMethodCallExpression expression) { - if (mySuperCallFound) { - return; - } - super.visitMethodCallExpression(expression); - if (isSuperMethodCall(expression, myMethod)) { - mySuperCallFound = true; - } - } + @Override + public void visitElement(@Nonnull PsiElement element) { + if (!mySuperCallFound) { + super.visitElement(element); + } + } - @Override - public void visitMethodReferenceExpression(PsiMethodReferenceExpression expression) { - if (mySuperCallFound) { - return; - } - final PsiExpression qualifier = expression.getQualifierExpression(); - if (qualifier instanceof PsiSuperExpression) { - final PsiElement target = expression.resolve(); - if (target instanceof PsiMethod) { - if (MethodSignatureUtil.isSuperMethod((PsiMethod) target, myMethod)) { - mySuperCallFound = true; - return; - } - } - } - super.visitMethodReferenceExpression(expression); - } + @Override + public void visitClass(PsiClass aClass) { + // anonymous and inner classes inside methods are visited to reduce false positives + super.visitClass(aClass); + } - boolean isSuperCallFound() { - return mySuperCallFound; + @Override + public void visitLambdaExpression(PsiLambdaExpression expression) { + // lambda's are visited to reduce false positives + super.visitLambdaExpression(expression); + } + + @Override + public void visitIfStatement(PsiIfStatement statement) { + final PsiExpression condition = statement.getCondition(); + final Object result = ExpressionUtils.computeConstantExpression(condition); + if (result != null && result.equals(Boolean.FALSE)) { + return; + } + super.visitIfStatement(statement); + } + + @Override + public void visitMethodCallExpression(@Nonnull PsiMethodCallExpression expression) { + if (mySuperCallFound) { + return; + } + super.visitMethodCallExpression(expression); + if (isSuperMethodCall(expression, myMethod)) { + mySuperCallFound = true; + } + } + + @Override + public void visitMethodReferenceExpression(PsiMethodReferenceExpression expression) { + if (mySuperCallFound) { + return; + } + final PsiExpression qualifier = expression.getQualifierExpression(); + if (qualifier instanceof PsiSuperExpression) { + final PsiElement target = expression.resolve(); + if (target instanceof PsiMethod) { + if (MethodSignatureUtil.isSuperMethod((PsiMethod) target, myMethod)) { + mySuperCallFound = true; + return; + } + } + } + super.visitMethodReferenceExpression(expression); + } + + boolean isSuperCallFound() { + return mySuperCallFound; + } } - } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/jdk/AutoUnboxingInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/jdk/AutoUnboxingInspection.java index 8ba5a93759..5b3360c240 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/jdk/AutoUnboxingInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/jdk/AutoUnboxingInspection.java @@ -247,63 +247,21 @@ private static String buildNewExpressionText(PsiExpression expression, PsiPrimit return expressionText + '.' + boxMethodName + "()"; } - private static boolean isValueOfCall(PsiMethodCallExpression methodCallExpression) { - final PsiExpressionList argumentList = methodCallExpression.getArgumentList(); + private static boolean isValueOfCall(PsiMethodCallExpression callExpr) { + final PsiExpressionList argumentList = callExpr.getArgumentList(); final PsiExpression[] arguments = argumentList.getExpressions(); if (arguments.length != 1) { return false; } final PsiExpression argument = arguments[0]; final PsiType type = argument.getType(); - return (MethodCallUtils.isCallToMethod( - methodCallExpression, - CommonClassNames.JAVA_LANG_INTEGER, - null, - "valueOf", - PsiType.INT - ) && PsiType.INT.equals(type)) || - (MethodCallUtils.isCallToMethod( - methodCallExpression, - CommonClassNames.JAVA_LANG_SHORT, - null, - "valueOf", - PsiType.SHORT - ) && PsiType.SHORT.equals(type)) || - (MethodCallUtils.isCallToMethod( - methodCallExpression, - CommonClassNames.JAVA_LANG_BYTE, - null, - "valueOf", - PsiType.BYTE - ) && PsiType.BYTE.equals(type)) || - (MethodCallUtils.isCallToMethod( - methodCallExpression, - CommonClassNames.JAVA_LANG_LONG, - null, - "valueOf", - PsiType.LONG - ) && PsiType.LONG.equals(type)) || - (MethodCallUtils.isCallToMethod( - methodCallExpression, - CommonClassNames.JAVA_LANG_CHARACTER, - null, - "valueOf", - PsiType.CHAR - ) && PsiType.CHAR.equals(type)) || - (MethodCallUtils.isCallToMethod( - methodCallExpression, - CommonClassNames.JAVA_LANG_DOUBLE, - null, - "valueOf", - PsiType.DOUBLE - ) && PsiType.DOUBLE.equals(type)) || - (MethodCallUtils.isCallToMethod( - methodCallExpression, - CommonClassNames.JAVA_LANG_FLOAT, - null, - "valueOf", - PsiType.FLOAT - ) && PsiType.FLOAT.equals(type)); + return (MethodCallUtils.isCallToMethod(callExpr, CommonClassNames.JAVA_LANG_INTEGER, null, "valueOf", PsiType.INT) && PsiType.INT.equals(type)) + || (MethodCallUtils.isCallToMethod(callExpr, CommonClassNames.JAVA_LANG_SHORT, null, "valueOf", PsiType.SHORT) && PsiType.SHORT.equals(type)) + || (MethodCallUtils.isCallToMethod(callExpr, CommonClassNames.JAVA_LANG_BYTE, null, "valueOf", PsiType.BYTE) && PsiType.BYTE.equals(type)) + || (MethodCallUtils.isCallToMethod(callExpr, CommonClassNames.JAVA_LANG_LONG, null, "valueOf", PsiType.LONG) && PsiType.LONG.equals(type)) + || (MethodCallUtils.isCallToMethod(callExpr, CommonClassNames.JAVA_LANG_CHARACTER, null, "valueOf", PsiType.CHAR) && PsiType.CHAR.equals(type)) + || (MethodCallUtils.isCallToMethod(callExpr, CommonClassNames.JAVA_LANG_DOUBLE, null, "valueOf", PsiType.DOUBLE) && PsiType.DOUBLE.equals(type)) + || (MethodCallUtils.isCallToMethod(callExpr, CommonClassNames.JAVA_LANG_FLOAT, null, "valueOf", PsiType.FLOAT) && PsiType.FLOAT.equals(type)); } @NonNls