diff --git a/java-analysis-impl/src/main/java/com/intellij/java/analysis/impl/codeInspection/booleanIsAlwaysInverted/BooleanMethodIsAlwaysInvertedInspection.java b/java-analysis-impl/src/main/java/com/intellij/java/analysis/impl/codeInspection/booleanIsAlwaysInverted/BooleanMethodIsAlwaysInvertedInspection.java index ebba361f5..1d6631bdb 100644 --- a/java-analysis-impl/src/main/java/com/intellij/java/analysis/impl/codeInspection/booleanIsAlwaysInverted/BooleanMethodIsAlwaysInvertedInspection.java +++ b/java-analysis-impl/src/main/java/com/intellij/java/analysis/impl/codeInspection/booleanIsAlwaysInverted/BooleanMethodIsAlwaysInvertedInspection.java @@ -28,258 +28,206 @@ import consulo.util.dataholder.Key; import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; -import org.jetbrains.annotations.NonNls; import java.util.Collection; /** - * User: anna - * Date: 06-Jan-2006 + * @author anna + * @since 2006-01-06 */ @ExtensionImpl @IntentionMetaData(ignoreId = "java.BooleanMethodIsAlwaysInvertedInspection", fileExtensions = "java", categories = {"Java", "Boolean"}) -public class BooleanMethodIsAlwaysInvertedInspection extends GlobalJavaInspectionTool -{ - private static final Key ALWAYS_INVERTED = Key.create("ALWAYS_INVERTED_METHOD"); - - @Nonnull - @Override - public HighlightDisplayLevel getDefaultLevel() - { - return HighlightDisplayLevel.WARNING; - } - - @Override - @Nonnull - public LocalizeValue getDisplayName() - { - return InspectionLocalize.booleanMethodIsAlwaysInvertedDisplayName(); - } - - @Override - @Nonnull - public LocalizeValue getGroupDisplayName() - { - return InspectionLocalize.groupNamesDataFlowIssues(); - } - - @Override - @Nonnull - @NonNls - public String getShortName() - { - return "BooleanMethodIsAlwaysInverted"; - } - - @Override - @Nullable - public RefGraphAnnotator getAnnotator(final RefManager refManager, Object state) - { - return new BooleanInvertedAnnotator(); - } - - @Override - public CommonProblemDescriptor[] checkElement( - RefEntity refEntity, - @Nonnull AnalysisScope scope, - @Nonnull final InspectionManager manager, - @Nonnull final GlobalInspectionContext globalContext, - Object state - ) - { - if (refEntity instanceof RefMethod refMethod) - { - if (!refMethod.isReferenced() || hasNonInvertedCalls(refMethod) || !refMethod.getSuperMethods().isEmpty()) { - return null; - } - final PsiMethod psiMethod = (PsiMethod) refMethod.getElement(); - final PsiIdentifier psiIdentifier = psiMethod.getNameIdentifier(); - if (psiIdentifier != null) - { - return new ProblemDescriptor[]{ - manager.createProblemDescriptor( - psiIdentifier, - InspectionLocalize.booleanMethodIsAlwaysInvertedProblemDescriptor().get(), - new InvertMethodFix(), - ProblemHighlightType.GENERIC_ERROR_OR_WARNING, - false - ) - }; - } - } - return null; - } - - private static boolean hasNonInvertedCalls(final RefMethod refMethod) - { - final Boolean alwaysInverted = refMethod.getUserData(ALWAYS_INVERTED); - if (alwaysInverted == null || refMethod.isExternalOverride() || (refMethod.isReferenced() && !alwaysInverted)) { - return true; - } - final Collection superMethods = refMethod.getSuperMethods(); - for (RefMethod superMethod : superMethods) - { - if (hasNonInvertedCalls(superMethod)) - { - return true; - } - } - return false; - } - - @Override - protected boolean queryExternalUsagesRequests( - final RefManager manager, - final GlobalJavaInspectionContext context, - final ProblemDescriptionsProcessor descriptionsProcessor, - Object state - ) - { - manager.iterate(new RefJavaVisitor() - { - @Override - @RequiredReadAction - public void visitMethod(@Nonnull final RefMethod refMethod) - { - if (descriptionsProcessor.getDescriptions(refMethod) != null) - { //suspicious method -> need to check external usages - final GlobalJavaInspectionContext.UsagesProcessor usagesProcessor = psiReference -> { - final PsiElement psiReferenceExpression = psiReference.getElement(); - if (psiReferenceExpression instanceof PsiReferenceExpression referenceExpression && !isInvertedMethodCall(referenceExpression)) - { - descriptionsProcessor.ignoreElement(refMethod); - } - return false; - }; - traverseSuperMethods(refMethod, context, usagesProcessor); - } - } - }); - return false; - } - - private static void traverseSuperMethods( - RefMethod refMethod, - GlobalJavaInspectionContext globalContext, - GlobalJavaInspectionContext.UsagesProcessor processor - ) - { - final Collection superMethods = refMethod.getSuperMethods(); - for (RefMethod superMethod : superMethods) - { - traverseSuperMethods(superMethod, globalContext, processor); - } - globalContext.enqueueMethodUsagesProcessor(refMethod, processor); - } - - private static void checkMethodCall(RefElement refWhat, final PsiElement element) - { - if (!(refWhat instanceof RefMethod)) - { - return; - } - final RefMethod refMethod = (RefMethod) refWhat; - final PsiElement psiElement = refMethod.getElement(); - if (!(psiElement instanceof PsiMethod)) - { - return; - } - final PsiMethod psiMethod = (PsiMethod) psiElement; - if (!PsiType.BOOLEAN.equals(psiMethod.getReturnType())) - { - return; - } - element.accept(new JavaRecursiveElementVisitor() - { - @Override - public void visitMethodCallExpression(@Nonnull PsiMethodCallExpression call) - { - super.visitMethodCallExpression(call); - final PsiReferenceExpression methodExpression = call.getMethodExpression(); - if (methodExpression.isReferenceTo(psiMethod)) - { - if (isInvertedMethodCall(methodExpression)) - { - return; - } - refMethod.putUserData(ALWAYS_INVERTED, Boolean.FALSE); - } - } - }); - } - - private static boolean isInvertedMethodCall(final PsiReferenceExpression methodExpression) - { - final PsiPrefixExpression prefixExpression = PsiTreeUtil.getParentOfType(methodExpression, PsiPrefixExpression.class); - if (methodExpression.getQualifierExpression() instanceof PsiSuperExpression) - { - return true; //don't flag super calls - } - if (prefixExpression != null) - { - final IElementType tokenType = prefixExpression.getOperationTokenType(); - if (tokenType.equals(JavaTokenType.EXCL)) - { - return true; - } - } - return false; - } - - private static class BooleanInvertedAnnotator extends RefGraphAnnotator - { - @Override - public void onInitialize(RefElement refElement) - { - if (refElement instanceof RefMethod) - { - final PsiElement element = refElement.getElement(); - if (!(element instanceof PsiMethod method && PsiType.BOOLEAN.equals(method.getReturnType()))) { - return; - } - refElement.putUserData(ALWAYS_INVERTED, Boolean.TRUE); //initial mark boolean methods - } - } - - @Override - public void onMarkReferenced(RefElement refWhat, RefElement refFrom, boolean referencedFromClassInitializer) - { - checkMethodCall(refWhat, refFrom.getElement()); - } - } - - @Override - public QuickFix getQuickFix(final String hint) - { - return new InvertMethodFix(); - } - - private static class InvertMethodFix implements LocalQuickFix - { - @Override - @Nonnull - public LocalizeValue getName() - { - return LocalizeValue.localizeTODO("Invert method"); - } - - @Override - public void applyFix(@Nonnull final Project project, @Nonnull final ProblemDescriptor descriptor) - { - final PsiElement element = descriptor.getPsiElement(); - final PsiMethod psiMethod = PsiTreeUtil.getParentOfType(element, PsiMethod.class); - assert psiMethod != null; - final RefactoringActionHandler invertBooleanHandler = JavaRefactoringActionHandlerFactory.getInstance().createInvertBooleanHandler(); - final Runnable runnable = - () -> invertBooleanHandler.invoke(project, new PsiElement[]{psiMethod}, DataManager.getInstance().getDataContext()); - if (project.getApplication().isUnitTestMode()) - { - runnable.run(); - } - else - { - project.getApplication().invokeLater(runnable, project.getDisposed()); - } - } - } +public class BooleanMethodIsAlwaysInvertedInspection extends GlobalJavaInspectionTool { + private static final Key ALWAYS_INVERTED = Key.create("ALWAYS_INVERTED_METHOD"); + + @Nonnull + @Override + public HighlightDisplayLevel getDefaultLevel() { + return HighlightDisplayLevel.WARNING; + } + + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionLocalize.booleanMethodIsAlwaysInvertedDisplayName(); + } + + @Nonnull + @Override + public LocalizeValue getGroupDisplayName() { + return InspectionLocalize.groupNamesDataFlowIssues(); + } + + @Nonnull + @Override + public String getShortName() { + return "BooleanMethodIsAlwaysInverted"; + } + + @Nullable + @Override + public RefGraphAnnotator getAnnotator(@Nonnull RefManager refManager, @Nonnull Object state) { + return new BooleanInvertedAnnotator(); + } + + @Override + @RequiredReadAction + public CommonProblemDescriptor[] checkElement( + @Nonnull RefEntity refEntity, + @Nonnull AnalysisScope scope, + @Nonnull InspectionManager manager, + @Nonnull GlobalInspectionContext globalContext, + @Nonnull Object state + ) { + if (refEntity instanceof RefMethod refMethod) { + if (!refMethod.isReferenced() || hasNonInvertedCalls(refMethod) || !refMethod.getSuperMethods().isEmpty()) { + return null; + } + PsiMethod psiMethod = (PsiMethod) refMethod.getElement(); + PsiIdentifier psiIdentifier = psiMethod.getNameIdentifier(); + if (psiIdentifier != null) { + return new ProblemDescriptor[]{ + manager.newProblemDescriptor(InspectionLocalize.booleanMethodIsAlwaysInvertedProblemDescriptor()) + .range(psiIdentifier) + .withFix(new InvertMethodFix()) + .create() + }; + } + } + return null; + } + + private static boolean hasNonInvertedCalls(RefMethod refMethod) { + Boolean alwaysInverted = refMethod.getUserData(ALWAYS_INVERTED); + if (alwaysInverted == null || refMethod.isExternalOverride() || (refMethod.isReferenced() && !alwaysInverted)) { + return true; + } + Collection superMethods = refMethod.getSuperMethods(); + for (RefMethod superMethod : superMethods) { + if (hasNonInvertedCalls(superMethod)) { + return true; + } + } + return false; + } + + @Override + protected boolean queryExternalUsagesRequests( + RefManager manager, + final GlobalJavaInspectionContext context, + final ProblemDescriptionsProcessor descriptionsProcessor, + Object state + ) { + manager.iterate(new RefJavaVisitor() { + @Override + @RequiredReadAction + public void visitMethod(@Nonnull RefMethod refMethod) { + if (descriptionsProcessor.getDescriptions(refMethod) != null) { //suspicious method -> need to check external usages + GlobalJavaInspectionContext.UsagesProcessor usagesProcessor = psiReference -> { + PsiElement psiReferenceExpression = psiReference.getElement(); + if (psiReferenceExpression instanceof PsiReferenceExpression referenceExpression + && !isInvertedMethodCall(referenceExpression)) { + descriptionsProcessor.ignoreElement(refMethod); + } + return false; + }; + traverseSuperMethods(refMethod, context, usagesProcessor); + } + } + }); + return false; + } + + private static void traverseSuperMethods( + RefMethod refMethod, + GlobalJavaInspectionContext globalContext, + GlobalJavaInspectionContext.UsagesProcessor processor + ) { + Collection superMethods = refMethod.getSuperMethods(); + for (RefMethod superMethod : superMethods) { + traverseSuperMethods(superMethod, globalContext, processor); + } + globalContext.enqueueMethodUsagesProcessor(refMethod, processor); + } + + private static void checkMethodCall(RefElement refWhat, PsiElement element) { + if (refWhat instanceof RefMethod refMethod + && refMethod.getElement() instanceof PsiMethod method + && PsiType.BOOLEAN.equals(method.getReturnType())) { + element.accept(new JavaRecursiveElementVisitor() { + @Override + @RequiredReadAction + public void visitMethodCallExpression(@Nonnull PsiMethodCallExpression call) { + super.visitMethodCallExpression(call); + PsiReferenceExpression methodExpression = call.getMethodExpression(); + if (methodExpression.isReferenceTo(method)) { + if (isInvertedMethodCall(methodExpression)) { + return; + } + refMethod.putUserData(ALWAYS_INVERTED, Boolean.FALSE); + } + } + }); + } + } + + private static boolean isInvertedMethodCall(PsiReferenceExpression methodExpression) { + PsiPrefixExpression prefixExpression = PsiTreeUtil.getParentOfType(methodExpression, PsiPrefixExpression.class); + if (methodExpression.getQualifierExpression() instanceof PsiSuperExpression) { + return true; //don't flag super calls + } + if (prefixExpression != null) { + IElementType tokenType = prefixExpression.getOperationTokenType(); + if (tokenType.equals(JavaTokenType.EXCL)) { + return true; + } + } + return false; + } + + private static class BooleanInvertedAnnotator extends RefGraphAnnotator { + @Override + public void onInitialize(RefElement refElement) { + if (refElement instanceof RefMethod refMethod + && refMethod.getElement() instanceof PsiMethod method + && PsiType.BOOLEAN.equals(method.getReturnType())) { + refElement.putUserData(ALWAYS_INVERTED, Boolean.TRUE); //initial mark boolean methods + } + } + + @Override + public void onMarkReferenced(RefElement refWhat, RefElement refFrom, boolean referencedFromClassInitializer) { + checkMethodCall(refWhat, refFrom.getElement()); + } + } + + @Override + public QuickFix getQuickFix(String hint) { + return new InvertMethodFix(); + } + + private static class InvertMethodFix implements LocalQuickFix { + @Override + @Nonnull + public LocalizeValue getName() { + return LocalizeValue.localizeTODO("Invert method"); + } + + @Override + @RequiredReadAction + public void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor descriptor) { + PsiElement element = descriptor.getPsiElement(); + PsiMethod psiMethod = PsiTreeUtil.getParentOfType(element, PsiMethod.class); + assert psiMethod != null; + RefactoringActionHandler invertBooleanHandler = JavaRefactoringActionHandlerFactory.getInstance().createInvertBooleanHandler(); + Runnable runnable = + () -> invertBooleanHandler.invoke(project, new PsiElement[]{psiMethod}, DataManager.getInstance().getDataContext()); + if (project.getApplication().isUnitTestMode()) { + runnable.run(); + } + else { + project.getApplication().invokeLater(runnable, project.getDisposed()); + } + } + } } diff --git a/java-analysis-impl/src/main/java/com/intellij/java/analysis/impl/codeInspection/localCanBeFinal/LocalCanBeFinal.java b/java-analysis-impl/src/main/java/com/intellij/java/analysis/impl/codeInspection/localCanBeFinal/LocalCanBeFinal.java index d1fc5a325..5c6abbce0 100644 --- a/java-analysis-impl/src/main/java/com/intellij/java/analysis/impl/codeInspection/localCanBeFinal/LocalCanBeFinal.java +++ b/java-analysis-impl/src/main/java/com/intellij/java/analysis/impl/codeInspection/localCanBeFinal/LocalCanBeFinal.java @@ -25,7 +25,6 @@ import consulo.language.editor.FileModificationService; import consulo.language.editor.inspection.LocalQuickFix; import consulo.language.editor.inspection.ProblemDescriptor; -import consulo.language.editor.inspection.ProblemHighlightType; import consulo.language.editor.inspection.localize.InspectionLocalize; import consulo.language.editor.inspection.scheme.InspectionManager; import consulo.language.editor.rawHighlight.HighlightDisplayLevel; @@ -37,7 +36,6 @@ import consulo.project.Project; import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; -import org.jetbrains.annotations.NonNls; import javax.swing.*; import java.awt.*; @@ -51,308 +49,332 @@ */ @ExtensionImpl public class LocalCanBeFinal extends BaseJavaBatchLocalInspectionTool { - private static final Logger LOG = Logger.getInstance(LocalCanBeFinal.class); - - public boolean REPORT_VARIABLES = true; - public boolean REPORT_PARAMETERS = true; - - private final LocalQuickFix myQuickFix; - @NonNls - public static final String SHORT_NAME = "LocalCanBeFinal"; - - public LocalCanBeFinal() { - myQuickFix = new AcceptSuggested(); - } - - @Nonnull - @Override - public HighlightDisplayLevel getDefaultLevel() { - return HighlightDisplayLevel.WARNING; - } - - @Override - public ProblemDescriptor[] checkMethod(@Nonnull PsiMethod method, @Nonnull InspectionManager manager, boolean isOnTheFly, Object state) { - List list = checkCodeBlock(method.getBody(), manager, isOnTheFly); - return list == null ? null : list.toArray(new ProblemDescriptor[list.size()]); - } - - @Override - public ProblemDescriptor[] checkClass(@Nonnull PsiClass aClass, @Nonnull InspectionManager manager, boolean isOnTheFly, Object state) { - List allProblems = null; - final PsiClassInitializer[] initializers = aClass.getInitializers(); - for (PsiClassInitializer initializer : initializers) { - final List problems = checkCodeBlock(initializer.getBody(), manager, isOnTheFly); - if (problems != null) { - if (allProblems == null) { - allProblems = new ArrayList<>(1); - } - allProblems.addAll(problems); - } - } - return allProblems == null ? null : allProblems.toArray(new ProblemDescriptor[allProblems.size()]); - } - - @Nullable - private List checkCodeBlock(final PsiCodeBlock body, InspectionManager manager, boolean onTheFly) { - if (body == null) return null; - final ControlFlow flow; - try { - ControlFlowPolicy policy = new ControlFlowPolicy() { - @Override - @RequiredReadAction - public PsiVariable getUsedVariable(PsiReferenceExpression refExpr) { - if (refExpr.isQualified()) return null; + private static final Logger LOG = Logger.getInstance(LocalCanBeFinal.class); - PsiElement refElement = refExpr.resolve(); - if (refElement instanceof PsiLocalVariable || refElement instanceof PsiParameter) { - if (!isVariableDeclaredInMethod((PsiVariable) refElement)) return null; - return (PsiVariable) refElement; - } + public boolean REPORT_VARIABLES = true; + public boolean REPORT_PARAMETERS = true; - return null; - } + private final LocalQuickFix myQuickFix; + public static final String SHORT_NAME = "LocalCanBeFinal"; - @Override - public boolean isParameterAccepted(PsiParameter psiParameter) { - return isVariableDeclaredInMethod(psiParameter); - } + public LocalCanBeFinal() { + myQuickFix = new AcceptSuggested(); + } - @Override - public boolean isLocalVariableAccepted(PsiLocalVariable psiVariable) { - return isVariableDeclaredInMethod(psiVariable); - } + @Nonnull + @Override + public HighlightDisplayLevel getDefaultLevel() { + return HighlightDisplayLevel.WARNING; + } + + @Override + @RequiredReadAction + public ProblemDescriptor[] checkMethod( + @Nonnull PsiMethod method, + @Nonnull InspectionManager manager, + boolean isOnTheFly, + Object state + ) { + List list = checkCodeBlock(method.getBody(), manager, isOnTheFly); + return list == null ? null : list.toArray(new ProblemDescriptor[list.size()]); + } - private boolean isVariableDeclaredInMethod(PsiVariable psiVariable) { - return PsiTreeUtil.getParentOfType(psiVariable, PsiClass.class) == PsiTreeUtil.getParentOfType(body, PsiClass.class); + @Override + @RequiredReadAction + public ProblemDescriptor[] checkClass(@Nonnull PsiClass aClass, @Nonnull InspectionManager manager, boolean isOnTheFly, Object state) { + List allProblems = null; + PsiClassInitializer[] initializers = aClass.getInitializers(); + for (PsiClassInitializer initializer : initializers) { + List problems = checkCodeBlock(initializer.getBody(), manager, isOnTheFly); + if (problems != null) { + if (allProblems == null) { + allProblems = new ArrayList<>(1); + } + allProblems.addAll(problems); + } } - }; - flow = ControlFlowFactory.getInstance(body.getProject()).getControlFlow(body, policy, false); - } catch (AnalysisCanceledException e) { - return null; + return allProblems == null ? null : allProblems.toArray(new ProblemDescriptor[allProblems.size()]); } - int start = flow.getStartOffset(body); - int end = flow.getEndOffset(body); - - final List writtenVariables = - new ArrayList<>(ControlFlowUtil.getWrittenVariables(flow, start, end, false)); - - final HashSet ssaVarsSet = new HashSet<>(); - body.accept(new JavaRecursiveElementWalkingVisitor() { - @Override - @RequiredReadAction - public void visitCodeBlock(@Nonnull PsiCodeBlock block) { - super.visitCodeBlock(block); - PsiElement anchor = block; - if (block.getParent() instanceof PsiSwitchStatement) { - anchor = block.getParent(); + @Nullable + @RequiredReadAction + private List checkCodeBlock(final PsiCodeBlock body, InspectionManager manager, boolean onTheFly) { + if (body == null) { + return null; } - int from = flow.getStartOffset(anchor); - int end = flow.getEndOffset(anchor); - List ssa = ControlFlowUtil.getSSAVariables(flow, from, end, true); - HashSet declared = getDeclaredVariables(block); - for (PsiVariable psiVariable : ssa) { - if (declared.contains(psiVariable)) { - ssaVarsSet.add(psiVariable); - } + final ControlFlow flow; + try { + ControlFlowPolicy policy = new ControlFlowPolicy() { + @Override + @RequiredReadAction + public PsiVariable getUsedVariable(PsiReferenceExpression refExpr) { + if (refExpr.isQualified()) { + return null; + } + + PsiElement refElement = refExpr.resolve(); + if (refElement instanceof PsiLocalVariable || refElement instanceof PsiParameter) { + if (!isVariableDeclaredInMethod((PsiVariable) refElement)) { + return null; + } + return (PsiVariable) refElement; + } + + return null; + } + + @Override + public boolean isParameterAccepted(PsiParameter psiParameter) { + return isVariableDeclaredInMethod(psiParameter); + } + + @Override + public boolean isLocalVariableAccepted(PsiLocalVariable psiVariable) { + return isVariableDeclaredInMethod(psiVariable); + } + + private boolean isVariableDeclaredInMethod(PsiVariable psiVariable) { + return PsiTreeUtil.getParentOfType(psiVariable, PsiClass.class) == PsiTreeUtil.getParentOfType(body, PsiClass.class); + } + }; + flow = ControlFlowFactory.getInstance(body.getProject()).getControlFlow(body, policy, false); } - } - - @Override - public void visitForeachStatement(@Nonnull PsiForeachStatement statement) { - super.visitForeachStatement(statement); - final PsiParameter param = statement.getIterationParameter(); - final PsiStatement body = statement.getBody(); - if (body == null) return; - int from = flow.getStartOffset(body); - int end = flow.getEndOffset(body); - if (!ControlFlowUtil.getWrittenVariables(flow, from, end, false).contains(param)) { - writtenVariables.remove(param); - ssaVarsSet.add(param); + catch (AnalysisCanceledException e) { + return null; } - } - - @RequiredReadAction - private HashSet getDeclaredVariables(PsiCodeBlock block) { - final HashSet result = new HashSet<>(); - PsiElement[] children = block.getChildren(); - for (PsiElement child : children) { - child.accept(new JavaElementVisitor() { + + int start = flow.getStartOffset(body); + int end = flow.getEndOffset(body); + + final List writtenVariables = + new ArrayList<>(ControlFlowUtil.getWrittenVariables(flow, start, end, false)); + + final HashSet ssaVarsSet = new HashSet<>(); + body.accept(new JavaRecursiveElementWalkingVisitor() { @Override - public void visitReferenceExpression(@Nonnull PsiReferenceExpression expression) { - visitReferenceElement(expression); + @RequiredReadAction + public void visitCodeBlock(@Nonnull PsiCodeBlock block) { + super.visitCodeBlock(block); + PsiElement anchor = block; + if (block.getParent() instanceof PsiSwitchStatement) { + anchor = block.getParent(); + } + int from = flow.getStartOffset(anchor); + int end = flow.getEndOffset(anchor); + List ssa = ControlFlowUtil.getSSAVariables(flow, from, end, true); + HashSet declared = getDeclaredVariables(block); + for (PsiVariable psiVariable : ssa) { + if (declared.contains(psiVariable)) { + ssaVarsSet.add(psiVariable); + } + } } @Override - public void visitDeclarationStatement(@Nonnull PsiDeclarationStatement statement) { - PsiElement[] declaredElements = statement.getDeclaredElements(); - for (PsiElement declaredElement : declaredElements) { - if (declaredElement instanceof PsiVariable) result.add(declaredElement); - } + public void visitForeachStatement(@Nonnull PsiForeachStatement statement) { + super.visitForeachStatement(statement); + PsiParameter param = statement.getIterationParameter(); + PsiStatement body = statement.getBody(); + if (body == null) { + return; + } + int from = flow.getStartOffset(body); + int end = flow.getEndOffset(body); + if (!ControlFlowUtil.getWrittenVariables(flow, from, end, false).contains(param)) { + writtenVariables.remove(param); + ssaVarsSet.add(param); + } } - }); - } - - return result; - } - @Override - public void visitReferenceExpression(PsiReferenceExpression expression) { - } - }); + @RequiredReadAction + private HashSet getDeclaredVariables(PsiCodeBlock block) { + final HashSet result = new HashSet<>(); + PsiElement[] children = block.getChildren(); + for (PsiElement child : children) { + child.accept(new JavaElementVisitor() { + @Override + public void visitReferenceExpression(@Nonnull PsiReferenceExpression expression) { + visitReferenceElement(expression); + } + + @Override + public void visitDeclarationStatement(@Nonnull PsiDeclarationStatement statement) { + PsiElement[] declaredElements = statement.getDeclaredElements(); + for (PsiElement declaredElement : declaredElements) { + if (declaredElement instanceof PsiVariable) { + result.add(declaredElement); + } + } + } + }); + } + + return result; + } - ArrayList result = new ArrayList<>(ssaVarsSet); + @Override + public void visitReferenceExpression(PsiReferenceExpression expression) { + } + }); - if (body.getParent() instanceof PsiMethod) { - PsiMethod method = (PsiMethod) body.getParent(); - PsiParameter[] parameters = method.getParameterList().getParameters(); - for (PsiParameter parameter : parameters) { - if (!result.contains(parameter)) result.add(parameter); - } - } + List result = new ArrayList<>(ssaVarsSet); - PsiVariable[] psiVariables = result.toArray(new PsiVariable[result.size()]); - for (PsiVariable psiVariable : psiVariables) { - if (!isReportParameters() && psiVariable instanceof PsiParameter - || !isReportVariables() && psiVariable instanceof PsiLocalVariable - || psiVariable.hasModifierProperty(PsiModifier.FINAL)) { - result.remove(psiVariable); - } - - if (psiVariable instanceof PsiLocalVariable) { - PsiDeclarationStatement decl = (PsiDeclarationStatement) psiVariable.getParent(); - if (decl != null && decl.getParent() instanceof PsiForStatement) { - result.remove(psiVariable); + if (body.getParent() instanceof PsiMethod method) { + for (PsiParameter parameter : method.getParameterList().getParameters()) { + if (!result.contains(parameter)) { + result.add(parameter); + } + } } - } - } - for (PsiVariable writtenVariable : writtenVariables) { - if (writtenVariable instanceof PsiParameter) { - result.remove(writtenVariable); - } - } + PsiVariable[] psiVariables = result.toArray(new PsiVariable[result.size()]); + for (PsiVariable psiVariable : psiVariables) { + if (!isReportParameters() && psiVariable instanceof PsiParameter + || !isReportVariables() && psiVariable instanceof PsiLocalVariable + || psiVariable.hasModifierProperty(PsiModifier.FINAL)) { + result.remove(psiVariable); + } - if (result.isEmpty()) return null; - for (Iterator iterator = result.iterator(); iterator.hasNext(); ) { - final PsiVariable variable = iterator.next(); - if (!variable.isPhysical()) { - iterator.remove(); - } - } - List problems = new ArrayList<>(result.size()); - for (PsiVariable variable : result) { - final PsiIdentifier nameIdenitier = variable.getNameIdentifier(); - PsiElement problemElement = nameIdenitier != null ? nameIdenitier : variable; - if (variable instanceof PsiParameter && !(((PsiParameter) variable).getDeclarationScope() instanceof PsiForeachStatement)) { - problems.add(manager.createProblemDescriptor( - problemElement, - InspectionLocalize.inspectionCanBeLocalParameterProblemDescriptor().get(), - myQuickFix, - ProblemHighlightType.GENERIC_ERROR_OR_WARNING, - onTheFly - )); - } else { - problems.add(manager.createProblemDescriptor( - problemElement, - InspectionLocalize.inspectionCanBeLocalVariableProblemDescriptor().get(), - myQuickFix, - ProblemHighlightType.GENERIC_ERROR_OR_WARNING, - onTheFly - )); - } - } + if (psiVariable instanceof PsiLocalVariable) { + PsiDeclarationStatement decl = (PsiDeclarationStatement) psiVariable.getParent(); + if (decl != null && decl.getParent() instanceof PsiForStatement) { + result.remove(psiVariable); + } + } + } - return problems; - } + for (PsiVariable writtenVariable : writtenVariables) { + if (writtenVariable instanceof PsiParameter) { + result.remove(writtenVariable); + } + } - @Override - @Nonnull - public LocalizeValue getDisplayName() { - return InspectionLocalize.inspectionLocalCanBeFinalDisplayName(); - } + if (result.isEmpty()) { + return null; + } + for (Iterator iterator = result.iterator(); iterator.hasNext(); ) { + PsiVariable variable = iterator.next(); + if (!variable.isPhysical()) { + iterator.remove(); + } + } + List problems = new ArrayList<>(result.size()); + for (PsiVariable variable : result) { + PsiIdentifier nameIdentifier = variable.getNameIdentifier(); + PsiElement problemElement = nameIdentifier != null ? nameIdentifier : variable; + if (variable instanceof PsiParameter param && !(param.getDeclarationScope() instanceof PsiForeachStatement)) { + problems.add(manager.newProblemDescriptor(InspectionLocalize.inspectionCanBeLocalParameterProblemDescriptor()) + .range(problemElement) + .onTheFly(onTheFly) + .withOptionalFix(myQuickFix) + .create()); + } + else { + problems.add(manager.newProblemDescriptor(InspectionLocalize.inspectionCanBeLocalVariableProblemDescriptor()) + .range(problemElement) + .onTheFly(onTheFly) + .withOptionalFix(myQuickFix) + .create()); + } + } - @Override - @Nonnull - public LocalizeValue getGroupDisplayName() { - return InspectionLocalize.groupNamesCodeStyleIssues(); - } + return problems; + } - @Override - @Nonnull - public String getShortName() { - return SHORT_NAME; - } + @Override + @Nonnull + public LocalizeValue getDisplayName() { + return InspectionLocalize.inspectionLocalCanBeFinalDisplayName(); + } - private static class AcceptSuggested implements LocalQuickFix { @Override @Nonnull - public LocalizeValue getName() { - return InspectionLocalize.inspectionCanBeFinalAcceptQuickfix(); + public LocalizeValue getGroupDisplayName() { + return InspectionLocalize.groupNamesCodeStyleIssues(); } @Override - @RequiredWriteAction - public void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor problem) { - if (!FileModificationService.getInstance().preparePsiElementForWrite(problem.getPsiElement())) return; - PsiElement nameIdentifier = problem.getPsiElement(); - if (nameIdentifier == null) return; - PsiVariable psiVariable = PsiTreeUtil.getParentOfType(nameIdentifier, PsiVariable.class, false); - if (psiVariable == null) return; - try { - psiVariable.normalizeDeclaration(); - PsiUtil.setModifierProperty(psiVariable, PsiModifier.FINAL, true); - } catch (IncorrectOperationException e) { - LOG.error(e); - } + @Nonnull + public String getShortName() { + return SHORT_NAME; + } + + private static class AcceptSuggested implements LocalQuickFix { + @Override + @Nonnull + public LocalizeValue getName() { + return InspectionLocalize.inspectionCanBeFinalAcceptQuickfix(); + } + + @Override + @RequiredWriteAction + public void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor problem) { + if (!FileModificationService.getInstance().preparePsiElementForWrite(problem.getPsiElement())) { + return; + } + PsiElement nameIdentifier = problem.getPsiElement(); + if (nameIdentifier == null) { + return; + } + PsiVariable psiVariable = PsiTreeUtil.getParentOfType(nameIdentifier, PsiVariable.class, false); + if (psiVariable == null) { + return; + } + try { + psiVariable.normalizeDeclaration(); + PsiUtil.setModifierProperty(psiVariable, PsiModifier.FINAL, true); + } + catch (IncorrectOperationException e) { + LOG.error(e); + } + } } - } - @Override - public JComponent createOptionsPanel() { - return new OptionsPanel(); - } + @Override + public JComponent createOptionsPanel() { + return new OptionsPanel(); + } - private boolean isReportVariables() { - return REPORT_VARIABLES; - } + private boolean isReportVariables() { + return REPORT_VARIABLES; + } - private boolean isReportParameters() { - return REPORT_PARAMETERS; - } + private boolean isReportParameters() { + return REPORT_PARAMETERS; + } - private class OptionsPanel extends JPanel { - private final JCheckBox myReportVariablesCheckbox; - private final JCheckBox myReportParametersCheckbox; + private class OptionsPanel extends JPanel { + private final JCheckBox myReportVariablesCheckbox; + private final JCheckBox myReportParametersCheckbox; - private OptionsPanel() { - super(new GridBagLayout()); + private OptionsPanel() { + super(new GridBagLayout()); - GridBagConstraints gc = new GridBagConstraints(); - gc.weighty = 0; - gc.weightx = 1; - gc.fill = GridBagConstraints.HORIZONTAL; - gc.anchor = GridBagConstraints.NORTHWEST; + GridBagConstraints gc = new GridBagConstraints(); + gc.weighty = 0; + gc.weightx = 1; + gc.fill = GridBagConstraints.HORIZONTAL; + gc.anchor = GridBagConstraints.NORTHWEST; - myReportVariablesCheckbox = new JCheckBox(InspectionLocalize.inspectionLocalCanBeFinalOption().get()); - myReportVariablesCheckbox.setSelected(REPORT_VARIABLES); - myReportVariablesCheckbox.getModel().addChangeListener(e -> REPORT_VARIABLES = myReportVariablesCheckbox.isSelected()); - gc.gridy = 0; - add(myReportVariablesCheckbox, gc); + myReportVariablesCheckbox = new JCheckBox(InspectionLocalize.inspectionLocalCanBeFinalOption().get()); + myReportVariablesCheckbox.setSelected(REPORT_VARIABLES); + myReportVariablesCheckbox.getModel().addChangeListener(e -> REPORT_VARIABLES = myReportVariablesCheckbox.isSelected()); + gc.gridy = 0; + add(myReportVariablesCheckbox, gc); - myReportParametersCheckbox = new JCheckBox(InspectionLocalize.inspectionLocalCanBeFinalOption1().get()); - myReportParametersCheckbox.setSelected(REPORT_PARAMETERS); - myReportParametersCheckbox.getModel().addChangeListener(e -> REPORT_PARAMETERS = myReportParametersCheckbox.isSelected()); + myReportParametersCheckbox = new JCheckBox(InspectionLocalize.inspectionLocalCanBeFinalOption1().get()); + myReportParametersCheckbox.setSelected(REPORT_PARAMETERS); + myReportParametersCheckbox.getModel().addChangeListener(e -> REPORT_PARAMETERS = myReportParametersCheckbox.isSelected()); - gc.weighty = 1; - gc.gridy++; - add(myReportParametersCheckbox, gc); + gc.weighty = 1; + gc.gridy++; + add(myReportParametersCheckbox, gc); + } } - } - @Override - public boolean isEnabledByDefault() { - return false; - } + @Override + public boolean isEnabledByDefault() { + return false; + } } diff --git a/java-analysis-impl/src/main/java/com/intellij/java/analysis/impl/codeInspection/miscGenerics/RedundantTypeArgsInspection.java b/java-analysis-impl/src/main/java/com/intellij/java/analysis/impl/codeInspection/miscGenerics/RedundantTypeArgsInspection.java index 30d02cc5e..f665a54a2 100644 --- a/java-analysis-impl/src/main/java/com/intellij/java/analysis/impl/codeInspection/miscGenerics/RedundantTypeArgsInspection.java +++ b/java-analysis-impl/src/main/java/com/intellij/java/analysis/impl/codeInspection/miscGenerics/RedundantTypeArgsInspection.java @@ -18,6 +18,7 @@ import com.intellij.java.language.psi.*; import com.intellij.java.language.psi.impl.source.resolve.DefaultParameterTypeInferencePolicy; import com.intellij.java.language.psi.util.PsiUtil; +import consulo.annotation.access.RequiredReadAction; import consulo.annotation.access.RequiredWriteAction; import consulo.annotation.component.ExtensionImpl; import consulo.language.editor.inspection.LocalQuickFix; @@ -40,149 +41,170 @@ */ @ExtensionImpl public class RedundantTypeArgsInspection extends GenericsInspectionToolBase { - private static final Logger LOG = Logger.getInstance(RedundantTypeArgsInspection.class); - - public RedundantTypeArgsInspection() { - myQuickFixAction = new MyQuickFixAction(); - } - - private final LocalQuickFix myQuickFixAction; - - @Override - public boolean isEnabledByDefault() { - return true; - } - - @Override - @Nonnull - public LocalizeValue getGroupDisplayName() { - return InspectionLocalize.groupNamesVerboseOrRedundantCodeConstructs(); - } - - @Override - @Nonnull - public LocalizeValue getDisplayName() { - return InspectionLocalize.inspectionRedundantTypeDisplayName(); - } - - @Override - @Nonnull - public String getShortName() { - return "RedundantTypeArguments"; - } - - @Override - public ProblemDescriptor[] checkMethod(@Nonnull PsiMethod psiMethod, @Nonnull InspectionManager manager, boolean isOnTheFly, Object state) { - final PsiCodeBlock body = psiMethod.getBody(); - if (body != null) { - return getDescriptions(body, manager, isOnTheFly, state); - } - return null; - } - - @Override - public ProblemDescriptor[] getDescriptions(PsiElement place, final InspectionManager inspectionManager, boolean isOnTheFly, Object state) { - final List problems = new ArrayList<>(); - place.accept(new JavaRecursiveElementWalkingVisitor() { - @Override - public void visitMethodCallExpression(@Nonnull PsiMethodCallExpression expression) { - final PsiType[] typeArguments = expression.getTypeArguments(); - if (typeArguments.length > 0) { - checkCallExpression(expression.getMethodExpression(), typeArguments, expression, inspectionManager, problems); - } - } - - @Override - public void visitNewExpression(@Nonnull PsiNewExpression expression) { - final PsiType[] typeArguments = expression.getTypeArguments(); - if (typeArguments.length > 0) { - final PsiJavaCodeReferenceElement classReference = expression.getClassReference(); - if (classReference != null) { - checkCallExpression(classReference, typeArguments, expression, inspectionManager, problems); - } - } - } + private static final Logger LOG = Logger.getInstance(RedundantTypeArgsInspection.class); - private void checkCallExpression( - final PsiJavaCodeReferenceElement reference, - final PsiType[] typeArguments, - PsiCallExpression expression, - final InspectionManager inspectionManager, - final List problems - ) { - PsiExpressionList argumentList = expression.getArgumentList(); - if (argumentList == null) return; - final JavaResolveResult resolveResult = reference.advancedResolve(false); - - final PsiElement element = resolveResult.getElement(); - if (element instanceof PsiMethod method && resolveResult.isValidResult()) { - final PsiTypeParameter[] typeParameters = method.getTypeParameters(); - if (typeParameters.length == typeArguments.length) { - final PsiParameter[] parameters = method.getParameterList().getParameters(); - PsiResolveHelper resolveHelper = JavaPsiFacade.getInstance(expression.getProject()).getResolveHelper(); - final PsiSubstitutor psiSubstitutor = resolveHelper.inferTypeArguments( - typeParameters, - parameters, - argumentList.getExpressions(), - PsiSubstitutor.EMPTY, - expression, - DefaultParameterTypeInferencePolicy.INSTANCE - ); - for (int i = 0, length = typeParameters.length; i < length; i++) { - PsiTypeParameter typeParameter = typeParameters[i]; - final PsiType inferredType = psiSubstitutor.getSubstitutionMap().get(typeParameter); - if (!typeArguments[i].equals(inferredType)) return; - if (PsiUtil.resolveClassInType(method.getReturnType()) == typeParameter - && PsiPrimitiveType.getUnboxedType(inferredType) != null) { - return; - } - } + public RedundantTypeArgsInspection() { + myQuickFixAction = new MyQuickFixAction(); + } - final PsiCallExpression copy = (PsiCallExpression) expression.copy(); //see IDEADEV-8174 - try { - copy.getTypeArgumentList().delete(); - if (copy.resolveMethod() != element) return; - } catch (IncorrectOperationException e) { - LOG.error(e); - return; - } + private final LocalQuickFix myQuickFixAction; - final ProblemDescriptor descriptor = inspectionManager.createProblemDescriptor( - expression.getTypeArgumentList(), - InspectionLocalize.inspectionRedundantTypeProblemDescriptor().get(), - myQuickFixAction, - ProblemHighlightType.LIKE_UNUSED_SYMBOL, - false - ); - problems.add(descriptor); - } - } - } + @Override + public boolean isEnabledByDefault() { + return true; + } - }); + @Override + @Nonnull + public LocalizeValue getGroupDisplayName() { + return InspectionLocalize.groupNamesVerboseOrRedundantCodeConstructs(); + } - if (problems.isEmpty()) return null; - return problems.toArray(new ProblemDescriptor[problems.size()]); - } + @Override + @Nonnull + public LocalizeValue getDisplayName() { + return InspectionLocalize.inspectionRedundantTypeDisplayName(); + } - private static class MyQuickFixAction implements LocalQuickFix { @Override @Nonnull - public LocalizeValue getName() { - return InspectionLocalize.inspectionRedundantTypeRemoveQuickfix(); + public String getShortName() { + return "RedundantTypeArguments"; } @Override - @RequiredWriteAction - public void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor descriptor) { - final PsiReferenceParameterList typeArgumentList = (PsiReferenceParameterList) descriptor.getPsiElement(); - try { - final PsiMethodCallExpression expr = (PsiMethodCallExpression) JavaPsiFacade.getInstance(project).getElementFactory() - .createExpressionFromText("foo()", null); - typeArgumentList.replace(expr.getTypeArgumentList()); - } catch (IncorrectOperationException e) { - LOG.error(e); - } + public ProblemDescriptor[] checkMethod( + @Nonnull PsiMethod psiMethod, + @Nonnull InspectionManager manager, + boolean isOnTheFly, + Object state + ) { + PsiCodeBlock body = psiMethod.getBody(); + if (body != null) { + return getDescriptions(body, manager, isOnTheFly, state); + } + return null; + } + + @Override + public ProblemDescriptor[] getDescriptions( + PsiElement place, + final InspectionManager inspectionManager, + boolean isOnTheFly, + Object state + ) { + final List problems = new ArrayList<>(); + place.accept(new JavaRecursiveElementWalkingVisitor() { + @Override + @RequiredReadAction + public void visitMethodCallExpression(@Nonnull PsiMethodCallExpression expression) { + PsiType[] typeArguments = expression.getTypeArguments(); + if (typeArguments.length > 0) { + checkCallExpression(expression.getMethodExpression(), typeArguments, expression, inspectionManager, problems); + } + } + + @Override + @RequiredReadAction + public void visitNewExpression(@Nonnull PsiNewExpression expression) { + PsiType[] typeArguments = expression.getTypeArguments(); + if (typeArguments.length > 0) { + PsiJavaCodeReferenceElement classReference = expression.getClassReference(); + if (classReference != null) { + checkCallExpression(classReference, typeArguments, expression, inspectionManager, problems); + } + } + } + + @RequiredReadAction + private void checkCallExpression( + PsiJavaCodeReferenceElement reference, + PsiType[] typeArguments, + PsiCallExpression expression, + InspectionManager inspectionManager, + List problems + ) { + PsiExpressionList argumentList = expression.getArgumentList(); + if (argumentList == null) { + return; + } + JavaResolveResult resolveResult = reference.advancedResolve(false); + + if (resolveResult.getElement() instanceof PsiMethod method && resolveResult.isValidResult()) { + PsiTypeParameter[] typeParameters = method.getTypeParameters(); + if (typeParameters.length == typeArguments.length) { + PsiParameter[] parameters = method.getParameterList().getParameters(); + PsiResolveHelper resolveHelper = JavaPsiFacade.getInstance(expression.getProject()).getResolveHelper(); + PsiSubstitutor psiSubstitutor = resolveHelper.inferTypeArguments( + typeParameters, + parameters, + argumentList.getExpressions(), + PsiSubstitutor.EMPTY, + expression, + DefaultParameterTypeInferencePolicy.INSTANCE + ); + for (int i = 0, length = typeParameters.length; i < length; i++) { + PsiTypeParameter typeParameter = typeParameters[i]; + PsiType inferredType = psiSubstitutor.getSubstitutionMap().get(typeParameter); + if (!typeArguments[i].equals(inferredType)) { + return; + } + if (PsiUtil.resolveClassInType(method.getReturnType()) == typeParameter + && PsiPrimitiveType.getUnboxedType(inferredType) != null) { + return; + } + } + + PsiCallExpression copy = (PsiCallExpression) expression.copy(); //see IDEADEV-8174 + try { + copy.getTypeArgumentList().delete(); + if (copy.resolveMethod() != method) { + return; + } + } + catch (IncorrectOperationException e) { + LOG.error(e); + return; + } + + ProblemDescriptor descriptor = inspectionManager.newProblemDescriptor( + InspectionLocalize.inspectionRedundantTypeProblemDescriptor() + ) + .range(expression.getTypeArgumentList()) + .highlightType(ProblemHighlightType.LIKE_UNUSED_SYMBOL) + .withOptionalFix(myQuickFixAction) + .create(); + problems.add(descriptor); + } + } + } + }); + + if (problems.isEmpty()) { + return null; + } + return problems.toArray(new ProblemDescriptor[problems.size()]); + } + + private static class MyQuickFixAction implements LocalQuickFix { + @Override + @Nonnull + public LocalizeValue getName() { + return InspectionLocalize.inspectionRedundantTypeRemoveQuickfix(); + } + + @Override + @RequiredWriteAction + public void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor descriptor) { + PsiReferenceParameterList typeArgumentList = (PsiReferenceParameterList) descriptor.getPsiElement(); + try { + PsiMethodCallExpression expr = (PsiMethodCallExpression) JavaPsiFacade.getInstance(project).getElementFactory() + .createExpressionFromText("foo()", null); + typeArgumentList.replace(expr.getTypeArgumentList()); + } + catch (IncorrectOperationException e) { + LOG.error(e); + } + } } - } } diff --git a/java-analysis-impl/src/main/java/com/intellij/java/analysis/impl/codeInspection/redundantCast/RedundantCastInspection.java b/java-analysis-impl/src/main/java/com/intellij/java/analysis/impl/codeInspection/redundantCast/RedundantCastInspection.java index 8044a1ec9..2ca180734 100644 --- a/java-analysis-impl/src/main/java/com/intellij/java/analysis/impl/codeInspection/redundantCast/RedundantCastInspection.java +++ b/java-analysis-impl/src/main/java/com/intellij/java/analysis/impl/codeInspection/redundantCast/RedundantCastInspection.java @@ -21,6 +21,7 @@ import com.intellij.java.language.psi.util.PsiExpressionTrimRenderer; import com.intellij.java.language.psi.util.PsiUtil; import com.intellij.java.language.psi.util.RedundantCastUtil; +import consulo.annotation.access.RequiredReadAction; import consulo.annotation.access.RequiredWriteAction; import consulo.annotation.component.ExtensionImpl; import consulo.language.editor.inspection.InspectionToolState; @@ -44,130 +45,131 @@ */ @ExtensionImpl public class RedundantCastInspection extends GenericsInspectionToolBase { - private static final String SHORT_NAME = "RedundantCast"; - - private final LocalQuickFix myQuickFixAction; - - public RedundantCastInspection() { - myQuickFixAction = new AcceptSuggested(); - } - - @Nonnull - @Override - public InspectionToolState createStateProvider() { - return new RedundantCastInspectionState(); - } - - @Override - public boolean isEnabledByDefault() { - return true; - } - - @Nonnull - @Override - public HighlightDisplayLevel getDefaultLevel() { - return HighlightDisplayLevel.WARNING; - } - - @Override - @Nullable - public ProblemDescriptor[] getDescriptions( - @Nonnull PsiElement where, - @Nonnull InspectionManager manager, - boolean isOnTheFly, - RedundantCastInspectionState state - ) { - List redundantCasts = RedundantCastUtil.getRedundantCastsInside(where); - if (redundantCasts.isEmpty()) { - return null; + private static final String SHORT_NAME = "RedundantCast"; + + private final LocalQuickFix myQuickFixAction = new AcceptSuggested(); + + @Nonnull + @Override + public InspectionToolState createStateProvider() { + return new RedundantCastInspectionState(); } - List descriptions = new ArrayList<>(redundantCasts.size()); - for (PsiTypeCastExpression redundantCast : redundantCasts) { - ProblemDescriptor descriptor = createDescription(redundantCast, manager, isOnTheFly, state); - if (descriptor != null) { - descriptions.add(descriptor); - } + + @Override + public boolean isEnabledByDefault() { + return true; } - if (descriptions.isEmpty()) { - return null; + + @Nonnull + @Override + public HighlightDisplayLevel getDefaultLevel() { + return HighlightDisplayLevel.WARNING; } - return descriptions.toArray(ProblemDescriptor.EMPTY_ARRAY); - } - - @Override - public ProblemDescriptor[] checkField( - @Nonnull PsiField field, - @Nonnull InspectionManager manager, - boolean isOnTheFly, - RedundantCastInspectionState state - ) { - return getDescriptions(field, manager, isOnTheFly, state); - } - - @Nullable - private ProblemDescriptor createDescription( - @Nonnull PsiTypeCastExpression cast, - @Nonnull InspectionManager manager, - boolean onTheFly, - RedundantCastInspectionState state - ) { - PsiExpression operand = cast.getOperand(); - PsiTypeElement castType = cast.getCastType(); - if (operand == null || castType == null) { - return null; + + @Nullable + @Override + @RequiredReadAction + public ProblemDescriptor[] getDescriptions( + @Nonnull PsiElement where, + @Nonnull InspectionManager manager, + boolean isOnTheFly, + RedundantCastInspectionState state + ) { + List redundantCasts = RedundantCastUtil.getRedundantCastsInside(where); + if (redundantCasts.isEmpty()) { + return null; + } + List descriptions = new ArrayList<>(redundantCasts.size()); + for (PsiTypeCastExpression redundantCast : redundantCasts) { + ProblemDescriptor descriptor = createDescription(redundantCast, manager, isOnTheFly, state); + if (descriptor != null) { + descriptions.add(descriptor); + } + } + if (descriptions.isEmpty()) { + return null; + } + return descriptions.toArray(ProblemDescriptor.EMPTY_ARRAY); } - PsiElement parent = PsiUtil.skipParenthesizedExprUp(cast.getParent()); - if (parent instanceof PsiExpressionList) { - final PsiElement gParent = parent.getParent(); - if (gParent instanceof PsiMethodCallExpression methodCall && state.IGNORE_SUSPICIOUS_METHOD_CALLS) { - final String message = SuspiciousMethodCallUtil - .getSuspiciousMethodCallMessage(methodCall, operand, operand.getType(), true, new ArrayList<>(), 0); - if (message != null) { - return null; + + @Override + @RequiredReadAction + public ProblemDescriptor[] checkField( + @Nonnull PsiField field, + @Nonnull InspectionManager manager, + boolean isOnTheFly, + RedundantCastInspectionState state + ) { + return getDescriptions(field, manager, isOnTheFly, state); + } + + @Nullable + @RequiredReadAction + private ProblemDescriptor createDescription( + @Nonnull PsiTypeCastExpression cast, + @Nonnull InspectionManager manager, + boolean onTheFly, + RedundantCastInspectionState state + ) { + PsiExpression operand = cast.getOperand(); + PsiTypeElement castType = cast.getCastType(); + if (operand == null || castType == null) { + return null; + } + if (PsiUtil.skipParenthesizedExprUp(cast.getParent()) instanceof PsiExpressionList exprList + && exprList.getParent() instanceof PsiMethodCallExpression methodCall + && state.IGNORE_SUSPICIOUS_METHOD_CALLS) { + String message = SuspiciousMethodCallUtil + .getSuspiciousMethodCallMessage(methodCall, operand, operand.getType(), true, new ArrayList<>(), 0); + if (message != null) { + return null; + } + } + + return manager.newProblemDescriptor(InspectionLocalize.inspectionRedundantCastProblemDescriptor( + "" + PsiExpressionTrimRenderer.render(operand) + "", + "#ref #loc" + )) + .range(castType) + .highlightType(ProblemHighlightType.LIKE_UNUSED_SYMBOL) + .onTheFly(onTheFly) + .withFix(myQuickFixAction) + .create(); + } + + private static class AcceptSuggested implements LocalQuickFix { + @Override + @Nonnull + public LocalizeValue getName() { + return InspectionLocalize.inspectionRedundantCastRemoveQuickfix(); + } + + @Override + @RequiredWriteAction + public void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor descriptor) { + PsiElement castTypeElement = descriptor.getPsiElement(); + PsiTypeCastExpression cast = castTypeElement == null ? null : (PsiTypeCastExpression) castTypeElement.getParent(); + if (cast != null) { + RemoveRedundantCastUtil.removeCast(cast); + } } - } } - String message = InspectionLocalize.inspectionRedundantCastProblemDescriptor( - "" + PsiExpressionTrimRenderer.render(operand) + "", - "#ref #loc" - ).get(); - return manager.createProblemDescriptor(castType, message, myQuickFixAction, ProblemHighlightType.LIKE_UNUSED_SYMBOL, onTheFly); - } + @Override + @Nonnull + public LocalizeValue getDisplayName() { + return InspectionLocalize.inspectionRedundantCastDisplayName(); + } - private static class AcceptSuggested implements LocalQuickFix { @Override @Nonnull - public LocalizeValue getName() { - return InspectionLocalize.inspectionRedundantCastRemoveQuickfix(); + public LocalizeValue getGroupDisplayName() { + return InspectionLocalize.groupNamesVerboseOrRedundantCodeConstructs(); } @Override - @RequiredWriteAction - public void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor descriptor) { - PsiElement castTypeElement = descriptor.getPsiElement(); - PsiTypeCastExpression cast = castTypeElement == null ? null : (PsiTypeCastExpression)castTypeElement.getParent(); - if (cast != null) { - RemoveRedundantCastUtil.removeCast(cast); - } + @Nonnull + public String getShortName() { + return SHORT_NAME; } - } - - @Override - @Nonnull - public LocalizeValue getDisplayName() { - return InspectionLocalize.inspectionRedundantCastDisplayName(); - } - - @Override - @Nonnull - public LocalizeValue getGroupDisplayName() { - return InspectionLocalize.groupNamesVerboseOrRedundantCodeConstructs(); - } - - @Override - @Nonnull - public String getShortName() { - return SHORT_NAME; - } } diff --git a/java-language-impl/src/main/resources/LOCALIZE-LIB/en_US/consulo.java.language.impl.JavaErrorLocalize.yaml b/java-language-impl/src/main/resources/LOCALIZE-LIB/en_US/consulo.java.language.impl.JavaErrorLocalize.yaml index 1b7f5413e..0e30390e5 100644 --- a/java-language-impl/src/main/resources/LOCALIZE-LIB/en_US/consulo.java.language.impl.JavaErrorLocalize.yaml +++ b/java-language-impl/src/main/resources/LOCALIZE-LIB/en_US/consulo.java.language.impl.JavaErrorLocalize.yaml @@ -30,6 +30,8 @@ direct.abstract.method.access: text: Abstract method ''{0}'' cannot be accessed directly exception.already.caught.warn: text: 'Unreachable section: {1, choice, 0#exception|2#exceptions} ''''{0}'''' {1, choice, 0#has|2#have} already been caught' +exception.is.never.thrown: + text: Exception ''{0}'' is never thrown in the method expression.expected: text: Expression expected extends.after.enum: @@ -104,6 +106,8 @@ method.is.not.used: text: Method ''{0}'' is never used missing.method.body: text: Missing method body, or declare abstract +missing.package.statement: + text: 'Missing package statement: ''''{0}''''' missing.return.type: text: Invalid method declaration; return type required modifiers.for.enum.constants: diff --git a/java-manifest/src/main/java/org/osmorc/manifest/codeInspection/MissingFinalNewlineInspection.java b/java-manifest/src/main/java/org/osmorc/manifest/codeInspection/MissingFinalNewlineInspection.java index b9c24a042..6831108c4 100644 --- a/java-manifest/src/main/java/org/osmorc/manifest/codeInspection/MissingFinalNewlineInspection.java +++ b/java-manifest/src/main/java/org/osmorc/manifest/codeInspection/MissingFinalNewlineInspection.java @@ -22,23 +22,22 @@ * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - package org.osmorc.manifest.codeInspection; +import consulo.annotation.access.RequiredReadAction; import consulo.annotation.component.ExtensionImpl; import consulo.language.Language; import consulo.language.editor.inspection.LocalInspectionTool; import consulo.language.editor.inspection.LocalQuickFix; import consulo.language.editor.inspection.ProblemDescriptor; -import consulo.language.editor.inspection.ProblemHighlightType; import consulo.language.editor.inspection.localize.InspectionLocalize; import consulo.language.editor.inspection.scheme.InspectionManager; import consulo.language.editor.rawHighlight.HighlightDisplayLevel; -import consulo.language.psi.PsiElement; import consulo.language.psi.PsiFile; import consulo.language.psi.util.PsiTreeUtil; import consulo.localize.LocalizeValue; import consulo.project.Project; +import consulo.ui.annotation.RequiredUIAccess; import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; import org.osmorc.manifest.lang.ManifestLanguage; @@ -52,80 +51,88 @@ */ @ExtensionImpl public class MissingFinalNewlineInspection extends LocalInspectionTool { - @Override - @Nonnull - public LocalizeValue getGroupDisplayName() { - return InspectionLocalize.inspectionGeneralToolsGroupName(); - } + @Nonnull + @Override + public LocalizeValue getGroupDisplayName() { + return InspectionLocalize.inspectionGeneralToolsGroupName(); + } - @Nullable - @Override - public Language getLanguage() { - return ManifestLanguage.INSTANCE; - } + @Nullable + @Override + public Language getLanguage() { + return ManifestLanguage.INSTANCE; + } - @Nonnull - public LocalizeValue getDisplayName() { - return LocalizeValue.localizeTODO("Missing Final New Line"); - } + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return LocalizeValue.localizeTODO("Missing Final New Line"); + } - @Nonnull - public String getShortName() { - return getClass().getSimpleName(); - } + @Nonnull + @Override + public String getShortName() { + return getClass().getSimpleName(); + } - public boolean isEnabledByDefault() { - return true; - } + @Override + public boolean isEnabledByDefault() { + return true; + } - @Nonnull - public HighlightDisplayLevel getDefaultLevel() { - return HighlightDisplayLevel.ERROR; - } + @Nonnull + @Override + public HighlightDisplayLevel getDefaultLevel() { + return HighlightDisplayLevel.ERROR; + } - @Override - public ProblemDescriptor[] checkFile(@Nonnull PsiFile file, @Nonnull InspectionManager manager, boolean isOnTheFly) { - if (file instanceof ManifestFile) { - String text = file.getText(); - // http://ea.jetbrains.com/browser/ea_problems/22570 - if (text != null && text.length() > 0) { - if (text.charAt(text.length() - 1) != '\n') { - Section section = PsiTreeUtil.findElementOfClassAtOffset(file, text.length() - 1, - Section.class, false); - if (section != null) { - return new ProblemDescriptor[]{manager.createProblemDescriptor(section.getLastChild(), - "Manifest file doesn't end with a final newline", - new AddNewlineQuickFix(section), - ProblemHighlightType.GENERIC_ERROR_OR_WARNING, isOnTheFly)}; - } + @Override + @RequiredReadAction + public ProblemDescriptor[] checkFile(@Nonnull PsiFile file, @Nonnull InspectionManager manager, boolean isOnTheFly) { + if (file instanceof ManifestFile) { + String text = file.getText(); + // http://ea.jetbrains.com/browser/ea_problems/22570 + if (text != null && text.length() > 0) { + if (text.charAt(text.length() - 1) != '\n') { + Section section = PsiTreeUtil.findElementOfClassAtOffset(file, text.length() - 1, Section.class, false); + if (section != null) { + return new ProblemDescriptor[]{ + manager.newProblemDescriptor( + LocalizeValue.localizeTODO("Manifest file doesn't end with a final newline") + ) + .range(section.getLastChild()) + .onTheFly(isOnTheFly) + .withFix(new AddNewlineQuickFix(section)) + .create()}; + } + } + } } - } + return ProblemDescriptor.EMPTY_ARRAY; } - return ProblemDescriptor.EMPTY_ARRAY; - } - private static class AddNewlineQuickFix implements LocalQuickFix { - private final Section section; + private static class AddNewlineQuickFix implements LocalQuickFix { + private final Section section; - private AddNewlineQuickFix(Section section) { - this.section = section; - } + private AddNewlineQuickFix(Section section) { + this.section = section; + } - @Override - @Nonnull - public LocalizeValue getName() { - return LocalizeValue.localizeTODO("Add newline"); - } + @Override + @Nonnull + public LocalizeValue getName() { + return LocalizeValue.localizeTODO("Add newline"); + } - public void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor descriptor) { - PsiElement lastChild = section.getLastChild(); - if (lastChild instanceof Header) { - Header header = (Header)lastChild; - header.getNode().addLeaf(ManifestTokenType.NEWLINE, "\n", null); - } - else { - throw new RuntimeException("No header found to add a newline to"); - } + @Override + @RequiredUIAccess + public void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor descriptor) { + if (section.getLastChild() instanceof Header header) { + header.getNode().addLeaf(ManifestTokenType.NEWLINE, "\n", null); + } + else { + throw new RuntimeException("No header found to add a newline to"); + } + } } - } } diff --git a/java-properties-impl/src/main/java/consulo/java/properties/impl/i18n/InconsistentResourceBundleInspection.java b/java-properties-impl/src/main/java/consulo/java/properties/impl/i18n/InconsistentResourceBundleInspection.java index 7cb9a702f..c120c143d 100644 --- a/java-properties-impl/src/main/java/consulo/java/properties/impl/i18n/InconsistentResourceBundleInspection.java +++ b/java-properties-impl/src/main/java/consulo/java/properties/impl/i18n/InconsistentResourceBundleInspection.java @@ -18,6 +18,7 @@ import com.intellij.lang.properties.ResourceBundle; import com.intellij.lang.properties.*; import com.intellij.lang.properties.psi.PropertiesFile; +import consulo.annotation.access.RequiredReadAction; import consulo.annotation.component.ExtensionImpl; import consulo.language.Language; import consulo.language.editor.inspection.*; @@ -44,6 +45,7 @@ public class InconsistentResourceBundleInspection extends GlobalSimpleInspection private static final Key> VISITED_BUNDLES_KEY = Key.create("VISITED_BUNDLES_KEY"); @Nonnull + @Override public LocalizeValue getGroupDisplayName() { return PropertiesLocalize.propertiesFilesInspectionGroupDisplayName(); } @@ -79,14 +81,17 @@ public InspectionToolState createStateProvider() { } @Override - public void inspectionStarted(@Nonnull InspectionManager manager, - @Nonnull GlobalInspectionContext globalContext, - @Nonnull ProblemDescriptionsProcessor problemDescriptionsProcessor, - @Nonnull Object state) { + public void inspectionStarted( + @Nonnull InspectionManager manager, + @Nonnull GlobalInspectionContext globalContext, + @Nonnull ProblemDescriptionsProcessor problemDescriptionsProcessor, + @Nonnull Object state + ) { globalContext.putUserData(VISITED_BUNDLES_KEY, new HashSet<>()); } @Override + @RequiredReadAction public void checkFile( @Nonnull PsiFile file, @Nonnull InspectionManager manager, @@ -100,18 +105,18 @@ public void checkFile( checkFile(file, manager, visitedBundles, globalContext.getRefManager(), problemDescriptionsProcessor, inspectionState); } + @RequiredReadAction private void checkFile( - @Nonnull final PsiFile file, - @Nonnull final InspectionManager manager, + @Nonnull PsiFile file, + @Nonnull InspectionManager manager, @Nonnull Set visitedBundles, RefManager refManager, ProblemDescriptionsProcessor processor, InconsistentResourceBundleInspectionState state ) { - if (!(file instanceof PropertiesFile)) { + if (!(file instanceof PropertiesFile propertiesFile)) { return; } - final PropertiesFile propertiesFile = (PropertiesFile) file; ResourceBundle resourceBundle = propertiesFile.getResourceBundle(); if (!visitedBundles.add(resourceBundle)) { return; @@ -148,11 +153,12 @@ private void checkFile( } } + @RequiredReadAction private static void checkDuplicatedProperties( - final BidirectionalMap parents, - final List files, - final Map> keysUpToParent, - final InspectionManager manager, + BidirectionalMap parents, + List files, + Map> keysUpToParent, + InspectionManager manager, RefManager refManager, ProblemDescriptionsProcessor processor ) { @@ -171,13 +177,10 @@ private static void checkDuplicatedProperties( IProperty parentProperty = parent.findPropertyByKey(overriddenKey); if (parentProperty != null && Comparing.strEqual(property.getValue(), parentProperty.getValue())) { LocalizeValue message = InspectionLocalize.inconsistentBundlePropertyInheritedWithTheSameValue(parent.getName()); - ProblemDescriptor descriptor = manager.createProblemDescriptor( - property.getPsiElement(), - message.get(), - RemovePropertyLocalFix.INSTANCE, - ProblemHighlightType.GENERIC_ERROR_OR_WARNING, - false - ); + ProblemDescriptor descriptor = manager.newProblemDescriptor(message) + .range(property.getPsiElement()) + .withFix(RemovePropertyLocalFix.INSTANCE) + .create(); processor.addProblemElement(refManager.getReference(file.getContainingFile()), descriptor); } parent = parents.get(parent); @@ -186,11 +189,12 @@ private static void checkDuplicatedProperties( } } + @RequiredReadAction private static void checkConsistency( - final BidirectionalMap parents, - final List files, - final Map> keysUpToParent, - final InspectionManager manager, + BidirectionalMap parents, + List files, + Map> keysUpToParent, + InspectionManager manager, RefManager refManager, ProblemDescriptionsProcessor processor ) { @@ -215,24 +219,23 @@ private static void checkConsistency( IProperty property = file.findPropertyByKey(inconsistentKey); assert property != null; LocalizeValue message = InspectionLocalize.inconsistentBundlePropertyError(inconsistentKey, parent.getName()); - ProblemDescriptor descriptor = manager.createProblemDescriptor( - property.getPsiElement(), - message.get(), - false, - LocalQuickFix.EMPTY_ARRAY, - ProblemHighlightType.GENERIC_ERROR_OR_WARNING - ); + ProblemDescriptor descriptor = manager.newProblemDescriptor(message) + .range(property.getPsiElement()) + .create(); processor.addProblemElement(refManager.getReference(file.getContainingFile()), descriptor); } } } - private static void checkMissingTranslations(final BidirectionalMap parents, - final List files, - final Map> keysUpToParent, - final InspectionManager manager, - RefManager refManager, - ProblemDescriptionsProcessor processor) { + @RequiredReadAction + private static void checkMissingTranslations( + BidirectionalMap parents, + List files, + Map> keysUpToParent, + InspectionManager manager, + RefManager refManager, + ProblemDescriptionsProcessor processor + ) { for (PropertiesFile file : files) { PropertiesFile parent = parents.get(file); if (parent == null) { @@ -268,13 +271,9 @@ private static void checkMissingTranslations(final BidirectionalMap result = new ArrayList<>(); - for (PsiClassInitializer initializer : initializers) { - final ProblemDescriptor[] descriptors = checkElement(initializer, manager, isOnTheFly); - if (descriptors != null) { - ContainerUtil.addAll(result, descriptors); - } + @Override + @Nonnull + public LocalizeValue getGroupDisplayName() { + return InspectionLocalize.groupNamesPropertiesFiles(); } - return result.isEmpty() ? null : result.toArray(new ProblemDescriptor[result.size()]); - } + @Override + @Nonnull + public LocalizeValue getDisplayName() { + return CodeInsightLocalize.inspectionUnresolvedPropertyKeyReferenceName(); + } - @Override - @Nullable - public ProblemDescriptor[] checkField(@Nonnull PsiField field, @Nonnull InspectionManager manager, boolean isOnTheFly, Object state) { - List result = new ArrayList<>(); - appendProblems(manager, isOnTheFly, result, field.getInitializer()); - appendProblems(manager, isOnTheFly, result, field.getModifierList()); - if (field instanceof PsiEnumConstant enumConstant) { - appendProblems(manager, isOnTheFly, result, enumConstant.getArgumentList()); + @Override + @Nonnull + public String getShortName() { + return "UnresolvedPropertyKey"; } - return result.isEmpty() ? null : result.toArray(new ProblemDescriptor[result.size()]); - } - private static void appendProblems(InspectionManager manager, boolean isOnTheFly, List result, PsiElement element) { - if (element != null) { - final ProblemDescriptor[] descriptors = checkElement(element, manager, isOnTheFly); - if (descriptors != null) { - Collections.addAll(result, descriptors); - } + @Override + @Nonnull + public HighlightDisplayLevel getDefaultLevel() { + return HighlightDisplayLevel.ERROR; } - } - @Nullable - private static ProblemDescriptor[] checkElement(PsiElement element, final InspectionManager manager, boolean onTheFly) { - UnresolvedPropertyVisitor visitor = new UnresolvedPropertyVisitor(manager, onTheFly); - element.accept(visitor); - List problems = visitor.getProblems(); - return problems.isEmpty() ? null : problems.toArray(new ProblemDescriptor[problems.size()]); - } + @Override + public boolean isEnabledByDefault() { + return true; + } - private static class UnresolvedPropertyVisitor extends JavaRecursiveElementWalkingVisitor { - private final InspectionManager myManager; - private final List myProblems = new ArrayList<>(); - private final boolean onTheFly; + @Override + @Nullable + public ProblemDescriptor[] checkMethod( + @Nonnull PsiMethod method, + @Nonnull InspectionManager manager, + boolean isOnTheFly, + Object state + ) { + return checkElement(method, manager, isOnTheFly); + } + @Override + @Nullable + public ProblemDescriptor[] checkClass(@Nonnull PsiClass aClass, @Nonnull InspectionManager manager, boolean isOnTheFly, Object state) { + PsiClassInitializer[] initializers = aClass.getInitializers(); + List result = new ArrayList<>(); + for (PsiClassInitializer initializer : initializers) { + ProblemDescriptor[] descriptors = checkElement(initializer, manager, isOnTheFly); + if (descriptors != null) { + ContainerUtil.addAll(result, descriptors); + } + } - public UnresolvedPropertyVisitor(final InspectionManager manager, boolean onTheFly) { - myManager = manager; - this.onTheFly = onTheFly; + return result.isEmpty() ? null : result.toArray(new ProblemDescriptor[result.size()]); } @Override - public void visitAnonymousClass(PsiAnonymousClass aClass) { - final PsiExpressionList argList = aClass.getArgumentList(); - if (argList != null) { - argList.accept(this); - } + @Nullable + public ProblemDescriptor[] checkField(@Nonnull PsiField field, @Nonnull InspectionManager manager, boolean isOnTheFly, Object state) { + List result = new ArrayList<>(); + appendProblems(manager, isOnTheFly, result, field.getInitializer()); + appendProblems(manager, isOnTheFly, result, field.getModifierList()); + if (field instanceof PsiEnumConstant enumConstant) { + appendProblems(manager, isOnTheFly, result, enumConstant.getArgumentList()); + } + return result.isEmpty() ? null : result.toArray(new ProblemDescriptor[result.size()]); } - @Override - public void visitClass(@Nonnull PsiClass aClass) { + private static void appendProblems(InspectionManager manager, boolean isOnTheFly, List result, PsiElement element) { + if (element != null) { + ProblemDescriptor[] descriptors = checkElement(element, manager, isOnTheFly); + if (descriptors != null) { + Collections.addAll(result, descriptors); + } + } } - @Override - public void visitField(@Nonnull PsiField field) { + @Nullable + private static ProblemDescriptor[] checkElement(PsiElement element, InspectionManager manager, boolean onTheFly) { + UnresolvedPropertyVisitor visitor = new UnresolvedPropertyVisitor(manager, onTheFly); + element.accept(visitor); + List problems = visitor.getProblems(); + return problems.isEmpty() ? null : problems.toArray(new ProblemDescriptor[problems.size()]); } - @Override - @RequiredReadAction - public void visitLiteralExpression(PsiLiteralExpression expression) { - Object value = expression.getValue(); - if (!(value instanceof String)) return; - String key = (String)value; - if (isComputablePropertyExpression(expression)) return; - Ref resourceBundleName = new Ref<>(); - if (!JavaPropertiesUtil.isValidPropertyReference(myManager.getProject(), expression, key, resourceBundleName)) { - String bundleName = resourceBundleName.get(); - if (bundleName != null) { // can be null if we were unable to resolve literal expression, e.g. when JDK was not set - appendPropertyKeyNotFoundProblem(bundleName, key, expression, myManager, myProblems, onTheFly); + private static class UnresolvedPropertyVisitor extends JavaRecursiveElementWalkingVisitor { + private final InspectionManager myManager; + private final List myProblems = new ArrayList<>(); + private final boolean onTheFly; + + public UnresolvedPropertyVisitor(InspectionManager manager, boolean onTheFly) { + myManager = manager; + this.onTheFly = onTheFly; } - } - else if (expression.getParent() instanceof PsiNameValuePair nvp) { - if (Comparing.equal(nvp.getName(), AnnotationUtil.PROPERTY_KEY_RESOURCE_BUNDLE_PARAMETER)) { - PropertiesReferenceManager manager = PropertiesReferenceManager.getInstance(expression.getProject()); - Module module = ModuleUtilCore.findModuleForPsiElement(expression); - if (module != null) { - List propFiles = manager.findPropertiesFiles(module, key); - if (propFiles.isEmpty()) { - final LocalizeValue description = CodeInsightLocalize.inspectionInvalidResourceBundleReference(key); - final ProblemDescriptor problem = myManager.createProblemDescriptor( - expression, - description.get(), - (LocalQuickFix)null, - ProblemHighlightType.LIKE_UNKNOWN_SYMBOL, - onTheFly - ); - myProblems.add(problem); + + @Override + public void visitAnonymousClass(PsiAnonymousClass aClass) { + PsiExpressionList argList = aClass.getArgumentList(); + if (argList != null) { + argList.accept(this); } - } } - } - else if (expression.getParent() instanceof PsiExpressionList expressions - && expression.getParent().getParent() instanceof PsiMethodCallExpression methodCall) { - final Map annotationParams = new HashMap<>(); - annotationParams.put(AnnotationUtil.PROPERTY_KEY_RESOURCE_BUNDLE_PARAMETER, null); - if (!JavaI18nUtil.mustBePropertyKey(myManager.getProject(), expression, annotationParams)) return; - final int paramsCount = JavaPropertiesUtil.getPropertyValueParamsMaxCount(expression); - if (paramsCount == -1) return; + @Override + public void visitClass(@Nonnull PsiClass aClass) { + } + + @Override + public void visitField(@Nonnull PsiField field) { + } + + @Override + @RequiredReadAction + public void visitLiteralExpression(PsiLiteralExpression expression) { + Object value = expression.getValue(); + if (!(value instanceof String key)) { + return; + } + if (isComputablePropertyExpression(expression)) { + return; + } + SimpleReference resourceBundleName = new SimpleReference<>(); + if (!JavaPropertiesUtil.isValidPropertyReference(myManager.getProject(), expression, key, resourceBundleName)) { + String bundleName = resourceBundleName.get(); + if (bundleName != null) { // can be null if we were unable to resolve literal expression, e.g. when JDK was not set + appendPropertyKeyNotFoundProblem(bundleName, key, expression, myManager, myProblems, onTheFly); + } + } + else if (expression.getParent() instanceof PsiNameValuePair nvp) { + if (Comparing.equal(nvp.getName(), AnnotationUtil.PROPERTY_KEY_RESOURCE_BUNDLE_PARAMETER)) { + PropertiesReferenceManager manager = PropertiesReferenceManager.getInstance(expression.getProject()); + Module module = expression.getModule(); + if (module != null) { + List propFiles = manager.findPropertiesFiles(module, key); + if (propFiles.isEmpty()) { + LocalizeValue description = CodeInsightLocalize.inspectionInvalidResourceBundleReference(key); + ProblemDescriptor problem = myManager.newProblemDescriptor(description) + .range(expression) + .highlightType(ProblemHighlightType.LIKE_UNKNOWN_SYMBOL) + .onTheFly(onTheFly) + .create(); + myProblems.add(problem); + } + } + } + } + else if (expression.getParent() instanceof PsiExpressionList expressions + && expression.getParent().getParent() instanceof PsiMethodCallExpression methodCall) { + Map annotationParams = new HashMap<>(); + annotationParams.put(AnnotationUtil.PROPERTY_KEY_RESOURCE_BUNDLE_PARAMETER, null); + if (!JavaI18nUtil.mustBePropertyKey(myManager.getProject(), expression, annotationParams)) { + return; + } + + int paramsCount = JavaPropertiesUtil.getPropertyValueParamsMaxCount(expression); + if (paramsCount == -1) { + return; + } - final PsiMethod method = methodCall.resolveMethod(); - final PsiExpression[] args = expressions.getExpressions(); - for (int i = 0; i < args.length; i++) { - if (args[i] == expression) { - if (i + paramsCount >= args.length - && method != null - && method.getParameterList().getParametersCount() == i + 2 - && method.getParameterList().getParameters()[i + 1].isVarArgs() - && !hasArrayTypeAt(i + 1, methodCall)) { - myProblems.add(myManager.createProblemDescriptor( - methodCall, - CodeInsightLocalize.propertyHasMoreParametersThanPassed(key, paramsCount, args.length - i - 1).get(), - onTheFly, - new LocalQuickFix[0], - ProblemHighlightType.GENERIC_ERROR - )); + PsiMethod method = methodCall.resolveMethod(); + PsiExpression[] args = expressions.getExpressions(); + for (int i = 0; i < args.length; i++) { + if (args[i] == expression) { + if (i + paramsCount >= args.length + && method != null + && method.getParameterList().getParametersCount() == i + 2 + && method.getParameterList().getParameters()[i + 1].isVarArgs() + && !hasArrayTypeAt(i + 1, methodCall)) { + LocalQuickFix[] fixes = new LocalQuickFix[0]; + myProblems.add( + myManager.newProblemDescriptor(CodeInsightLocalize.propertyHasMoreParametersThanPassed( + key, + paramsCount, + args.length - i - 1 + )) + .range(methodCall) + .highlightType(ProblemHighlightType.GENERIC_ERROR) + .onTheFly(onTheFly) + .withFixes(fixes) + .create() + ); + } + break; + } + } } - break; - } } - } - } - private static void appendPropertyKeyNotFoundProblem( - @Nonnull String bundleName, - @Nonnull String key, - @Nonnull PsiLiteralExpression expression, - @Nonnull InspectionManager manager, - @Nonnull List problems, - boolean onTheFly - ) { - final LocalizeValue description = CodeInsightLocalize.inspectionUnresolvedPropertyKeyReferenceMessage(key); - final List propertiesFiles = - filterNotInLibrary(expression.getProject(), I18nUtil.propertiesFilesByBundleName(bundleName, expression)); - problems.add( - manager.createProblemDescriptor( - expression, - description.get(), - propertiesFiles.isEmpty() ? null : new JavaCreatePropertyFix(expression, key, propertiesFiles), - ProblemHighlightType.LIKE_UNKNOWN_SYMBOL, onTheFly - ) - ); - } + @RequiredReadAction + private static void appendPropertyKeyNotFoundProblem( + @Nonnull String bundleName, + @Nonnull String key, + @Nonnull PsiLiteralExpression expression, + @Nonnull InspectionManager manager, + @Nonnull List problems, + boolean onTheFly + ) { + List propertiesFiles = + filterNotInLibrary(expression.getProject(), I18nUtil.propertiesFilesByBundleName(bundleName, expression)); + problems.add( + manager.newProblemDescriptor(CodeInsightLocalize.inspectionUnresolvedPropertyKeyReferenceMessage(key)) + .range(expression) + .highlightType(ProblemHighlightType.LIKE_UNKNOWN_SYMBOL) + .onTheFly(onTheFly) + .withOptionalFix(propertiesFiles.isEmpty() ? null : new JavaCreatePropertyFix(expression, key, propertiesFiles)) + .create() + ); + } - @Nonnull - private static List filterNotInLibrary(@Nonnull Project project, @Nonnull List propertiesFiles) { - final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex(); + @Nonnull + private static List filterNotInLibrary(@Nonnull Project project, @Nonnull List propertiesFiles) { + ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex(); - final List result = new ArrayList<>(propertiesFiles.size()); - for (final PropertiesFile file : propertiesFiles) { - if (!fileIndex.isInLibraryClasses(file.getVirtualFile()) && !fileIndex.isInLibrarySource(file.getVirtualFile())) { - result.add(file); + List result = new ArrayList<>(propertiesFiles.size()); + for (PropertiesFile file : propertiesFiles) { + if (!fileIndex.isInLibraryClasses(file.getVirtualFile()) && !fileIndex.isInLibrarySource(file.getVirtualFile())) { + result.add(file); + } + } + return result; } - } - return result; - } - private static boolean hasArrayTypeAt(int i, PsiMethodCallExpression methodCall) { - return methodCall != null - && methodCall.getArgumentList().getExpressionTypes().length > i - && methodCall.getArgumentList().getExpressionTypes()[i] instanceof PsiArrayType; - } + private static boolean hasArrayTypeAt(int i, PsiMethodCallExpression methodCall) { + return methodCall != null + && methodCall.getArgumentList().getExpressionTypes().length > i + && methodCall.getArgumentList().getExpressionTypes()[i] instanceof PsiArrayType; + } - private static boolean isComputablePropertyExpression(PsiExpression expression) { - while (expression != null && expression.getParent() instanceof PsiParenthesizedExpression parenthesizedExpression) { - expression = parenthesizedExpression; - } - return expression != null && expression.getParent() instanceof PsiExpression; - } + private static boolean isComputablePropertyExpression(PsiExpression expression) { + while (expression != null && expression.getParent() instanceof PsiParenthesizedExpression parenthesizedExpr) { + expression = parenthesizedExpr; + } + return expression != null && expression.getParent() instanceof PsiExpression; + } - public List getProblems() { - return myProblems; + public List getProblems() { + return myProblems; + } } - } } diff --git a/java-properties-impl/src/main/java/consulo/java/properties/impl/i18n/JavaPropertiesUtil.java b/java-properties-impl/src/main/java/consulo/java/properties/impl/i18n/JavaPropertiesUtil.java index 324b78d86..93925d0ba 100644 --- a/java-properties-impl/src/main/java/consulo/java/properties/impl/i18n/JavaPropertiesUtil.java +++ b/java-properties-impl/src/main/java/consulo/java/properties/impl/i18n/JavaPropertiesUtil.java @@ -8,108 +8,101 @@ import com.intellij.lang.properties.PropertiesUtil; import com.intellij.lang.properties.psi.PropertiesFile; import com.intellij.lang.properties.references.I18nUtil; +import consulo.annotation.access.RequiredReadAction; import consulo.java.analysis.impl.util.JavaI18nUtil; import consulo.java.properties.impl.psi.PropertyCreationHandler; import consulo.language.psi.PsiPolyVariantReference; import consulo.language.psi.PsiReference; import consulo.language.psi.ResolveResult; -import consulo.language.util.IncorrectOperationException; import consulo.project.Project; -import consulo.util.lang.ref.Ref; +import consulo.util.lang.ref.SimpleReference; import jakarta.annotation.Nonnull; import java.text.MessageFormat; -import java.util.Collection; import java.util.HashMap; import java.util.List; +import java.util.Map; /** * @author VISTALL - * @since 20/12/2022 + * @since 2022-12-20 */ public class JavaPropertiesUtil { - public static final PropertyCreationHandler DEFAULT_PROPERTY_CREATION_HANDLER = new PropertyCreationHandler() { - @Override - public void createProperty(final Project project, - final Collection propertiesFiles, - final String key, - final String value, - final PsiExpression[] parameters) throws IncorrectOperationException { - I18nUtil.createProperty(project, propertiesFiles, key, value); - } - }; - + public static final PropertyCreationHandler DEFAULT_PROPERTY_CREATION_HANDLER = + (project, propertiesFiles, key, value, parameters) -> + I18nUtil.createProperty(project, propertiesFiles, key, value); - public static boolean isPropertyRef(final PsiLiteralExpression expression, final String key, final String resourceBundleName) { - if (resourceBundleName == null) { - return !PropertiesUtil.findPropertiesByKey(expression.getProject(), key).isEmpty(); - } - else { - final List propertiesFiles = I18nUtil.propertiesFilesByBundleName(resourceBundleName, expression); - boolean containedInPropertiesFile = false; - for (PropertiesFile propertiesFile : propertiesFiles) { - containedInPropertiesFile |= propertiesFile.findPropertyByKey(key) != null; - } - return containedInPropertiesFile; + public static boolean isPropertyRef(PsiLiteralExpression expression, String key, String resourceBundleName) { + if (resourceBundleName == null) { + return !PropertiesUtil.findPropertiesByKey(expression.getProject(), key).isEmpty(); + } + else { + List propertiesFiles = I18nUtil.propertiesFilesByBundleName(resourceBundleName, expression); + boolean containedInPropertiesFile = false; + for (PropertiesFile propertiesFile : propertiesFiles) { + containedInPropertiesFile |= propertiesFile.findPropertyByKey(key) != null; + } + return containedInPropertiesFile; + } } - } - /** - * Returns number of different parameters in i18n message. For example, for string - * Class {0} info: Class {0} extends class {1} and implements interface {2} - * number of parameters is 3. - * - * @param expression i18n literal - * @return number of parameters - */ - public static int getPropertyValueParamsMaxCount(final PsiLiteralExpression expression) { - int maxCount = -1; - for (PsiReference reference : expression.getReferences()) { - if (reference instanceof PsiPolyVariantReference) { - for (ResolveResult result : ((PsiPolyVariantReference)reference).multiResolve(false)) { - if (result.isValidResult() && result.getElement() instanceof IProperty) { - String value = ((IProperty)result.getElement()).getValue(); - MessageFormat format; - try { - format = new MessageFormat(value); - } - catch (Exception e) { - continue; // ignore syntax error + /** + * Returns number of different parameters in i18n message. For example, for string + * Class {0} info: Class {0} extends class {1} and implements interface {2} + * number of parameters is 3. + * + * @param expression i18n literal + * @return number of parameters + */ + @RequiredReadAction + public static int getPropertyValueParamsMaxCount(PsiLiteralExpression expression) { + int maxCount = -1; + for (PsiReference reference : expression.getReferences()) { + if (reference instanceof PsiPolyVariantReference polyVariantRef) { + for (ResolveResult result : polyVariantRef.multiResolve(false)) { + if (result.isValidResult() && result.getElement() instanceof IProperty property) { + String value = property.getValue(); + MessageFormat format; + try { + format = new MessageFormat(value); + } + catch (Exception e) { + continue; // ignore syntax error + } + try { + int count = format.getFormatsByArgumentIndex().length; + maxCount = Math.max(maxCount, count); + } + catch (IllegalArgumentException ignored) { + } + } + } } - try { - int count = format.getFormatsByArgumentIndex().length; - maxCount = Math.max(maxCount, count); - } - catch (IllegalArgumentException ignored) { - } - } } - } + return maxCount; } - return maxCount; - } - - public static boolean isValidPropertyReference(@Nonnull Project project, - @Nonnull PsiLiteralExpression expression, - @Nonnull String key, - @Nonnull Ref outResourceBundle) { - final HashMap annotationAttributeValues = new HashMap(); - annotationAttributeValues.put(AnnotationUtil.PROPERTY_KEY_RESOURCE_BUNDLE_PARAMETER, null); - if (JavaI18nUtil.mustBePropertyKey(project, expression, annotationAttributeValues)) { - final Object resourceBundleName = annotationAttributeValues.get(AnnotationUtil.PROPERTY_KEY_RESOURCE_BUNDLE_PARAMETER); - if (!(resourceBundleName instanceof PsiExpression)) { - return false; - } - PsiExpression expr = (PsiExpression)resourceBundleName; - final Object value = JavaPsiFacade.getInstance(expr.getProject()).getConstantEvaluationHelper().computeConstantExpression(expr); - if (value == null) { - return false; - } - String bundleName = value.toString(); - outResourceBundle.set(bundleName); - return isPropertyRef(expression, key, bundleName); + public static boolean isValidPropertyReference( + @Nonnull Project project, + @Nonnull PsiLiteralExpression expression, + @Nonnull String key, + @Nonnull SimpleReference outResourceBundle + ) { + Map annotationAttributeValues = new HashMap<>(); + annotationAttributeValues.put(AnnotationUtil.PROPERTY_KEY_RESOURCE_BUNDLE_PARAMETER, null); + if (JavaI18nUtil.mustBePropertyKey(project, expression, annotationAttributeValues)) { + Object resourceBundleName = annotationAttributeValues.get(AnnotationUtil.PROPERTY_KEY_RESOURCE_BUNDLE_PARAMETER); + if (!(resourceBundleName instanceof PsiExpression expr)) { + return false; + } + Object value = JavaPsiFacade.getInstance(expr.getProject()).getConstantEvaluationHelper().computeConstantExpression(expr); + if (value == null) { + return false; + } + String bundleName = value.toString(); + outResourceBundle.set(bundleName); + return isPropertyRef(expression, key, bundleName); + } + return true; } - return true; - } } diff --git a/plugin/src/main/java/com/intellij/java/impl/codeInspection/RedundantSuppressInspection.java b/plugin/src/main/java/com/intellij/java/impl/codeInspection/RedundantSuppressInspection.java index bbd3d7671..d8234cd3c 100644 --- a/plugin/src/main/java/com/intellij/java/impl/codeInspection/RedundantSuppressInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/codeInspection/RedundantSuppressInspection.java @@ -48,7 +48,6 @@ import consulo.util.lang.StringUtil; import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; -import org.jetbrains.annotations.NonNls; import javax.swing.*; import java.util.*; @@ -92,9 +91,8 @@ public LocalizeValue getDisplayName() { return InspectionLocalize.inspectionRedundantSuppressionName(); } - @Override @Nonnull - @NonNls + @Override public String getShortName() { return "RedundantSuppression"; } @@ -106,7 +104,7 @@ public JComponent createOptionsPanel() { @Override public void runInspection( - @Nonnull final AnalysisScope scope, + @Nonnull AnalysisScope scope, @Nonnull final InspectionManager manager, @Nonnull final GlobalInspectionContext globalContext, @Nonnull final ProblemDescriptionsProcessor problemDescriptionsProcessor, @@ -123,9 +121,9 @@ public void visitClass(@Nonnull RefClass refClass) { if (descriptors != null) { for (CommonProblemDescriptor descriptor : descriptors) { if (descriptor instanceof ProblemDescriptor problemDescriptor) { - final PsiElement psiElement = problemDescriptor.getPsiElement(); - final PsiMember member = PsiTreeUtil.getParentOfType(psiElement, PsiMember.class); - final RefElement refElement = globalContext.getRefManager().getReference(member); + PsiElement psiElement = problemDescriptor.getPsiElement(); + PsiMember member = PsiTreeUtil.getParentOfType(psiElement, PsiMember.class); + RefElement refElement = globalContext.getRefManager().getReference(member); if (refElement != null) { problemDescriptionsProcessor.addProblemElement(refElement, descriptor); continue; @@ -146,7 +144,7 @@ private CommonProblemDescriptor[] checkElement( @Nonnull Project project, Object state ) { - final PsiClass psiClass = refEntity.getElement(); + PsiClass psiClass = refEntity.getElement(); if (psiClass == null) { return null; } @@ -165,9 +163,8 @@ public CommonProblemDescriptor[] checkElement( @Override public void visitModifierList(@Nonnull PsiModifierList list) { super.visitModifierList(list); - final PsiElement parent = list.getParent(); - if (parent instanceof PsiModifierListOwner && !(parent instanceof PsiClass)) { - checkElement(parent); + if (list.getParent() instanceof PsiModifierListOwner modifierListOwner && !(modifierListOwner instanceof PsiClass)) { + checkElement(modifierListOwner); } } @@ -184,7 +181,7 @@ public void visitClass(@Nonnull PsiClass aClass) { } } - private void checkElement(final PsiElement owner) { + private void checkElement( PsiElement owner) { String idsString = JavaSuppressionUtil.getSuppressedInspectionIdsIn(owner); if (idsString != null && !idsString.isEmpty()) { List ids = StringUtil.split(idsString, ","); @@ -215,16 +212,16 @@ private void checkElement(final PsiElement owner) { InspectionToolWrapper[] toolWrappers = getInspectionTools(psiElement, manager); for (Collection ids : suppressedScopes.values()) { for (Iterator iterator = ids.iterator(); iterator.hasNext(); ) { - final String shortName = iterator.next().trim(); + String shortName = iterator.next().trim(); for (InspectionToolWrapper toolWrapper : toolWrappers) { - if (toolWrapper instanceof LocalInspectionToolWrapper localInspectionToolWrapper - && localInspectionToolWrapper.getTool().getID().equals(shortName)) { - if (localInspectionToolWrapper.isUnfair()) { + if (toolWrapper instanceof LocalInspectionToolWrapper localToolWrapper + && localToolWrapper.getTool().getID().equals(shortName)) { + if (localToolWrapper.isUnfair()) { iterator.remove(); break; } else { - suppressedTools.add(toolWrapper); + suppressedTools.add(localToolWrapper); } } else if (toolWrapper.getShortName().equals(shortName)) { @@ -246,9 +243,9 @@ else if (toolWrapper.getShortName().equals(shortName)) { final GlobalInspectionContextBase globalContext = new GlobalInspectionContextBase(file.getProject()); globalContext.setCurrentScope(scope); - final RefManagerImpl refManager = (RefManagerImpl) globalContext.getRefManager(); + RefManagerImpl refManager = (RefManagerImpl) globalContext.getRefManager(); refManager.inspectionReadActionStarted(); - final List result; + List result; try { result = new ArrayList<>(); for (InspectionToolWrapper toolWrapper : suppressedTools) { @@ -258,7 +255,7 @@ else if (toolWrapper.getShortName().equals(shortName)) { final Collection descriptors; if (toolWrapper instanceof LocalInspectionToolWrapper local) { if (local.isUnfair()) { - continue; //cant't work with passes other than LocalInspectionPass + continue; //can't work with passes other than LocalInspectionPass } List results = manager.runLocalToolLocaly(local.getTool(), file, state); descriptors = new ArrayList<>(results); @@ -317,10 +314,10 @@ public RefEntity getElement(@Nonnull CommonProblemDescriptor descriptor) { continue; } for (CommonProblemDescriptor descriptor : descriptors) { - if (!(descriptor instanceof ProblemDescriptor)) { + if (!(descriptor instanceof ProblemDescriptor problemDescriptor)) { continue; } - PsiElement element = ((ProblemDescriptor) descriptor).getPsiElement(); + PsiElement element = problemDescriptor.getPsiElement(); if (element == null) { continue; } @@ -343,15 +340,14 @@ public RefEntity getElement(@Nonnull CommonProblemDescriptor descriptor) { } else { psiMember = PsiTreeUtil.getParentOfType(suppressedScope, PsiDocCommentOwner.class); - final PsiStatement statement = PsiTreeUtil.getNextSiblingOfType(suppressedScope, PsiStatement.class); + PsiStatement statement = PsiTreeUtil.getNextSiblingOfType(suppressedScope, PsiStatement.class); problemLine = statement != null ? statement.getText() : null; } if (psiMember != null && psiMember.isValid()) { - String description = InspectionLocalize.inspectionRedundantSuppressionDescription().get(); if (myQuickFixes == null) { myQuickFixes = new BidirectionalMap<>(); } - final String key = toolId + (problemLine != null ? ";" + problemLine : ""); + String key = toolId + (problemLine != null ? ";" + problemLine : ""); QuickFix fix = myQuickFixes.get(key); if (fix == null) { fix = new RemoveSuppressWarningAction(toolId, problemLine); @@ -370,13 +366,12 @@ else if (psiMember instanceof PsiClass psiClass) { if (identifier == null) { identifier = psiMember; } - result.add(manager.createProblemDescriptor( - identifier, - description, - (LocalQuickFix) fix, - ProblemHighlightType.GENERIC_ERROR_OR_WARNING, - false - )); + result.add( + manager.newProblemDescriptor(InspectionLocalize.inspectionRedundantSuppressionDescription()) + .range(identifier) + .withFix((LocalQuickFix) fix) + .create() + ); } } } @@ -396,19 +391,17 @@ protected InspectionToolWrapper[] getInspectionTools(PsiElement psiElement, @Non return profile.getInspectionTools(psiElement); } - - @Override @Nullable - public QuickFix getQuickFix(final String hint) { + @Override + public QuickFix getQuickFix(String hint) { return myQuickFixes != null ? myQuickFixes.get(hint) : new RemoveSuppressWarningAction(hint); } - - @Override @Nullable - public String getHint(@Nonnull final QuickFix fix) { + @Override + public String getHint(@Nonnull QuickFix fix) { if (myQuickFixes != null) { - final List list = myQuickFixes.getKeysByValue(fix); + List list = myQuickFixes.getKeysByValue(fix); if (list != null) { LOG.assertTrue(list.size() == 1); return list.get(0); diff --git a/plugin/src/main/java/com/intellij/java/impl/codeInspection/canBeFinal/CanBeFinalInspection.java b/plugin/src/main/java/com/intellij/java/impl/codeInspection/canBeFinal/CanBeFinalInspection.java index 78828b75d..993031413 100644 --- a/plugin/src/main/java/com/intellij/java/impl/codeInspection/canBeFinal/CanBeFinalInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/codeInspection/canBeFinal/CanBeFinalInspection.java @@ -13,15 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -/* - * Created by IntelliJ IDEA. - * User: max - * Date: Dec 24, 2001 - * Time: 2:46:32 PM - * To change template for new class use - * Code Style | Class Templates options (Tools | IDE Options). - */ package com.intellij.java.impl.codeInspection.canBeFinal; import com.intellij.java.analysis.codeInspection.GlobalJavaInspectionContext; @@ -32,6 +23,7 @@ import com.intellij.java.impl.codeInspection.reference.RefFieldImpl; import com.intellij.java.language.psi.*; import com.intellij.java.language.psi.util.PsiUtil; +import consulo.annotation.access.RequiredReadAction; import consulo.annotation.access.RequiredWriteAction; import consulo.annotation.component.ExtensionImpl; import consulo.java.deadCodeNotWorking.OldStyleInspection; @@ -53,11 +45,14 @@ import consulo.project.Project; import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; -import org.jetbrains.annotations.NonNls; import javax.swing.*; import java.awt.*; +/** + * @author max + * @since 2001-12-24 + */ @ExtensionImpl public class CanBeFinalInspection extends GlobalJavaInspectionTool implements OldStyleInspection { private static final Logger LOG = Logger.getInstance(CanBeFinalInspection.class); @@ -65,7 +60,6 @@ public class CanBeFinalInspection extends GlobalJavaInspectionTool implements Ol public boolean REPORT_CLASSES = false; public boolean REPORT_METHODS = false; public boolean REPORT_FIELDS = true; - @NonNls public static final String SHORT_NAME = "CanBeFinal"; private class OptionsPanel extends JPanel { @@ -124,18 +118,19 @@ public JComponent createOptionsPanel() { @Override @Nullable - public RefGraphAnnotator getAnnotator(final RefManager refManager) { + public RefGraphAnnotator getAnnotator(@Nonnull RefManager refManager) { return new CanBeFinalAnnotator(refManager); } - @Override @Nullable + @Override + @RequiredReadAction public CommonProblemDescriptor[] checkElement( - @Nonnull final RefEntity refEntity, - @Nonnull final AnalysisScope scope, - @Nonnull final InspectionManager manager, - @Nonnull final GlobalInspectionContext globalContext, - @Nonnull final ProblemDescriptionsProcessor processor, + @Nonnull RefEntity refEntity, + @Nonnull AnalysisScope scope, + @Nonnull InspectionManager manager, + @Nonnull GlobalInspectionContext globalContext, + @Nonnull ProblemDescriptionsProcessor processor, @Nonnull Object state ) { if (refEntity instanceof RefJavaElement refElement) { @@ -144,7 +139,7 @@ public CommonProblemDescriptor[] checkElement( return null; } - final PsiMember psiMember = (PsiMember) refElement.getElement(); + PsiMember psiMember = (PsiMember) refElement.getElement(); if (psiMember == null || !CanBeFinalHandler.allowToBeFinal(psiMember)) { return null; } @@ -156,8 +151,7 @@ public CommonProblemDescriptor[] checkElement( } psiIdentifier = ((PsiClass) psiMember).getNameIdentifier(); } - else if (refElement instanceof RefMethod) { - RefMethod refMethod = (RefMethod) refElement; + else if (refElement instanceof RefMethod refMethod) { if (refMethod.getOwnerClass().isFinal()) { return null; } @@ -175,13 +169,10 @@ else if (refElement instanceof RefField) { if (psiIdentifier != null) { return new ProblemDescriptor[]{ - manager.createProblemDescriptor( - psiIdentifier, - InspectionLocalize.inspectionExportResultsCanBeFinalDescription().get(), - new AcceptSuggested(globalContext.getRefManager()), - ProblemHighlightType.GENERIC_ERROR_OR_WARNING, - false - ) + manager.newProblemDescriptor(InspectionLocalize.inspectionExportResultsCanBeFinalDescription()) + .range(psiIdentifier) + .withFix(new AcceptSuggested(globalContext.getRefManager())) + .create() }; } } @@ -190,7 +181,7 @@ else if (refElement instanceof RefField) { @Override protected boolean queryExternalUsagesRequests( - final RefManager manager, + RefManager manager, final GlobalJavaInspectionContext globalContext, final ProblemDescriptionsProcessor problemsProcessor, Object state @@ -207,7 +198,7 @@ public void visitElement(@Nonnull RefEntity refEntity) { } refEntity.accept(new RefJavaVisitor() { @Override - public void visitMethod(@Nonnull final RefMethod refMethod) { + public void visitMethod(@Nonnull RefMethod refMethod) { if (!refMethod.isStatic() && !PsiModifier.PRIVATE.equals(refMethod.getAccessModifier()) && !(refMethod instanceof RefImplicitConstructor)) { globalContext.enqueueDerivedMethodsProcessor(refMethod, derivedMethod -> { @@ -219,7 +210,7 @@ public void visitMethod(@Nonnull final RefMethod refMethod) { } @Override - public void visitClass(@Nonnull final RefClass refClass) { + public void visitClass(@Nonnull RefClass refClass) { if (!refClass.isAnonymous()) { globalContext.enqueueDerivedClassesProcessor( refClass, @@ -233,12 +224,12 @@ public void visitClass(@Nonnull final RefClass refClass) { } @Override - public void visitField(@Nonnull final RefField refField) { + public void visitField(@Nonnull RefField refField) { globalContext.enqueueFieldUsagesProcessor( refField, psiReference -> { - PsiElement expression = psiReference.getElement(); - if (expression instanceof PsiReferenceExpression referenceExpression && PsiUtil.isAccessedForWriting(referenceExpression)) { + if (psiReference.getElement() instanceof PsiReferenceExpression referenceExpression + && PsiUtil.isAccessedForWriting(referenceExpression)) { ((RefFieldImpl) refField).setFlag(false, CanBeFinalAnnotator.CAN_BE_FINAL_MASK); problemsProcessor.ignoreElement(refField); return false; @@ -255,20 +246,20 @@ public void visitField(@Nonnull final RefField refField) { } - @Override @Nullable - public QuickFix getQuickFix(final String hint) { + @Override + public QuickFix getQuickFix(String hint) { return new AcceptSuggested(null); } - @Override @Nonnull + @Override public LocalizeValue getDisplayName() { return InspectionLocalize.inspectionCanBeFinalDisplayName(); } - @Override @Nonnull + @Override public LocalizeValue getGroupDisplayName() { return InspectionLocalize.groupNamesDeclarationRedundancy(); } @@ -282,12 +273,12 @@ public String getShortName() { private static class AcceptSuggested implements LocalQuickFix { private final RefManager myManager; - public AcceptSuggested(final RefManager manager) { + public AcceptSuggested(RefManager manager) { myManager = manager; } - @Override @Nonnull + @Override public LocalizeValue getName() { return InspectionLocalize.inspectionCanBeFinalAcceptQuickfix(); } @@ -298,15 +289,15 @@ public void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor descri if (!FileModificationService.getInstance().preparePsiElementForWrite(descriptor.getPsiElement())) { return; } - final PsiElement element = descriptor.getPsiElement(); - final PsiModifierListOwner psiElement = PsiTreeUtil.getParentOfType(element, PsiModifierListOwner.class); + PsiElement element = descriptor.getPsiElement(); + PsiModifierListOwner psiElement = PsiTreeUtil.getParentOfType(element, PsiModifierListOwner.class); if (psiElement != null) { RefJavaElement refElement = (RefJavaElement) (myManager != null ? myManager.getReference(psiElement) : null); try { if (psiElement instanceof PsiVariable variable) { variable.normalizeDeclaration(); } - final PsiModifierList modifierList = psiElement.getModifierList(); + PsiModifierList modifierList = psiElement.getModifierList(); LOG.assertTrue(modifierList != null); modifierList.setModifierProperty(PsiModifier.FINAL, true); } @@ -320,5 +311,4 @@ public void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor descri } } } - } diff --git a/plugin/src/main/java/com/intellij/java/impl/codeInspection/miscGenerics/RedundantArrayForVarargsCallInspection.java b/plugin/src/main/java/com/intellij/java/impl/codeInspection/miscGenerics/RedundantArrayForVarargsCallInspection.java index 509036579..14c87733c 100644 --- a/plugin/src/main/java/com/intellij/java/impl/codeInspection/miscGenerics/RedundantArrayForVarargsCallInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/codeInspection/miscGenerics/RedundantArrayForVarargsCallInspection.java @@ -21,11 +21,11 @@ import com.intellij.java.impl.refactoring.util.InlineUtil; import com.intellij.java.language.psi.*; import com.intellij.java.language.psi.util.PsiUtil; +import consulo.annotation.access.RequiredReadAction; import consulo.annotation.component.ExtensionImpl; import consulo.language.editor.FileModificationService; import consulo.language.editor.inspection.LocalQuickFix; import consulo.language.editor.inspection.ProblemDescriptor; -import consulo.language.editor.inspection.ProblemHighlightType; import consulo.language.editor.inspection.localize.InspectionLocalize; import consulo.language.editor.inspection.scheme.InspectionManager; import consulo.language.psi.PsiElement; @@ -33,9 +33,9 @@ import consulo.localize.LocalizeValue; import consulo.logging.Logger; import consulo.project.Project; +import consulo.ui.annotation.RequiredUIAccess; import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; -import org.jetbrains.annotations.NonNls; import java.util.ArrayList; import java.util.List; @@ -50,6 +50,7 @@ public class RedundantArrayForVarargsCallInspection extends GenericsInspectionTo private static class MyQuickFix implements LocalQuickFix { @Override + @RequiredUIAccess public void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor descriptor) { PsiNewExpression arrayCreation = (PsiNewExpression) descriptor.getPsiElement(); if (arrayCreation == null || !arrayCreation.isValid()) { @@ -69,6 +70,7 @@ public LocalizeValue getName() { } @Override + @RequiredReadAction public ProblemDescriptor[] getDescriptions(PsiElement place, final InspectionManager manager, final boolean isOnTheFly, Object state) { if (!PsiUtil.isLanguageLevel5OrHigher(place)) { return null; @@ -76,12 +78,14 @@ public ProblemDescriptor[] getDescriptions(PsiElement place, final InspectionMan final List problems = new ArrayList<>(); place.accept(new JavaRecursiveElementWalkingVisitor() { @Override + @RequiredReadAction public void visitCallExpression(@Nonnull PsiCallExpression expression) { super.visitCallExpression(expression); checkCall(expression); } @Override + @RequiredReadAction public void visitEnumConstant(@Nonnull PsiEnumConstant enumConstant) { super.visitEnumConstant(enumConstant); checkCall(enumConstant); @@ -92,11 +96,11 @@ public void visitClass(@Nonnull PsiClass aClass) { //do not go inside to prevent multiple signals of the same problem } + @RequiredReadAction private void checkCall(PsiCall expression) { - final JavaResolveResult resolveResult = expression.resolveMethodGenerics(); - PsiElement element = resolveResult.getElement(); - final PsiSubstitutor substitutor = resolveResult.getSubstitutor(); - if (element instanceof PsiMethod method && method.isVarArgs()) { + JavaResolveResult resolveResult = expression.resolveMethodGenerics(); + PsiSubstitutor substitutor = resolveResult.getSubstitutor(); + if (resolveResult.getElement() instanceof PsiMethod method && method.isVarArgs()) { PsiParameter[] parameters = method.getParameterList().getParameters(); PsiExpressionList argumentList = expression.getArgumentList(); if (argumentList != null) { @@ -109,18 +113,16 @@ private void checkCall(PsiCall expression) { if (lastArg instanceof PsiNewExpression newExpression && substitutor.substitute(((PsiEllipsisType) lastParamType).toArrayType()).equals(lastArg.getType())) { PsiExpression[] initializers = getInitializers(newExpression); - if (initializers != null) { - if (isSafeToFlatten(expression, method, initializers)) { - final ProblemDescriptor descriptor = manager.createProblemDescriptor( - lastArg, - InspectionLocalize.inspectionRedundantArrayCreationForVarargsCallDescriptor().get(), - myQuickFixAction, - ProblemHighlightType.GENERIC_ERROR_OR_WARNING, - isOnTheFly - ); - - problems.add(descriptor); - } + if (initializers != null && isSafeToFlatten(expression, method, initializers)) { + ProblemDescriptor descriptor = manager.newProblemDescriptor( + InspectionLocalize.inspectionRedundantArrayCreationForVarargsCallDescriptor() + ) + .range(lastArg) + .onTheFly(isOnTheFly) + .withFix(myQuickFixAction) + .create(); + + problems.add(descriptor); } } } @@ -145,12 +147,12 @@ private boolean isSafeToFlatten(PsiCall callExpression, PsiMethod oldRefMethod, if (arrayElements.length > 0) { copyArgumentList.addRange(arrayElements[0], arrayElements[arrayElements.length - 1]); } - final Project project = callExpression.getProject(); - final JavaResolveResult resolveResult; + Project project = callExpression.getProject(); + JavaResolveResult resolveResult; if (callExpression instanceof PsiEnumConstant enumConstant) { - final PsiClass containingClass = enumConstant.getContainingClass(); - final JavaPsiFacade facade = JavaPsiFacade.getInstance(project); - final PsiClassType classType = facade.getElementFactory().createType(containingClass); + PsiClass containingClass = enumConstant.getContainingClass(); + JavaPsiFacade facade = JavaPsiFacade.getInstance(project); + PsiClassType classType = facade.getElementFactory().createType(containingClass); resolveResult = facade.getResolveHelper().resolveConstructor(classType, copyArgumentList, enumConstant); return resolveResult.isValidResult() && resolveResult.getElement() == oldRefMethod; } @@ -159,9 +161,9 @@ private boolean isSafeToFlatten(PsiCall callExpression, PsiMethod oldRefMethod, if (!resolveResult.isValidResult() || resolveResult.getElement() != oldRefMethod) { return false; } - final ExpectedTypeInfo[] expectedTypes = + ExpectedTypeInfo[] expectedTypes = ExpectedTypesProvider.getExpectedTypes((PsiCallExpression) callExpression, false); - final PsiType expressionType = ((PsiCallExpression) copy).getType(); + PsiType expressionType = ((PsiCallExpression) copy).getType(); for (ExpectedTypeInfo expectedType : expectedTypes) { if (!expectedType.getType().isAssignableFrom(expressionType)) { return false; @@ -182,7 +184,7 @@ private boolean isSafeToFlatten(PsiCall callExpression, PsiMethod oldRefMethod, } @Nullable - private static PsiExpression[] getInitializers(final PsiNewExpression newExpression) { + private static PsiExpression[] getInitializers(PsiNewExpression newExpression) { PsiArrayInitializerExpression initializer = newExpression.getArrayInitializer(); if (initializer != null) { return initializer.getInitializers(); @@ -219,9 +221,8 @@ public LocalizeValue getDisplayName() { return InspectionLocalize.inspectionRedundantArrayCreationDisplayName(); } - @Override @Nonnull - @NonNls + @Override public String getShortName() { return "RedundantArrayCreation"; } diff --git a/plugin/src/main/java/com/intellij/java/impl/codeInspection/sameParameterValue/SameParameterValueInspection.java b/plugin/src/main/java/com/intellij/java/impl/codeInspection/sameParameterValue/SameParameterValueInspection.java index 131a71d72..2887da06a 100644 --- a/plugin/src/main/java/com/intellij/java/impl/codeInspection/sameParameterValue/SameParameterValueInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/codeInspection/sameParameterValue/SameParameterValueInspection.java @@ -24,6 +24,7 @@ import com.intellij.java.impl.refactoring.changeSignature.ParameterInfoImpl; import com.intellij.java.impl.refactoring.util.InlineUtil; import com.intellij.java.language.psi.*; +import consulo.annotation.access.RequiredReadAction; import consulo.annotation.access.RequiredWriteAction; import consulo.annotation.component.ExtensionImpl; import consulo.language.editor.inspection.*; @@ -58,8 +59,9 @@ public class SameParameterValueInspection extends GlobalJavaInspectionTool { private static final Logger LOG = Logger.getInstance(SameParameterValueInspection.class); - @Override @Nullable + @Override + @RequiredReadAction public CommonProblemDescriptor[] checkElement( @Nonnull RefEntity refEntity, @Nonnull AnalysisScope scope, @@ -68,7 +70,7 @@ public CommonProblemDescriptor[] checkElement( @Nonnull ProblemDescriptionsProcessor processor, @Nonnull Object state ) { - ArrayList problems = null; + List problems = null; if (refEntity instanceof RefMethod refMethod) { if (refMethod.hasSuperMethods()) { return null; @@ -85,17 +87,16 @@ public CommonProblemDescriptor[] checkElement( if (problems == null) { problems = new ArrayList<>(1); } - final String paramName = refParameter.getName(); - problems.add(manager.createProblemDescriptor( - refParameter.getElement(), - InspectionLocalize.inspectionSameParameterProblemDescriptor( - "" + paramName + "", - "" + value + "" - ).get(), - new InlineParameterValueFix(paramName, value), - ProblemHighlightType.GENERIC_ERROR_OR_WARNING, - false - )); + String paramName = refParameter.getName(); + problems.add( + manager.newProblemDescriptor(InspectionLocalize.inspectionSameParameterProblemDescriptor( + "" + paramName + "", + "" + value + "" + )) + .range(refParameter.getElement()) + .withFix(new InlineParameterValueFix(paramName, value)) + .create() + ); } } } @@ -106,7 +107,8 @@ public CommonProblemDescriptor[] checkElement( @Override protected boolean queryExternalUsagesRequests( - final RefManager manager, final GlobalJavaInspectionContext globalContext, + RefManager manager, + final GlobalJavaInspectionContext globalContext, final ProblemDescriptionsProcessor processor, Object state ) { manager.iterate(new RefJavaVisitor() { @@ -115,7 +117,7 @@ public void visitElement(@Nonnull RefEntity refEntity) { if (refEntity instanceof RefElement && processor.getDescriptions(refEntity) != null) { refEntity.accept(new RefJavaVisitor() { @Override - public void visitMethod(@Nonnull final RefMethod refMethod) { + public void visitMethod(@Nonnull RefMethod refMethod) { globalContext.enqueueMethodUsagesProcessor(refMethod, psiReference -> { processor.ignoreElement(refMethod); return false; @@ -149,23 +151,23 @@ public String getShortName() { @Override @Nullable - public QuickFix getQuickFix(final String hint) { + public QuickFix getQuickFix(String hint) { if (hint == null) { return null; } - final int spaceIdx = hint.indexOf(' '); + int spaceIdx = hint.indexOf(' '); if (spaceIdx == -1 || spaceIdx >= hint.length() - 1) { return null; //invalid hint } - final String paramName = hint.substring(0, spaceIdx); - final String value = hint.substring(spaceIdx + 1); + String paramName = hint.substring(0, spaceIdx); + String value = hint.substring(spaceIdx + 1); return new InlineParameterValueFix(paramName, value); } - @Override @Nullable - public String getHint(@Nonnull final QuickFix fix) { - final InlineParameterValueFix valueFix = (InlineParameterValueFix) fix; + @Override + public String getHint(@Nonnull QuickFix fix) { + InlineParameterValueFix valueFix = (InlineParameterValueFix) fix; return valueFix.getParamName() + " " + valueFix.getValue(); } @@ -173,7 +175,7 @@ public static class InlineParameterValueFix implements LocalQuickFix { private final String myValue; private final String myParameterName; - public InlineParameterValueFix(final String parameterName, final String value) { + public InlineParameterValueFix(String parameterName, String value) { myValue = value; myParameterName = parameterName; } @@ -186,13 +188,13 @@ public LocalizeValue getName() { @Override @RequiredWriteAction - public void applyFix(@Nonnull final Project project, @Nonnull ProblemDescriptor descriptor) { - final PsiElement element = descriptor.getPsiElement(); - final PsiMethod method = PsiTreeUtil.getParentOfType(element, PsiMethod.class); + public void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor descriptor) { + PsiElement element = descriptor.getPsiElement(); + PsiMethod method = PsiTreeUtil.getParentOfType(element, PsiMethod.class); LOG.assertTrue(method != null); PsiParameter parameter = PsiTreeUtil.getParentOfType(element, PsiParameter.class, false); if (parameter == null) { - final PsiParameter[] parameters = method.getParameterList().getParameters(); + PsiParameter[] parameters = method.getParameterList().getParameters(); for (PsiParameter psiParameter : parameters) { if (Comparing.strEqual(psiParameter.getName(), myParameterName)) { parameter = psiParameter; @@ -204,20 +206,20 @@ public void applyFix(@Nonnull final Project project, @Nonnull ProblemDescriptor return; } - final PsiExpression defToInline; + PsiExpression defToInline; try { defToInline = JavaPsiFacade.getInstance(project).getElementFactory().createExpressionFromText(myValue, parameter); } catch (IncorrectOperationException e) { return; } - final PsiParameter parameterToInline = parameter; + PsiParameter parameterToInline = parameter; inlineSameParameterValue(method, parameterToInline, defToInline); } @RequiredUIAccess - public static void inlineSameParameterValue(final PsiMethod method, final PsiParameter parameter, final PsiExpression defToInline) { - final Collection refsToInline = ReferencesSearch.search(parameter).findAll(); + public static void inlineSameParameterValue(PsiMethod method, PsiParameter parameter, PsiExpression defToInline) { + Collection refsToInline = ReferencesSearch.search(parameter).findAll(); method.getApplication().runWriteAction(() -> { try { @@ -229,7 +231,7 @@ public static void inlineSameParameterValue(final PsiMethod method, final PsiPar } } - for (final PsiExpression expr : exprs) { + for (PsiExpression expr : exprs) { if (expr != null) { InlineUtil.tryToInlineArrayCreationForVarargs(expr); } @@ -243,11 +245,12 @@ public static void inlineSameParameterValue(final PsiMethod method, final PsiPar removeParameter(method, parameter); } - public static void removeParameter(final PsiMethod method, final PsiParameter parameter) { - final PsiParameter[] parameters = method.getParameterList().getParameters(); - final List psiParameters = new ArrayList<>(); + @RequiredUIAccess + public static void removeParameter(PsiMethod method, PsiParameter parameter) { + PsiParameter[] parameters = method.getParameterList().getParameters(); + List psiParameters = new ArrayList<>(); int paramIdx = 0; - final String paramName = parameter.getName(); + String paramName = parameter.getName(); for (PsiParameter param : parameters) { if (!Comparing.strEqual(paramName, param.getName())) { psiParameters.add(new ParameterInfoImpl(paramIdx, param.getName(), param.getType())); diff --git a/plugin/src/main/java/com/intellij/java/impl/codeInspection/unneededThrows/RedundantThrows.java b/plugin/src/main/java/com/intellij/java/impl/codeInspection/unneededThrows/RedundantThrows.java index 4b771248c..2daf52882 100644 --- a/plugin/src/main/java/com/intellij/java/impl/codeInspection/unneededThrows/RedundantThrows.java +++ b/plugin/src/main/java/com/intellij/java/impl/codeInspection/unneededThrows/RedundantThrows.java @@ -47,7 +47,6 @@ import consulo.util.lang.Pair; import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; -import org.jetbrains.annotations.NonNls; import java.util.ArrayList; import java.util.List; @@ -59,11 +58,11 @@ public class RedundantThrows extends GlobalJavaInspectionTool { private static final Logger LOG = Logger.getInstance(RedundantThrows.class); private final BidirectionalMap myQuickFixes = new BidirectionalMap<>(); - @NonNls private static final String SHORT_NAME = "RedundantThrows"; - @Override @Nullable + @Override + @RequiredReadAction public CommonProblemDescriptor[] checkElement( @Nonnull RefEntity refEntity, @Nonnull AnalysisScope scope, @@ -85,50 +84,56 @@ public CommonProblemDescriptor[] checkElement( PsiMethod psiMethod = (PsiMethod) refMethod.getElement(); PsiClassType[] throwsList = psiMethod.getThrowsList().getReferencedTypes(); PsiJavaCodeReferenceElement[] throwsRefs = psiMethod.getThrowsList().getReferenceElements(); - ArrayList problems = null; + List problems = null; - final PsiManager psiManager = psiMethod.getManager(); + PsiManager psiManager = psiMethod.getManager(); for (int i = 0; i < throwsList.length; i++) { - final PsiClassType throwsType = throwsList[i]; - final String throwsClassName = throwsType.getClassName(); - final PsiJavaCodeReferenceElement throwsRef = throwsRefs[i]; + PsiClassType throwsType = throwsList[i]; + String throwsClassName = throwsType.getClassName(); + PsiJavaCodeReferenceElement throwsRef = throwsRefs[i]; if (ExceptionUtil.isUncheckedException(throwsType) || declaredInRemotableMethod(psiMethod, throwsType)) { continue; } for (PsiClass s : unThrown) { - final PsiClass throwsResolvedType = throwsType.resolve(); + PsiClass throwsResolvedType = throwsType.resolve(); if (psiManager.areElementsEquivalent(s, throwsResolvedType)) { if (problems == null) { problems = new ArrayList<>(1); } if (refMethod.isAbstract() || refMethod.getOwnerClass().isInterface()) { - problems.add(manager.createProblemDescriptor( - throwsRef, - InspectionLocalize.inspectionRedundantThrowsProblemDescriptor("#ref").get(), - getFix(processor, throwsClassName), - ProblemHighlightType.LIKE_UNUSED_SYMBOL, - false - )); + problems.add( + manager.newProblemDescriptor( + InspectionLocalize.inspectionRedundantThrowsProblemDescriptor("#ref") + ) + .range(throwsRef) + .highlightType(ProblemHighlightType.LIKE_UNUSED_SYMBOL) + .withFix(getFix(processor, throwsClassName)) + .create() + ); } else if (!refMethod.getDerivedMethods().isEmpty()) { - problems.add(manager.createProblemDescriptor( - throwsRef, - InspectionLocalize.inspectionRedundantThrowsProblemDescriptor1("#ref").get(), - getFix(processor, throwsClassName), - ProblemHighlightType.LIKE_UNUSED_SYMBOL, - false - )); + problems.add( + manager.newProblemDescriptor( + InspectionLocalize.inspectionRedundantThrowsProblemDescriptor1("#ref") + ) + .range(throwsRef) + .highlightType(ProblemHighlightType.LIKE_UNUSED_SYMBOL) + .withFix(getFix(processor, throwsClassName)) + .create() + ); } else { - problems.add(manager.createProblemDescriptor( - throwsRef, - InspectionLocalize.inspectionRedundantThrowsProblemDescriptor2("#ref").get(), - getFix(processor, throwsClassName), - ProblemHighlightType.LIKE_UNUSED_SYMBOL, - false - )); + problems.add( + manager.newProblemDescriptor( + InspectionLocalize.inspectionRedundantThrowsProblemDescriptor2("#ref") + ) + .range(throwsRef) + .highlightType(ProblemHighlightType.LIKE_UNUSED_SYMBOL) + .withFix(getFix(processor, throwsClassName)) + .create() + ); } } } @@ -142,7 +147,7 @@ else if (!refMethod.getDerivedMethods().isEmpty()) { return null; } - private static boolean declaredInRemotableMethod(final PsiMethod psiMethod, final PsiClassType throwsType) { + private static boolean declaredInRemotableMethod(PsiMethod psiMethod, PsiClassType throwsType) { if (!throwsType.equalsToText("java.rmi.RemoteException")) { return false; } @@ -155,11 +160,12 @@ private static boolean declaredInRemotableMethod(final PsiMethod psiMethod, fina return remote != null && aClass.isInheritor(remote, true); } - @Override protected boolean queryExternalUsagesRequests( - final RefManager manager, final GlobalJavaInspectionContext globalContext, - final ProblemDescriptionsProcessor processor, Object state + RefManager manager, + final GlobalJavaInspectionContext globalContext, + final ProblemDescriptionsProcessor processor, + Object state ) { manager.iterate(new RefJavaVisitor() { @Override @@ -167,7 +173,7 @@ public void visitElement(@Nonnull RefEntity refEntity) { if (processor.getDescriptions(refEntity) != null) { refEntity.accept(new RefJavaVisitor() { @Override - public void visitMethod(@Nonnull final RefMethod refMethod) { + public void visitMethod(@Nonnull RefMethod refMethod) { globalContext.enqueueDerivedMethodsProcessor(refMethod, derivedMethod -> { processor.ignoreElement(refMethod); return true; @@ -193,13 +199,14 @@ public LocalizeValue getGroupDisplayName() { return InspectionLocalize.groupNamesDeclarationRedundancy(); } - @Override @Nonnull + @Override public String getShortName() { return SHORT_NAME; } - private LocalQuickFix getFix(final ProblemDescriptionsProcessor processor, final String hint) { + @Nonnull + private LocalQuickFix getFix(ProblemDescriptionsProcessor processor, String hint) { QuickFix fix = myQuickFixes.get(hint); if (fix == null) { fix = new MyQuickFix(processor, hint); @@ -210,18 +217,18 @@ private LocalQuickFix getFix(final ProblemDescriptionsProcessor processor, final return (LocalQuickFix) fix; } - - @Override @Nullable + @Override public QuickFix getQuickFix(String hint) { return getFix(null, hint); } - @Override @Nullable - public String getHint(@Nonnull final QuickFix fix) { - final List hints = myQuickFixes.getKeysByValue(fix); + @Override + public String getHint(@Nonnull QuickFix fix) { + List hints = myQuickFixes.getKeysByValue(fix); LOG.assertTrue(hints != null && hints.size() == 1); + assert hints != null; return hints.get(0); } @@ -229,7 +236,7 @@ private static class MyQuickFix implements LocalQuickFix { private final ProblemDescriptionsProcessor myProcessor; private final String myHint; - public MyQuickFix(final ProblemDescriptionsProcessor processor, final String hint) { + public MyQuickFix(ProblemDescriptionsProcessor processor, String hint) { myProcessor = processor; myHint = hint; } @@ -246,28 +253,28 @@ public void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor descri if (myProcessor != null) { RefElement refElement = (RefElement) myProcessor.getElement(descriptor); if (refElement instanceof RefMethod refMethod && refElement.isValid()) { - final CommonProblemDescriptor[] problems = myProcessor.getDescriptions(refMethod); + CommonProblemDescriptor[] problems = myProcessor.getDescriptions(refMethod); if (problems != null) { removeExcessiveThrows(refMethod, null, problems); } } } else { - final PsiMethod psiMethod = PsiTreeUtil.getParentOfType(descriptor.getPsiElement(), PsiMethod.class); + PsiMethod psiMethod = PsiTreeUtil.getParentOfType(descriptor.getPsiElement(), PsiMethod.class); if (psiMethod != null) { removeExcessiveThrows(null, psiMethod, new CommonProblemDescriptor[]{descriptor}); } } } - @RequiredReadAction + @RequiredWriteAction private void removeExcessiveThrows( @Nullable RefMethod refMethod, - @Nullable final PsiModifierListOwner element, - final CommonProblemDescriptor[] problems + @Nullable PsiModifierListOwner element, + CommonProblemDescriptor[] problems ) { try { - @Nullable final PsiMethod psiMethod; + @Nullable PsiMethod psiMethod; if (element == null) { LOG.assertTrue(refMethod != null); psiMethod = (PsiMethod) refMethod.getElement(); @@ -278,20 +285,20 @@ private void removeExcessiveThrows( if (psiMethod == null) { return; //invalid refMethod } - final Project project = psiMethod.getProject(); - final PsiManager psiManager = PsiManager.getInstance(project); - final List refsToDelete = new ArrayList<>(); + Project project = psiMethod.getProject(); + PsiManager psiManager = PsiManager.getInstance(project); + List refsToDelete = new ArrayList<>(); for (CommonProblemDescriptor problem : problems) { - final PsiElement psiElement = ((ProblemDescriptor) problem).getPsiElement(); + PsiElement psiElement = ((ProblemDescriptor) problem).getPsiElement(); if (psiElement instanceof PsiJavaCodeReferenceElement classRef) { - final PsiType psiType = JavaPsiFacade.getInstance(psiManager.getProject()).getElementFactory().createType(classRef); + PsiType psiType = JavaPsiFacade.getInstance(psiManager.getProject()).getElementFactory().createType(classRef); removeException(refMethod, psiType, refsToDelete, psiMethod); } else { - final PsiReferenceList throwsList = psiMethod.getThrowsList(); - final PsiClassType[] classTypes = throwsList.getReferencedTypes(); + PsiReferenceList throwsList = psiMethod.getThrowsList(); + PsiClassType[] classTypes = throwsList.getReferencedTypes(); for (PsiClassType classType : classTypes) { - final String text = classType.getClassName(); + String text = classType.getClassName(); if (Comparing.strEqual(myHint, text)) { removeException(refMethod, classType, refsToDelete, psiMethod); break; @@ -305,7 +312,7 @@ private void removeExcessiveThrows( return; } - for (final PsiJavaCodeReferenceElement aRefsToDelete : refsToDelete) { + for (PsiJavaCodeReferenceElement aRefsToDelete : refsToDelete) { aRefsToDelete.delete(); } } @@ -315,10 +322,10 @@ private void removeExcessiveThrows( } private static void removeException( - final RefMethod refMethod, - final PsiType exceptionType, - final List refsToDelete, - final PsiMethod psiMethod + RefMethod refMethod, + PsiType exceptionType, + List refsToDelete, + PsiMethod psiMethod ) { PsiManager psiManager = psiMethod.getManager(); @@ -336,7 +343,7 @@ private static void removeException( } } else { - final Query> query = AllOverridingMethodsSearch.search(psiMethod.getContainingClass()); + Query> query = AllOverridingMethodsSearch.search(psiMethod.getContainingClass()); query.forEach(pair -> { if (pair.first == psiMethod) { removeException(null, exceptionType, refsToDelete, pair.second); diff --git a/plugin/src/main/java/com/intellij/java/impl/codeInspection/unneededThrows/RedundantThrowsDeclaration.java b/plugin/src/main/java/com/intellij/java/impl/codeInspection/unneededThrows/RedundantThrowsDeclaration.java index ae541ae10..94a15e944 100644 --- a/plugin/src/main/java/com/intellij/java/impl/codeInspection/unneededThrows/RedundantThrowsDeclaration.java +++ b/plugin/src/main/java/com/intellij/java/impl/codeInspection/unneededThrows/RedundantThrowsDeclaration.java @@ -19,10 +19,10 @@ import com.intellij.java.analysis.impl.codeInsight.daemon.impl.analysis.JavaHighlightUtil; import com.intellij.java.impl.codeInspection.DeleteThrowsFix; import com.intellij.java.language.impl.codeInsight.ExceptionUtil; -import com.intellij.java.language.impl.codeInsight.daemon.JavaErrorBundle; import com.intellij.java.language.psi.*; +import consulo.annotation.access.RequiredReadAction; import consulo.annotation.component.ExtensionImpl; -import consulo.language.editor.inspection.LocalQuickFix; +import consulo.java.language.impl.localize.JavaErrorLocalize; import consulo.language.editor.inspection.ProblemDescriptor; import consulo.language.editor.inspection.ProblemHighlightType; import consulo.language.editor.inspection.localize.InspectionLocalize; @@ -32,7 +32,6 @@ import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; -import org.jetbrains.annotations.NonNls; import java.util.Collection; import java.util.HashSet; @@ -56,15 +55,14 @@ public LocalizeValue getDisplayName() { return InspectionLocalize.redundantThrowsDeclaration(); } - @Override @Nonnull - @NonNls + @Override public String getShortName() { return "RedundantThrowsDeclaration"; } - @Override @Nullable + @Override public ProblemDescriptor[] checkFile( @Nonnull PsiFile file, @Nonnull final InspectionManager manager, @@ -74,30 +72,29 @@ public ProblemDescriptor[] checkFile( final Set problems = new HashSet<>(); file.accept(new JavaRecursiveElementWalkingVisitor() { @Override + @RequiredReadAction public void visitReferenceElement(@Nonnull PsiJavaCodeReferenceElement reference) { - final ProblemDescriptor descriptor = checkExceptionsNeverThrown(reference, manager, isOnTheFly); + ProblemDescriptor descriptor = checkExceptionsNeverThrown(reference, manager, isOnTheFly); if (descriptor != null) { problems.add(descriptor); } } - }); return problems.isEmpty() ? null : problems.toArray(new ProblemDescriptor[problems.size()]); } + @RequiredReadAction private static ProblemDescriptor checkExceptionsNeverThrown( PsiJavaCodeReferenceElement referenceElement, InspectionManager inspectionManager, boolean onTheFly ) { - if (!(referenceElement.getParent() instanceof PsiReferenceList)) { + if (!(referenceElement.getParent() instanceof PsiReferenceList referenceList)) { return null; } - PsiReferenceList referenceList = (PsiReferenceList) referenceElement.getParent(); - if (!(referenceList.getParent() instanceof PsiMethod)) { + if (!(referenceList.getParent() instanceof PsiMethod method)) { return null; } - PsiMethod method = (PsiMethod) referenceList.getParent(); if (referenceList != method.getThrowsList()) { return null; } @@ -117,13 +114,10 @@ private static ProblemDescriptor checkExceptionsNeverThrown( return null; } - PsiModifierList modifierList = method.getModifierList(); - if (!modifierList.hasModifierProperty(PsiModifier.PRIVATE) - && !modifierList.hasModifierProperty(PsiModifier.STATIC) - && !modifierList.hasModifierProperty(PsiModifier.FINAL) + if (!method.isPrivate() && !method.isStatic() && !method.isFinal() && !method.isConstructor() && !(containingClass instanceof PsiAnonymousClass) - && !containingClass.hasModifierProperty(PsiModifier.FINAL)) { + && !containingClass.isFinal()) { return null; } @@ -133,8 +127,8 @@ private static ProblemDescriptor checkExceptionsNeverThrown( // there may be field initializer throwing exception // that exception must be caught in the constructor PsiField[] fields = containingClass.getFields(); - for (final PsiField field : fields) { - if (field.hasModifierProperty(PsiModifier.STATIC)) { + for (PsiField field : fields) { + if (field.isStatic()) { continue; } PsiExpression initializer = field.getInitializer(); @@ -155,14 +149,11 @@ private static ProblemDescriptor checkExceptionsNeverThrown( return null; } - String description = JavaErrorBundle.message("exception.is.never.thrown", JavaHighlightUtil.formatType(exceptionType)); - LocalQuickFix quickFixes = new DeleteThrowsFix(method, exceptionType); - return inspectionManager.createProblemDescriptor( - referenceElement, - description, - quickFixes, - ProblemHighlightType.LIKE_UNUSED_SYMBOL, - onTheFly - ); + return inspectionManager.newProblemDescriptor(JavaErrorLocalize.exceptionIsNeverThrown(JavaHighlightUtil.formatType(exceptionType))) + .range(referenceElement) + .highlightType(ProblemHighlightType.LIKE_UNUSED_SYMBOL) + .onTheFly(onTheFly) + .withFix(new DeleteThrowsFix(method, exceptionType)) + .create(); } } diff --git a/plugin/src/main/java/com/intellij/java/impl/codeInspection/unusedParameters/UnusedParametersInspection.java b/plugin/src/main/java/com/intellij/java/impl/codeInspection/unusedParameters/UnusedParametersInspection.java index b7c6d157d..ee9c53518 100644 --- a/plugin/src/main/java/com/intellij/java/impl/codeInspection/unusedParameters/UnusedParametersInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/codeInspection/unusedParameters/UnusedParametersInspection.java @@ -13,15 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -/* - * Created by IntelliJ IDEA. - * User: max - * Date: Dec 24, 2001 - * Time: 2:46:32 PM - * To change template for new class use - * Code Style | Class Templates options (Tools | IDE Options). - */ package com.intellij.java.impl.codeInspection.unusedParameters; import com.intellij.java.analysis.codeInspection.GlobalJavaInspectionContext; @@ -35,6 +26,7 @@ import com.intellij.java.impl.refactoring.changeSignature.ParameterInfoImpl; import com.intellij.java.indexing.search.searches.OverridingMethodsSearch; import com.intellij.java.language.psi.*; +import consulo.annotation.access.RequiredReadAction; import consulo.annotation.access.RequiredWriteAction; import consulo.annotation.component.ExtensionImpl; import consulo.ide.impl.idea.openapi.project.ProjectUtil; @@ -55,12 +47,12 @@ import consulo.language.psi.util.PsiTreeUtil; import consulo.localize.LocalizeValue; import consulo.project.Project; +import consulo.ui.annotation.RequiredUIAccess; import consulo.ui.ex.awt.JBUI; import consulo.ui.ex.awtUnsafe.TargetAWT; import consulo.util.lang.Comparing; import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; -import org.jetbrains.annotations.NonNls; import javax.swing.*; import java.awt.*; @@ -68,20 +60,24 @@ import java.util.Collection; import java.util.List; +/** + * @author max + * @since 2001-12-24 + */ @ExtensionImpl public class UnusedParametersInspection extends GlobalJavaBatchInspectionTool implements OldStyleInspection { - @NonNls public static final String SHORT_NAME = "UnusedParameters"; - @Override @Nullable + @Override + @RequiredReadAction public CommonProblemDescriptor[] checkElement( - @Nonnull final RefEntity refEntity, - @Nonnull final AnalysisScope scope, - @Nonnull final InspectionManager manager, - @Nonnull final GlobalInspectionContext globalContext, - @Nonnull final ProblemDescriptionsProcessor processor, - Object state + @Nonnull RefEntity refEntity, + @Nonnull AnalysisScope scope, + @Nonnull InspectionManager manager, + @Nonnull GlobalInspectionContext globalContext, + @Nonnull ProblemDescriptionsProcessor processor, + @Nonnull Object state ) { if (refEntity instanceof RefMethod refMethod) { if (refMethod.isSyntheticJSP() @@ -92,31 +88,31 @@ public CommonProblemDescriptor[] checkElement( return null; } - final List unusedParameters = getUnusedParameters(refMethod); + List unusedParameters = getUnusedParameters(refMethod); if (unusedParameters.isEmpty() || refMethod.isEntry()) { return null; } - final PsiModifierListOwner element = refMethod.getElement(); + PsiModifierListOwner element = refMethod.getElement(); if (element != null && EntryPointsManager.getInstance(manager.getProject()).isEntryPoint(element)) { return null; } - final List result = new ArrayList<>(); + List result = new ArrayList<>(); for (RefParameter refParameter : unusedParameters) { - final PsiIdentifier psiIdentifier = refParameter.getElement().getNameIdentifier(); + PsiIdentifier psiIdentifier = refParameter.getElement().getNameIdentifier(); if (psiIdentifier != null) { result.add( - manager.createProblemDescriptor( - psiIdentifier, - refMethod.isAbstract() - ? InspectionLocalize.inspectionUnusedParameterComposer().get() - : InspectionLocalize.inspectionUnusedParameterComposer1().get(), - new AcceptSuggested(globalContext.getRefManager(), processor, refParameter.toString()), - ProblemHighlightType.LIKE_UNUSED_SYMBOL, - false - ) + manager.newProblemDescriptor( + refMethod.isAbstract() + ? InspectionLocalize.inspectionUnusedParameterComposer() + : InspectionLocalize.inspectionUnusedParameterComposer1() + ) + .range(psiIdentifier) + .highlightType(ProblemHighlightType.LIKE_UNUSED_SYMBOL) + .withFix(new AcceptSuggested(globalContext.getRefManager(), processor, refParameter.toString())) + .create() ); } } @@ -127,11 +123,11 @@ public CommonProblemDescriptor[] checkElement( @Override protected boolean queryExternalUsagesRequests( - @Nonnull final RefManager manager, - @Nonnull final GlobalJavaInspectionContext globalContext, + @Nonnull RefManager manager, + @Nonnull GlobalJavaInspectionContext globalContext, @Nonnull final ProblemDescriptionsProcessor processor ) { - final Project project = manager.getProject(); + Project project = manager.getProject(); for (RefElement entryPoint : globalContext.getEntryPointsManager(manager).getEntryPoints()) { processor.ignoreElement(entryPoint); } @@ -141,41 +137,41 @@ protected boolean queryExternalUsagesRequests( manager.iterate(new RefJavaVisitor() { @Override public void visitElement(@Nonnull RefEntity refEntity) { - if (refEntity instanceof RefMethod refMethod) { - final PsiModifierListOwner element = refMethod.getElement(); - if (element instanceof PsiMethod psiMethod) { //implicit constructors are invisible - if (!refMethod.isStatic() && !refMethod.isConstructor() && !PsiModifier.PRIVATE.equals(refMethod.getAccessModifier())) { - final ArrayList unusedParameters = getUnusedParameters(refMethod); - if (unusedParameters.isEmpty()) { - return; - } - PsiMethod[] derived = OverridingMethodsSearch.search(psiMethod, true).toArray(PsiMethod.EMPTY_ARRAY); - for (final RefParameter refParameter : unusedParameters) { - if (refMethod.isAbstract() && derived.length == 0) { - refParameter.parameterReferenced(false); - processor.ignoreElement(refParameter); - } - else { - int idx = refParameter.getIndex(); - final boolean[] found = {false}; - for (int i = 0; i < derived.length && !found[0]; i++) { - if (!scope.contains(derived[i])) { - final PsiParameter[] parameters = derived[i].getParameterList().getParameters(); - if (parameters.length >= idx) { - continue; - } - PsiParameter psiParameter = parameters[idx]; - ReferencesSearch.search(psiParameter, helper.getUseScope(psiParameter), false) - .forEach(new PsiReferenceProcessorAdapter( - element1 -> { - refParameter.parameterReferenced(false); - processor.ignoreElement(refParameter); - found[0] = true; - return false; - } - )); - } + if (refEntity instanceof RefMethod refMethod + && refMethod.getElement() instanceof PsiMethod psiMethod + //implicit constructors are invisible + && !refMethod.isStatic() + && !refMethod.isConstructor() + && !PsiModifier.PRIVATE.equals(refMethod.getAccessModifier())) { + List unusedParameters = getUnusedParameters(refMethod); + if (unusedParameters.isEmpty()) { + return; + } + PsiMethod[] derived = OverridingMethodsSearch.search(psiMethod, true).toArray(PsiMethod.EMPTY_ARRAY); + for (RefParameter refParameter : unusedParameters) { + if (refMethod.isAbstract() && derived.length == 0) { + refParameter.parameterReferenced(false); + processor.ignoreElement(refParameter); + } + else { + int idx = refParameter.getIndex(); + boolean[] found = {false}; + for (int i = 0; i < derived.length && !found[0]; i++) { + if (!scope.contains(derived[i])) { + PsiParameter[] parameters = derived[i].getParameterList().getParameters(); + if (parameters.length >= idx) { + continue; } + PsiParameter psiParameter = parameters[idx]; + ReferencesSearch.search(psiParameter, helper.getUseScope(psiParameter), false) + .forEach(new PsiReferenceProcessorAdapter( + element1 -> { + refParameter.parameterReferenced(false); + processor.ignoreElement(refParameter); + found[0] = true; + return false; + } + )); } } } @@ -186,30 +182,30 @@ public void visitElement(@Nonnull RefEntity refEntity) { return false; } - @Override @Nullable - public String getHint(@Nonnull final QuickFix fix) { + @Override + public String getHint(@Nonnull QuickFix fix) { return ((AcceptSuggested) fix).getHint(); } - @Override @Nullable - public QuickFix getQuickFix(final String hint) { + @Override + public QuickFix getQuickFix(String hint) { return new AcceptSuggested(null, null, hint); } @Override - public void compose(@Nonnull final StringBuffer buf, @Nonnull final RefEntity refEntity, @Nonnull final HTMLComposer composer) { + public void compose(@Nonnull StringBuffer buf, @Nonnull RefEntity refEntity, @Nonnull HTMLComposer composer) { if (refEntity instanceof RefMethod refMethod) { - final HTMLJavaHTMLComposer javaComposer = composer.getExtension(HTMLJavaHTMLComposer.COMPOSER); + HTMLJavaHTMLComposer javaComposer = composer.getExtension(HTMLJavaHTMLComposer.COMPOSER); javaComposer.appendDerivedMethods(buf, refMethod); javaComposer.appendSuperMethods(buf, refMethod); } } - public static ArrayList getUnusedParameters(RefMethod refMethod) { + public static List getUnusedParameters(RefMethod refMethod) { boolean checkDeep = !refMethod.isStatic() && !refMethod.isConstructor(); - ArrayList res = new ArrayList<>(); + List res = new ArrayList<>(); RefParameter[] methodParameters = refMethod.getParameters(); RefParameter[] result = new RefParameter[methodParameters.length]; System.arraycopy(methodParameters, 0, result, 0, methodParameters.length); @@ -226,10 +222,10 @@ public static ArrayList getUnusedParameters(RefMethod refMethod) { } private static void clearUsedParameters(@Nonnull RefMethod refMethod, RefParameter[] params, boolean checkDeep) { - RefParameter[] methodParms = refMethod.getParameters(); + RefParameter[] methodParams = refMethod.getParameters(); - for (int i = 0; i < methodParms.length; i++) { - if (methodParms[i].isUsedForReading()) { + for (int i = 0; i < methodParams.length; i++) { + if (methodParams[i].isUsedForReading()) { params[i] = null; } } @@ -261,7 +257,7 @@ public String getShortName() { @Override public JComponent createOptionsPanel() { - final JPanel panel = new JPanel(new GridBagLayout()); + JPanel panel = new JPanel(new GridBagLayout()); Project project = ProjectUtil.guessCurrentProject(panel); panel.add( TargetAWT.to(EntryPointsManager.getInstance(project).createConfigureAnnotationsBtn()), @@ -278,7 +274,7 @@ private static class AcceptSuggested implements LocalQuickFix { private final String myHint; private final ProblemDescriptionsProcessor myProcessor; - public AcceptSuggested(final RefManager manager, final ProblemDescriptionsProcessor processor, final String hint) { + public AcceptSuggested(RefManager manager, ProblemDescriptionsProcessor processor, String hint) { myManager = manager; myProcessor = processor; myHint = hint; @@ -300,17 +296,17 @@ public void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor descri if (!FileModificationService.getInstance().preparePsiElementForWrite(descriptor.getPsiElement())) { return; } - final PsiMethod psiMethod = PsiTreeUtil.getParentOfType(descriptor.getPsiElement(), PsiMethod.class); + PsiMethod psiMethod = PsiTreeUtil.getParentOfType(descriptor.getPsiElement(), PsiMethod.class); if (psiMethod != null) { - final ArrayList psiParameters = new ArrayList(); - final RefElement refMethod = myManager != null ? myManager.getReference(psiMethod) : null; + List psiParameters = new ArrayList<>(); + RefElement refMethod = myManager != null ? myManager.getReference(psiMethod) : null; if (refMethod != null) { - for (final RefParameter refParameter : getUnusedParameters((RefMethod) refMethod)) { + for (RefParameter refParameter : getUnusedParameters((RefMethod) refMethod)) { psiParameters.add(refParameter.getElement()); } } else { - final PsiParameter[] parameters = psiMethod.getParameterList().getParameters(); + PsiParameter[] parameters = psiMethod.getParameterList().getParameters(); for (PsiParameter parameter : parameters) { if (Comparing.strEqual(parameter.getName(), myHint)) { psiParameters.add(parameter); @@ -318,8 +314,8 @@ public void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor descri } } } - final PsiModificationTracker tracker = psiMethod.getManager().getModificationTracker(); - final long startModificationCount = tracker.getModificationCount(); + PsiModificationTracker tracker = psiMethod.getManager().getModificationTracker(); + long startModificationCount = tracker.getModificationCount(); removeUnusedParameterViaChangeSignature(psiMethod, psiParameters); if (refMethod != null && startModificationCount != tracker.getModificationCount()) { @@ -328,8 +324,9 @@ public void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor descri } } - private static void removeUnusedParameterViaChangeSignature(final PsiMethod psiMethod, final Collection parametersToDelete) { - ArrayList newParameters = new ArrayList<>(); + @RequiredUIAccess + private static void removeUnusedParameterViaChangeSignature(PsiMethod psiMethod, Collection parametersToDelete) { + List newParameters = new ArrayList<>(); PsiParameter[] oldParameters = psiMethod.getParameterList().getParameters(); for (int i = 0; i < oldParameters.length; i++) { PsiParameter oldParameter = oldParameters[i]; @@ -341,7 +338,8 @@ private static void removeUnusedParameterViaChangeSignature(final PsiMethod psiM ParameterInfoImpl[] parameterInfos = newParameters.toArray(new ParameterInfoImpl[newParameters.size()]); ChangeSignatureProcessor csp = new ChangeSignatureProcessor(psiMethod.getProject(), psiMethod, false, null, psiMethod.getName(), - psiMethod.getReturnType(), parameterInfos); + psiMethod.getReturnType(), parameterInfos + ); csp.run(); } diff --git a/plugin/src/main/java/com/intellij/java/impl/codeInspection/unusedReturnValue/UnusedReturnValue.java b/plugin/src/main/java/com/intellij/java/impl/codeInspection/unusedReturnValue/UnusedReturnValue.java index 9dbd38756..7056999cf 100644 --- a/plugin/src/main/java/com/intellij/java/impl/codeInspection/unusedReturnValue/UnusedReturnValue.java +++ b/plugin/src/main/java/com/intellij/java/impl/codeInspection/unusedReturnValue/UnusedReturnValue.java @@ -24,6 +24,7 @@ import com.intellij.java.indexing.search.searches.OverridingMethodsSearch; import com.intellij.java.language.psi.*; import com.intellij.java.language.psi.util.PropertyUtil; +import consulo.annotation.access.RequiredReadAction; import consulo.annotation.access.RequiredWriteAction; import consulo.annotation.component.ExtensionImpl; import consulo.deadCodeNotWorking.impl.SingleCheckboxOptionsPanel; @@ -56,15 +57,16 @@ public class UnusedReturnValue extends GlobalJavaInspectionTool implements OldSt public boolean IGNORE_BUILDER_PATTERN = false; - @Override @Nullable + @Override + @RequiredReadAction public CommonProblemDescriptor[] checkElement( - RefEntity refEntity, - AnalysisScope scope, - InspectionManager manager, - GlobalInspectionContext globalContext, - ProblemDescriptionsProcessor processor, - Object state + @Nonnull RefEntity refEntity, + @Nonnull AnalysisScope scope, + @Nonnull InspectionManager manager, + @Nonnull GlobalInspectionContext globalContext, + @Nonnull ProblemDescriptionsProcessor processor, + @Nonnull Object state ) { if (refEntity instanceof RefMethod refMethod) { if (refMethod.isConstructor() @@ -74,23 +76,20 @@ public CommonProblemDescriptor[] checkElement( } if (!refMethod.isReturnValueUsed()) { - final PsiMethod psiMethod = (PsiMethod) refMethod.getElement(); + PsiMethod psiMethod = (PsiMethod) refMethod.getElement(); if (IGNORE_BUILDER_PATTERN && PropertyUtil.isSimplePropertySetter(psiMethod)) { return null; } - final boolean isNative = psiMethod.hasModifierProperty(PsiModifier.NATIVE); + boolean isNative = psiMethod.hasModifierProperty(PsiModifier.NATIVE); if (refMethod.isExternalOverride() && !isNative) { return null; } return new ProblemDescriptor[]{ - manager.createProblemDescriptor( - psiMethod.getNavigationElement(), - InspectionLocalize.inspectionUnusedReturnValueProblemDescriptor().get(), - !isNative ? getFix(processor) : null, - ProblemHighlightType.GENERIC_ERROR_OR_WARNING, - false - ) + manager.newProblemDescriptor(InspectionLocalize.inspectionUnusedReturnValueProblemDescriptor()) + .range(psiMethod.getNavigationElement()) + .withOptionalFix(!isNative ? getFix(processor) : null) + .create() }; } } @@ -105,7 +104,7 @@ public JComponent createOptionsPanel() { @Override protected boolean queryExternalUsagesRequests( - final RefManager manager, + RefManager manager, final GlobalJavaInspectionContext globalContext, final ProblemDescriptionsProcessor processor, Object state @@ -116,7 +115,7 @@ public void visitElement(@Nonnull RefEntity refEntity) { if (refEntity instanceof RefElement && processor.getDescriptions(refEntity) != null) { refEntity.accept(new RefJavaVisitor() { @Override - public void visitMethod(@Nonnull final RefMethod refMethod) { + public void visitMethod(@Nonnull RefMethod refMethod) { globalContext.enqueueMethodUsagesProcessor(refMethod, psiReference -> { processor.ignoreElement(refMethod); return false; @@ -148,7 +147,7 @@ public String getShortName() { return "UnusedReturnValue"; } - private LocalQuickFix getFix(final ProblemDescriptionsProcessor processor) { + private LocalQuickFix getFix(ProblemDescriptionsProcessor processor) { if (myQuickFix == null) { myQuickFix = new MakeVoidQuickFix(processor); } @@ -165,7 +164,7 @@ private static class MakeVoidQuickFix implements LocalQuickFix { private final ProblemDescriptionsProcessor myProcessor; private static final Logger LOG = Logger.getInstance(MakeVoidQuickFix.class); - public MakeVoidQuickFix(final ProblemDescriptionsProcessor processor) { + public MakeVoidQuickFix(ProblemDescriptionsProcessor processor) { myProcessor = processor; } @@ -194,19 +193,20 @@ public void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor descri makeMethodHierarchyVoid(project, psiMethod); } + @RequiredWriteAction private static void makeMethodHierarchyVoid(Project project, @Nonnull PsiMethod psiMethod) { replaceReturnStatements(psiMethod); - for (final PsiMethod oMethod : OverridingMethodsSearch.search(psiMethod)) { + for (PsiMethod oMethod : OverridingMethodsSearch.search(psiMethod)) { replaceReturnStatements(oMethod); } - final PsiParameter[] params = psiMethod.getParameterList().getParameters(); - final ParameterInfoImpl[] infos = new ParameterInfoImpl[params.length]; + PsiParameter[] params = psiMethod.getParameterList().getParameters(); + ParameterInfoImpl[] infos = new ParameterInfoImpl[params.length]; for (int i = 0; i < params.length; i++) { PsiParameter param = params[i]; infos[i] = new ParameterInfoImpl(i, param.getName(), param.getType()); } - final ChangeSignatureProcessor csp = new ChangeSignatureProcessor( + ChangeSignatureProcessor csp = new ChangeSignatureProcessor( project, psiMethod, false, null, psiMethod.getName(), @@ -217,22 +217,23 @@ private static void makeMethodHierarchyVoid(Project project, @Nonnull PsiMethod csp.run(); } - private static void replaceReturnStatements(@Nonnull final PsiMethod method) { - final PsiCodeBlock body = method.getBody(); + @RequiredWriteAction + private static void replaceReturnStatements(@Nonnull PsiMethod method) { + PsiCodeBlock body = method.getBody(); if (body != null) { final List returnStatements = new ArrayList<>(); body.accept(new JavaRecursiveElementWalkingVisitor() { @Override - public void visitReturnStatement(@Nonnull final PsiReturnStatement statement) { + public void visitReturnStatement(@Nonnull PsiReturnStatement statement) { super.visitReturnStatement(statement); returnStatements.add(statement); } }); - final PsiStatement[] psiStatements = body.getStatements(); - final PsiStatement lastStatement = psiStatements[psiStatements.length - 1]; + PsiStatement[] psiStatements = body.getStatements(); + PsiStatement lastStatement = psiStatements[psiStatements.length - 1]; for (PsiReturnStatement returnStatement : returnStatements) { try { - final PsiExpression expression = returnStatement.getReturnValue(); + PsiExpression expression = returnStatement.getReturnValue(); if (expression instanceof PsiLiteralExpression || expression instanceof PsiThisExpression) { //avoid side effects if (returnStatement == lastStatement) { returnStatement.delete(); diff --git a/plugin/src/main/java/com/intellij/java/impl/codeInspection/visibility/VisibilityInspection.java b/plugin/src/main/java/com/intellij/java/impl/codeInspection/visibility/VisibilityInspection.java index 00501e3f6..c3f3ffbe9 100644 --- a/plugin/src/main/java/com/intellij/java/impl/codeInspection/visibility/VisibilityInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/codeInspection/visibility/VisibilityInspection.java @@ -13,15 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -/* - * Created by IntelliJ IDEA. - * User: max - * Date: Dec 21, 2001 - * Time: 8:46:41 PM - * To change template for new class use - * Code Style | Class Templates options (Tools | IDE Options). - */ package com.intellij.java.impl.codeInspection.visibility; import com.intellij.java.analysis.codeInspection.GlobalJavaInspectionContext; @@ -62,6 +53,10 @@ import java.awt.*; import java.util.List; +/** + * @author max + * @since 2001-12-21 + */ @ExtensionImpl public class VisibilityInspection extends GlobalJavaInspectionTool implements OldStyleInspection { private class OptionsPanel extends JPanel { @@ -201,17 +196,16 @@ public CommonProblemDescriptor[] checkElement( PsiElement element = refElement.getElement(); PsiElement nameIdentifier = element != null ? IdentifierUtil.getNameIdentifier(element) : null; if (nameIdentifier != null) { + LocalizeValue descriptionTemplate = access.equals(PsiModifier.PRIVATE) + ? InspectionLocalize.inspectionVisibilityComposeSuggestion("private") + : access.equals(PsiModifier.PACKAGE_LOCAL) + ? InspectionLocalize.inspectionVisibilityComposeSuggestion("package local") + : InspectionLocalize.inspectionVisibilityComposeSuggestion("protected"); return new ProblemDescriptor[]{ - manager.createProblemDescriptor( - nameIdentifier, - access.equals(PsiModifier.PRIVATE) - ? InspectionLocalize.inspectionVisibilityComposeSuggestion("private").get() - : access.equals(PsiModifier.PACKAGE_LOCAL) - ? InspectionLocalize.inspectionVisibilityComposeSuggestion("package local").get() - : InspectionLocalize.inspectionVisibilityComposeSuggestion("protected").get(), - new AcceptSuggestedAccess(globalContext.getRefManager(), access), - ProblemHighlightType.GENERIC_ERROR_OR_WARNING, false - ) + manager.newProblemDescriptor(descriptionTemplate) + .range(nameIdentifier) + .withFix(new AcceptSuggestedAccess(globalContext.getRefManager(), access)) + .create() }; } } @@ -292,8 +286,8 @@ private boolean isAccessible(RefJavaElement to, @PsiModifier.ModifierConstant St } if (to instanceof RefMethod refMethod) { - if (refMethod.isAbstract() && (refMethod.getDerivedMethods() - .isEmpty() || refMethod.getAccessModifier() == PsiModifier.PRIVATE)) { + if (refMethod.isAbstract() + && (refMethod.getDerivedMethods().isEmpty() || refMethod.getAccessModifier() == PsiModifier.PRIVATE)) { return false; } @@ -320,7 +314,7 @@ private boolean isAccessible(RefJavaElement to, @PsiModifier.ModifierConstant St List children = refClass.getChildren(); if (children != null) { for (Object refElement : children) { - if (!isAccessible((RefJavaElement)refElement, accessModifier)) { + if (!isAccessible((RefJavaElement) refElement, accessModifier)) { return false; } } @@ -332,7 +326,7 @@ private boolean isAccessible(RefJavaElement to, @PsiModifier.ModifierConstant St } } - List classExporters = ((RefClassImpl)refClass).getClassExporters(); + List classExporters = ((RefClassImpl) refClass).getClassExporters(); if (classExporters != null) { for (RefJavaElement refExporter : classExporters) { if (getAccessLevel(accessModifier) < getAccessLevel(refExporter.getAccessModifier())) { @@ -564,15 +558,14 @@ private static void ignoreElement(@Nonnull ProblemDescriptionsProcessor processo } } - RefEntity owner = refElement.getOwner(); - if (owner instanceof RefElement) { - processor.ignoreElement(owner); + if (refElement.getOwner() instanceof RefElement ownerRef) { + processor.ignoreElement(ownerRef); } } @Override public void compose(@Nonnull StringBuffer buf, @Nonnull RefEntity refEntity, HTMLComposer composer) { - composer.appendElementInReferences(buf, (RefElement)refEntity); + composer.appendElementInReferences(buf, (RefElement) refEntity); } @Override @@ -584,7 +577,7 @@ public QuickFix getQuickFix(String hint) { @Override @Nullable public String getHint(@Nonnull QuickFix fix) { - return ((AcceptSuggestedAccess)fix).getHint(); + return ((AcceptSuggestedAccess) fix).getHint(); } private static class AcceptSuggestedAccess implements LocalQuickFix { diff --git a/plugin/src/main/java/com/intellij/java/impl/codeInspection/wrongPackageStatement/WrongPackageStatementInspection.java b/plugin/src/main/java/com/intellij/java/impl/codeInspection/wrongPackageStatement/WrongPackageStatementInspection.java index 1f7ce11d9..c83574b6f 100644 --- a/plugin/src/main/java/com/intellij/java/impl/codeInspection/wrongPackageStatement/WrongPackageStatementInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/codeInspection/wrongPackageStatement/WrongPackageStatementInspection.java @@ -17,13 +17,12 @@ import com.intellij.java.analysis.impl.codeInspection.BaseJavaLocalInspectionTool; import com.intellij.java.impl.codeInspection.MoveToPackageFix; -import com.intellij.java.language.impl.codeInsight.daemon.JavaErrorBundle; import com.intellij.java.language.psi.*; import consulo.annotation.access.RequiredReadAction; import consulo.annotation.component.ExtensionImpl; +import consulo.java.language.impl.localize.JavaErrorLocalize; import consulo.language.editor.inspection.LocalQuickFix; import consulo.language.editor.inspection.ProblemDescriptor; -import consulo.language.editor.inspection.ProblemHighlightType; import consulo.language.editor.inspection.localize.InspectionLocalize; import consulo.language.editor.inspection.scheme.InspectionManager; import consulo.language.editor.rawHighlight.HighlightDisplayLevel; @@ -33,99 +32,95 @@ import consulo.util.lang.Comparing; import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; -import org.jetbrains.annotations.NonNls; import java.util.ArrayList; import java.util.List; /** - * User: anna - * Date: 14-Nov-2005 + * @author anna + * @since 2005-11-14 */ @ExtensionImpl public class WrongPackageStatementInspection extends BaseJavaLocalInspectionTool { - @Override - @Nullable - @RequiredReadAction - public ProblemDescriptor[] checkFile(@Nonnull PsiFile file, @Nonnull InspectionManager manager, boolean isOnTheFly, Object state) { - if (file instanceof PsiJavaFile javaFile) { - PsiDirectory directory = javaFile.getContainingDirectory(); - if (directory == null) return null; - PsiJavaPackage dirPackage = JavaDirectoryService.getInstance().getPackage(directory); - if (dirPackage == null) return null; - PsiPackageStatement packageStatement = javaFile.getPackageStatement(); + @Override + @Nullable + @RequiredReadAction + public ProblemDescriptor[] checkFile(@Nonnull PsiFile file, @Nonnull InspectionManager manager, boolean isOnTheFly, Object state) { + if (file instanceof PsiJavaFile javaFile) { + PsiDirectory directory = javaFile.getContainingDirectory(); + if (directory == null) { + return null; + } + PsiJavaPackage dirPackage = JavaDirectoryService.getInstance().getPackage(directory); + if (dirPackage == null) { + return null; + } + PsiPackageStatement packageStatement = javaFile.getPackageStatement(); - // highlight the first class in the file only - PsiClass[] classes = javaFile.getClasses(); - if (classes.length == 0 && packageStatement == null || classes.length == 1 && classes[0] instanceof PsiSyntheticClass) return null; + // highlight the first class in the file only + PsiClass[] classes = javaFile.getClasses(); + if (classes.length == 0 && packageStatement == null || classes.length == 1 && classes[0] instanceof PsiSyntheticClass) { + return null; + } - String packageName = dirPackage.getQualifiedName(); - if (!Comparing.strEqual(packageName, "", true) && packageStatement == null) { - String description = JavaErrorBundle.message("missing.package.statement", packageName); + String packageName = dirPackage.getQualifiedName(); + if (!Comparing.strEqual(packageName, "", true) && packageStatement == null) { - return new ProblemDescriptor[]{ - manager.createProblemDescriptor( - classes[0].getNameIdentifier(), - description, - new AdjustPackageNameFix(packageName), - ProblemHighlightType.GENERIC_ERROR_OR_WARNING, - isOnTheFly - ) - }; - } - if (packageStatement != null) { - final PsiJavaCodeReferenceElement packageReference = packageStatement.getPackageReference(); - PsiJavaPackage classPackage = (PsiJavaPackage)packageReference.resolve(); - List availableFixes = new ArrayList<>(); - if (classPackage == null || !Comparing.equal(dirPackage.getQualifiedName(), packageReference.getQualifiedName(), true)) { - availableFixes.add(new AdjustPackageNameFix(packageName)); - MoveToPackageFix moveToPackageFix = - new MoveToPackageFix(classPackage != null ? classPackage.getQualifiedName() : packageReference.getQualifiedName()); - if (moveToPackageFix.isAvailable(file)) { - availableFixes.add(moveToPackageFix); - } + return new ProblemDescriptor[]{ + manager.newProblemDescriptor(JavaErrorLocalize.missingPackageStatement(packageName)) + .range(classes[0].getNameIdentifier()) + .onTheFly(isOnTheFly) + .withFix(new AdjustPackageNameFix(packageName)) + .create() + }; + } + if (packageStatement != null) { + PsiJavaCodeReferenceElement packageReference = packageStatement.getPackageReference(); + PsiJavaPackage classPackage = (PsiJavaPackage) packageReference.resolve(); + List availableFixes = new ArrayList<>(); + if (classPackage == null || !Comparing.equal(dirPackage.getQualifiedName(), packageReference.getQualifiedName(), true)) { + availableFixes.add(new AdjustPackageNameFix(packageName)); + MoveToPackageFix moveToPackageFix = + new MoveToPackageFix(classPackage != null ? classPackage.getQualifiedName() : packageReference.getQualifiedName()); + if (moveToPackageFix.isAvailable(file)) { + availableFixes.add(moveToPackageFix); + } + } + if (!availableFixes.isEmpty()) { + ProblemDescriptor descriptor = manager.newProblemDescriptor( + JavaErrorLocalize.packageNameFilePathMismatch(packageReference.getQualifiedName(), dirPackage.getQualifiedName()) + ) + .range(packageStatement.getPackageReference()) + .onTheFly(isOnTheFly) + .withFixes(availableFixes) + .create(); + return new ProblemDescriptor[]{descriptor}; + } + } } - if (!availableFixes.isEmpty()){ - String description = JavaErrorBundle.message("package.name.file.path.mismatch", - packageReference.getQualifiedName(), - dirPackage.getQualifiedName()); - LocalQuickFix[] fixes = availableFixes.toArray(new LocalQuickFix[availableFixes.size()]); - ProblemDescriptor descriptor = manager.createProblemDescriptor( - packageStatement.getPackageReference(), - description, - isOnTheFly, - fixes, - ProblemHighlightType.GENERIC_ERROR_OR_WARNING - ); - return new ProblemDescriptor[]{descriptor}; - - } - } + return null; } - return null; - } - @Override - @Nonnull - public HighlightDisplayLevel getDefaultLevel() { - return HighlightDisplayLevel.ERROR; - } + @Override + @Nonnull + public HighlightDisplayLevel getDefaultLevel() { + return HighlightDisplayLevel.ERROR; + } - @Override - @Nonnull - public LocalizeValue getDisplayName() { - return InspectionLocalize.wrongPackageStatement(); - } + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionLocalize.wrongPackageStatement(); + } - @Override - @Nonnull - @NonNls - public String getShortName() { - return "WrongPackageStatement"; - } + @Nonnull + @Override + public String getShortName() { + return "WrongPackageStatement"; + } - @Override - public boolean isEnabledByDefault() { - return true; - } + @Override + public boolean isEnabledByDefault() { + return true; + } }