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 24b4d5b5e3..bbd3d7671a 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 @@ -40,6 +40,7 @@ import consulo.language.psi.PsiElement; import consulo.language.psi.PsiFile; import consulo.language.psi.util.PsiTreeUtil; +import consulo.localize.LocalizeValue; import consulo.logging.Logger; import consulo.project.Project; import consulo.util.collection.BidirectionalMap; @@ -57,333 +58,362 @@ */ @ExtensionImpl public class RedundantSuppressInspection extends GlobalInspectionTool implements OldStyleInspection { - private BidirectionalMap myQuickFixes = null; - private static final Logger LOG = Logger.getInstance(RedundantSuppressInspection.class); + private BidirectionalMap myQuickFixes = null; + private static final Logger LOG = Logger.getInstance(RedundantSuppressInspection.class); - public boolean IGNORE_ALL = false; + public boolean IGNORE_ALL = false; - @Nonnull - @Override - public HighlightDisplayLevel getDefaultLevel() { - return HighlightDisplayLevel.WARNING; - } + @Nonnull + @Override + public HighlightDisplayLevel getDefaultLevel() { + return HighlightDisplayLevel.WARNING; + } - @Override - public boolean isEnabledByDefault() { - return false; - } + @Override + public boolean isEnabledByDefault() { + return false; + } - @Nullable - @Override - public Language getLanguage() { - return JavaLanguage.INSTANCE; - } + @Nullable + @Override + public Language getLanguage() { + return JavaLanguage.INSTANCE; + } - @Override - @Nonnull - public String getGroupDisplayName() { - return InspectionLocalize.groupNamesDeclarationRedundancy().get(); - } + @Nonnull + @Override + public LocalizeValue getGroupDisplayName() { + return InspectionLocalize.groupNamesDeclarationRedundancy(); + } - @Override - @Nonnull - public String getDisplayName() { - return InspectionLocalize.inspectionRedundantSuppressionName().get(); - } + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionLocalize.inspectionRedundantSuppressionName(); + } - @Override - @Nonnull - @NonNls - public String getShortName() { - return "RedundantSuppression"; - } + @Override + @Nonnull + @NonNls + public String getShortName() { + return "RedundantSuppression"; + } - @Override - public JComponent createOptionsPanel() { - return new SingleCheckboxOptionsPanel("Ignore @SuppressWarning(\"ALL\")", this, "IGNORE_ALL"); - } + @Override + public JComponent createOptionsPanel() { + return new SingleCheckboxOptionsPanel("Ignore @SuppressWarning(\"ALL\")", this, "IGNORE_ALL"); + } - @Override - public void runInspection( - @Nonnull final AnalysisScope scope, - @Nonnull final InspectionManager manager, - @Nonnull final GlobalInspectionContext globalContext, - @Nonnull final ProblemDescriptionsProcessor problemDescriptionsProcessor, - @Nonnull Object state - ) { - globalContext.getRefManager().iterate(new RefJavaVisitor() { - @RequiredReadAction - @Override - public void visitClass(@Nonnull RefClass refClass) { - if (!globalContext.shouldCheck(refClass, RedundantSuppressInspection.this)) return; - CommonProblemDescriptor[] descriptors = checkElement(refClass, manager, globalContext.getProject(), state); - 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); - if (refElement != null) { - problemDescriptionsProcessor.addProblemElement(refElement, descriptor); - continue; - } + @Override + public void runInspection( + @Nonnull final AnalysisScope scope, + @Nonnull final InspectionManager manager, + @Nonnull final GlobalInspectionContext globalContext, + @Nonnull final ProblemDescriptionsProcessor problemDescriptionsProcessor, + @Nonnull Object state + ) { + globalContext.getRefManager().iterate(new RefJavaVisitor() { + @RequiredReadAction + @Override + public void visitClass(@Nonnull RefClass refClass) { + if (!globalContext.shouldCheck(refClass, RedundantSuppressInspection.this)) { + return; + } + CommonProblemDescriptor[] descriptors = checkElement(refClass, manager, globalContext.getProject(), state); + 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); + if (refElement != null) { + problemDescriptionsProcessor.addProblemElement(refElement, descriptor); + continue; + } + } + problemDescriptionsProcessor.addProblemElement(refClass, descriptor); + } + } } - problemDescriptionsProcessor.addProblemElement(refClass, descriptor); - } - } - } - }); - } - - @Nullable - @RequiredReadAction - private CommonProblemDescriptor[] checkElement( - @Nonnull RefClass refEntity, - @Nonnull InspectionManager manager, - @Nonnull Project project, - Object state - ) { - final PsiClass psiClass = refEntity.getElement(); - if (psiClass == null) return null; - return checkElement(psiClass, manager, project, state); - } + }); + } - @RequiredReadAction - public CommonProblemDescriptor[] checkElement( - @Nonnull final PsiElement psiElement, - @Nonnull final InspectionManager manager, - @Nonnull Project project, - Object state - ) { - final Map> suppressedScopes = new HashMap<>(); - psiElement.accept(new JavaRecursiveElementWalkingVisitor() { - @Override - public void visitModifierList(@Nonnull PsiModifierList list) { - super.visitModifierList(list); - final PsiElement parent = list.getParent(); - if (parent instanceof PsiModifierListOwner && !(parent instanceof PsiClass)) { - checkElement(parent); + @Nullable + @RequiredReadAction + private CommonProblemDescriptor[] checkElement( + @Nonnull RefClass refEntity, + @Nonnull InspectionManager manager, + @Nonnull Project project, + Object state + ) { + final PsiClass psiClass = refEntity.getElement(); + if (psiClass == null) { + return null; } - } + return checkElement(psiClass, manager, project, state); + } - @Override - public void visitComment(PsiComment comment) { - checkElement(comment); - } + @RequiredReadAction + public CommonProblemDescriptor[] checkElement( + @Nonnull final PsiElement psiElement, + @Nonnull final InspectionManager manager, + @Nonnull Project project, + Object state + ) { + final Map> suppressedScopes = new HashMap<>(); + psiElement.accept(new JavaRecursiveElementWalkingVisitor() { + @Override + public void visitModifierList(@Nonnull PsiModifierList list) { + super.visitModifierList(list); + final PsiElement parent = list.getParent(); + if (parent instanceof PsiModifierListOwner && !(parent instanceof PsiClass)) { + checkElement(parent); + } + } - @Override - public void visitClass(@Nonnull PsiClass aClass) { - if (aClass == psiElement) { - super.visitClass(aClass); - checkElement(aClass); - } - } + @Override + public void visitComment(PsiComment comment) { + checkElement(comment); + } - private void checkElement(final PsiElement owner) { - String idsString = JavaSuppressionUtil.getSuppressedInspectionIdsIn(owner); - if (idsString != null && !idsString.isEmpty()) { - List ids = StringUtil.split(idsString, ","); - if (IGNORE_ALL && (ids.contains(SuppressionUtil.ALL) || ids.contains(SuppressionUtil.ALL.toLowerCase()))) - return; - Collection suppressed = suppressedScopes.get(owner); - if (suppressed == null) { - suppressed = ids; - } else { - for (String id : ids) { - if (!suppressed.contains(id)) { - suppressed.add(id); - } + @Override + public void visitClass(@Nonnull PsiClass aClass) { + if (aClass == psiElement) { + super.visitClass(aClass); + checkElement(aClass); + } } - } - suppressedScopes.put(owner, suppressed); - } - } - }); - if (suppressedScopes.values().isEmpty()) return null; - // have to visit all file from scratch since inspections can be written in any perversive way including checkFile() overriding - Collection suppressedTools = new HashSet<>(); - InspectionToolWrapper[] toolWrappers = getInspectionTools(psiElement, manager); - for (Collection ids : suppressedScopes.values()) { - for (Iterator iterator = ids.iterator(); iterator.hasNext(); ) { - final String shortName = iterator.next().trim(); - for (InspectionToolWrapper toolWrapper : toolWrappers) { - if (toolWrapper instanceof LocalInspectionToolWrapper localInspectionToolWrapper - && localInspectionToolWrapper.getTool().getID().equals(shortName)) { - if (localInspectionToolWrapper.isUnfair()) { - iterator.remove(); - break; - } else { - suppressedTools.add(toolWrapper); + private void checkElement(final PsiElement owner) { + String idsString = JavaSuppressionUtil.getSuppressedInspectionIdsIn(owner); + if (idsString != null && !idsString.isEmpty()) { + List ids = StringUtil.split(idsString, ","); + if (IGNORE_ALL && (ids.contains(SuppressionUtil.ALL) || ids.contains(SuppressionUtil.ALL.toLowerCase()))) { + return; + } + Collection suppressed = suppressedScopes.get(owner); + if (suppressed == null) { + suppressed = ids; + } + else { + for (String id : ids) { + if (!suppressed.contains(id)) { + suppressed.add(id); + } + } + } + suppressedScopes.put(owner, suppressed); + } } - } else if (toolWrapper.getShortName().equals(shortName)) { - //ignore global unused as it won't be checked anyway - if (toolWrapper instanceof LocalInspectionToolWrapper || toolWrapper instanceof GlobalInspectionToolWrapper) { - suppressedTools.add(toolWrapper); - } else { - iterator.remove(); - break; + }); + + if (suppressedScopes.values().isEmpty()) { + return null; + } + // have to visit all file from scratch since inspections can be written in any perversive way including checkFile() overriding + Collection suppressedTools = new HashSet<>(); + InspectionToolWrapper[] toolWrappers = getInspectionTools(psiElement, manager); + for (Collection ids : suppressedScopes.values()) { + for (Iterator iterator = ids.iterator(); iterator.hasNext(); ) { + final String shortName = iterator.next().trim(); + for (InspectionToolWrapper toolWrapper : toolWrappers) { + if (toolWrapper instanceof LocalInspectionToolWrapper localInspectionToolWrapper + && localInspectionToolWrapper.getTool().getID().equals(shortName)) { + if (localInspectionToolWrapper.isUnfair()) { + iterator.remove(); + break; + } + else { + suppressedTools.add(toolWrapper); + } + } + else if (toolWrapper.getShortName().equals(shortName)) { + //ignore global unused as it won't be checked anyway + if (toolWrapper instanceof LocalInspectionToolWrapper || toolWrapper instanceof GlobalInspectionToolWrapper) { + suppressedTools.add(toolWrapper); + } + else { + iterator.remove(); + break; + } + } + } } - } } - } - } - PsiFile file = psiElement.getContainingFile(); - final AnalysisScope scope = new AnalysisScope(file); + PsiFile file = psiElement.getContainingFile(); + final AnalysisScope scope = new AnalysisScope(file); - final GlobalInspectionContextBase globalContext = new GlobalInspectionContextBase(file.getProject()); - globalContext.setCurrentScope(scope); - final RefManagerImpl refManager = (RefManagerImpl) globalContext.getRefManager(); - refManager.inspectionReadActionStarted(); - final List result; - try { - result = new ArrayList<>(); - for (InspectionToolWrapper toolWrapper : suppressedTools) { - String toolId = toolWrapper instanceof LocalInspectionToolWrapper inspectionToolWrapper - ? inspectionToolWrapper.getTool().getID() : toolWrapper.getShortName(); - toolWrapper.initialize(globalContext); - final Collection descriptors; - if (toolWrapper instanceof LocalInspectionToolWrapper local) { - if (local.isUnfair()) continue; //cant't work with passes other than LocalInspectionPass - List results = manager.runLocalToolLocaly(local.getTool(), file, state); - descriptors = new ArrayList<>(results); - } else if (toolWrapper instanceof GlobalInspectionToolWrapper global) { - GlobalInspectionTool globalTool = global.getTool(); - if (globalTool.isGraphNeeded()) { - refManager.findAllDeclarations(); - } - descriptors = new ArrayList<>(); - globalContext.getRefManager().iterate(new RefVisitor() { - @Override - public void visitElement(@Nonnull RefEntity refEntity) { - CommonProblemDescriptor[] descriptors1 = global.getTool().checkElement( - refEntity, - scope, - manager, - globalContext, - new ProblemDescriptionsProcessor() { - @Nullable - @Override - public CommonProblemDescriptor[] getDescriptions(@Nonnull RefEntity refEntity) { - return new CommonProblemDescriptor[0]; - } + final GlobalInspectionContextBase globalContext = new GlobalInspectionContextBase(file.getProject()); + globalContext.setCurrentScope(scope); + final RefManagerImpl refManager = (RefManagerImpl) globalContext.getRefManager(); + refManager.inspectionReadActionStarted(); + final List result; + try { + result = new ArrayList<>(); + for (InspectionToolWrapper toolWrapper : suppressedTools) { + String toolId = toolWrapper instanceof LocalInspectionToolWrapper inspectionToolWrapper + ? inspectionToolWrapper.getTool().getID() : toolWrapper.getShortName(); + toolWrapper.initialize(globalContext); + final Collection descriptors; + if (toolWrapper instanceof LocalInspectionToolWrapper local) { + if (local.isUnfair()) { + continue; //cant't work with passes other than LocalInspectionPass + } + List results = manager.runLocalToolLocaly(local.getTool(), file, state); + descriptors = new ArrayList<>(results); + } + else if (toolWrapper instanceof GlobalInspectionToolWrapper global) { + GlobalInspectionTool globalTool = global.getTool(); + if (globalTool.isGraphNeeded()) { + refManager.findAllDeclarations(); + } + descriptors = new ArrayList<>(); + globalContext.getRefManager().iterate(new RefVisitor() { + @Override + public void visitElement(@Nonnull RefEntity refEntity) { + CommonProblemDescriptor[] descriptors1 = global.getTool().checkElement( + refEntity, + scope, + manager, + globalContext, + new ProblemDescriptionsProcessor() { + @Nullable + @Override + public CommonProblemDescriptor[] getDescriptions(@Nonnull RefEntity refEntity) { + return new CommonProblemDescriptor[0]; + } - @Override - public void ignoreElement(@Nonnull RefEntity refEntity) {} + @Override + public void ignoreElement(@Nonnull RefEntity refEntity) { + } - @Override - public void addProblemElement( - @Nullable RefEntity refEntity, - @Nonnull CommonProblemDescriptor... commonProblemDescriptors - ) { - int i = 0; - } + @Override + public void addProblemElement( + @Nullable RefEntity refEntity, + @Nonnull CommonProblemDescriptor... commonProblemDescriptors + ) { + int i = 0; + } - @Override - public RefEntity getElement(@Nonnull CommonProblemDescriptor descriptor) { - return null; - } + @Override + public RefEntity getElement(@Nonnull CommonProblemDescriptor descriptor) { + return null; + } + } + ); + if (descriptors1 != null) { + ContainerUtil.addAll(descriptors, descriptors1); + } + } + }); + } + else { + continue; + } + for (PsiElement suppressedScope : suppressedScopes.keySet()) { + Collection suppressedIds = suppressedScopes.get(suppressedScope); + if (!suppressedIds.contains(toolId)) { + continue; + } + for (CommonProblemDescriptor descriptor : descriptors) { + if (!(descriptor instanceof ProblemDescriptor)) { + continue; + } + PsiElement element = ((ProblemDescriptor) descriptor).getPsiElement(); + if (element == null) { + continue; + } + PsiElement annotation = JavaSuppressionUtil.getElementToolSuppressedIn(element, toolId); + if (annotation != null && PsiTreeUtil.isAncestor(suppressedScope, annotation, false) + || annotation == null && !PsiTreeUtil.isAncestor(suppressedScope, element, false)) { + suppressedIds.remove(toolId); + break; + } + } } - ); - if (descriptors1 != null) { - ContainerUtil.addAll(descriptors, descriptors1); - } } - }); - } else { - continue; - } - for (PsiElement suppressedScope : suppressedScopes.keySet()) { - Collection suppressedIds = suppressedScopes.get(suppressedScope); - if (!suppressedIds.contains(toolId)) continue; - for (CommonProblemDescriptor descriptor : descriptors) { - if (!(descriptor instanceof ProblemDescriptor)) continue; - PsiElement element = ((ProblemDescriptor) descriptor).getPsiElement(); - if (element == null) continue; - PsiElement annotation = JavaSuppressionUtil.getElementToolSuppressedIn(element, toolId); - if (annotation != null && PsiTreeUtil.isAncestor(suppressedScope, annotation, false) - || annotation == null && !PsiTreeUtil.isAncestor(suppressedScope, element, false)) { - suppressedIds.remove(toolId); - break; + for (PsiElement suppressedScope : suppressedScopes.keySet()) { + Collection suppressedIds = suppressedScopes.get(suppressedScope); + for (String toolId : suppressedIds) { + PsiMember psiMember; + String problemLine = null; + if (suppressedScope instanceof PsiMember suppressedMember) { + psiMember = suppressedMember; + } + else { + psiMember = PsiTreeUtil.getParentOfType(suppressedScope, PsiDocCommentOwner.class); + final 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 : ""); + QuickFix fix = myQuickFixes.get(key); + if (fix == null) { + fix = new RemoveSuppressWarningAction(toolId, problemLine); + myQuickFixes.put(key, fix); + } + PsiElement identifier = null; + if (psiMember instanceof PsiMethod method) { + identifier = method.getNameIdentifier(); + } + else if (psiMember instanceof PsiField field) { + identifier = field.getNameIdentifier(); + } + else if (psiMember instanceof PsiClass psiClass) { + identifier = psiClass.getNameIdentifier(); + } + if (identifier == null) { + identifier = psiMember; + } + result.add(manager.createProblemDescriptor( + identifier, + description, + (LocalQuickFix) fix, + ProblemHighlightType.GENERIC_ERROR_OR_WARNING, + false + )); + } + } } - } } - } - for (PsiElement suppressedScope : suppressedScopes.keySet()) { - Collection suppressedIds = suppressedScopes.get(suppressedScope); - for (String toolId : suppressedIds) { - PsiMember psiMember; - String problemLine = null; - if (suppressedScope instanceof PsiMember suppressedMember) { - psiMember = suppressedMember; - } else { - psiMember = PsiTreeUtil.getParentOfType(suppressedScope, PsiDocCommentOwner.class); - final 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 : ""); - QuickFix fix = myQuickFixes.get(key); - if (fix == null) { - fix = new RemoveSuppressWarningAction(toolId, problemLine); - myQuickFixes.put(key, fix); - } - PsiElement identifier = null; - if (psiMember instanceof PsiMethod method) { - identifier = method.getNameIdentifier(); - } else if (psiMember instanceof PsiField field) { - identifier = field.getNameIdentifier(); - } else if (psiMember instanceof PsiClass psiClass) { - identifier = psiClass.getNameIdentifier(); - } - if (identifier == null) { - identifier = psiMember; - } - result.add(manager.createProblemDescriptor( - identifier, - description, - (LocalQuickFix) fix, - ProblemHighlightType.GENERIC_ERROR_OR_WARNING, - false - )); - } + finally { + refManager.inspectionReadActionFinished(); + globalContext.close(true); } - } - } finally { - refManager.inspectionReadActionFinished(); - globalContext.close(true); + return result.toArray(new ProblemDescriptor[result.size()]); } - return result.toArray(new ProblemDescriptor[result.size()]); - } - protected InspectionToolWrapper[] getInspectionTools(PsiElement psiElement, @Nonnull InspectionManager manager) { - ModifiableModel model = InspectionProjectProfileManager.getInstance(manager.getProject()).getInspectionProfile().getModifiableModel(); - InspectionProfileWrapper profile = new InspectionProfileWrapper((InspectionProfile) model); + protected InspectionToolWrapper[] getInspectionTools(PsiElement psiElement, @Nonnull InspectionManager manager) { + ModifiableModel model = + InspectionProjectProfileManager.getInstance(manager.getProject()).getInspectionProfile().getModifiableModel(); + InspectionProfileWrapper profile = new InspectionProfileWrapper((InspectionProfile) model); - return profile.getInspectionTools(psiElement); - } + return profile.getInspectionTools(psiElement); + } - @Override - @Nullable - public QuickFix getQuickFix(final String hint) { - return myQuickFixes != null ? myQuickFixes.get(hint) : new RemoveSuppressWarningAction(hint); - } + @Override + @Nullable + public QuickFix getQuickFix(final String hint) { + return myQuickFixes != null ? myQuickFixes.get(hint) : new RemoveSuppressWarningAction(hint); + } - @Override - @Nullable - public String getHint(@Nonnull final QuickFix fix) { - if (myQuickFixes != null) { - final List list = myQuickFixes.getKeysByValue(fix); - if (list != null) { - LOG.assertTrue(list.size() == 1); - return list.get(0); - } + @Override + @Nullable + public String getHint(@Nonnull final QuickFix fix) { + if (myQuickFixes != null) { + final List list = myQuickFixes.getKeysByValue(fix); + if (list != null) { + LOG.assertTrue(list.size() == 1); + return list.get(0); + } + } + return null; } - return null; - } } diff --git a/plugin/src/main/java/com/intellij/java/impl/codeInspection/concurrencyAnnotations/NonFinalFieldInImmutableInspection.java b/plugin/src/main/java/com/intellij/java/impl/codeInspection/concurrencyAnnotations/NonFinalFieldInImmutableInspection.java index 77eec5bd7f..46bf858e6f 100644 --- a/plugin/src/main/java/com/intellij/java/impl/codeInspection/concurrencyAnnotations/NonFinalFieldInImmutableInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/codeInspection/concurrencyAnnotations/NonFinalFieldInImmutableInspection.java @@ -26,54 +26,52 @@ import consulo.language.editor.inspection.ProblemsHolder; import consulo.language.editor.inspection.localize.InspectionLocalize; import consulo.language.psi.PsiElementVisitor; -import org.jetbrains.annotations.Nls; - +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; @ExtensionImpl public class NonFinalFieldInImmutableInspection extends BaseJavaLocalInspectionTool { + @Nonnull + @Override + public LocalizeValue getGroupDisplayName() { + return InspectionLocalize.groupNamesConcurrencyAnnotationIssues(); + } - @Override - @Nonnull - public String getGroupDisplayName() { - return InspectionLocalize.groupNamesConcurrencyAnnotationIssues().get(); - } - - @Override - @Nls - @Nonnull - public String getDisplayName() { - return "Non-final field in @Immutable class"; - } - - @Override - @Nonnull - public String getShortName() { - return "NonFinalFieldInImmutable"; - } + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return LocalizeValue.localizeTODO("Non-final field in @Immutable class"); + } + @Override + @Nonnull + public String getShortName() { + return "NonFinalFieldInImmutable"; + } - @Override - @Nonnull - public PsiElementVisitor buildVisitorImpl(@Nonnull final ProblemsHolder holder, - boolean isOnTheFly, - LocalInspectionToolSession session, - Object state) { - return new JavaElementVisitor() { - @Override - public void visitField(PsiField field) { - super.visitField(field); - if (field.hasModifierProperty(PsiModifier.FINAL)) { - return; - } - final PsiClass containingClass = field.getContainingClass(); - if (containingClass != null) { - if (!JCiPUtil.isImmutable(containingClass)) { - return; - } - holder.registerProblem(field, "Non-final field #ref in @Immutable class #loc"); - } - } - }; - } + @Override + @Nonnull + public PsiElementVisitor buildVisitorImpl( + @Nonnull final ProblemsHolder holder, + boolean isOnTheFly, + LocalInspectionToolSession session, + Object state + ) { + return new JavaElementVisitor() { + @Override + public void visitField(PsiField field) { + super.visitField(field); + if (field.hasModifierProperty(PsiModifier.FINAL)) { + return; + } + final PsiClass containingClass = field.getContainingClass(); + if (containingClass != null) { + if (!JCiPUtil.isImmutable(containingClass)) { + return; + } + holder.registerProblem(field, "Non-final field #ref in @Immutable class #loc"); + } + } + }; + } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/codeInspection/concurrencyAnnotations/NonFinalGuardInspection.java b/plugin/src/main/java/com/intellij/java/impl/codeInspection/concurrencyAnnotations/NonFinalGuardInspection.java index e0726ab8f5..94cb9d8600 100644 --- a/plugin/src/main/java/com/intellij/java/impl/codeInspection/concurrencyAnnotations/NonFinalGuardInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/codeInspection/concurrencyAnnotations/NonFinalGuardInspection.java @@ -25,100 +25,99 @@ import consulo.language.editor.inspection.localize.InspectionLocalize; import consulo.language.psi.PsiElementVisitor; import consulo.language.psi.util.PsiTreeUtil; -import org.jetbrains.annotations.Nls; - +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; @ExtensionImpl public class NonFinalGuardInspection extends BaseJavaLocalInspectionTool { + @Nonnull + @Override + public LocalizeValue getGroupDisplayName() { + return InspectionLocalize.groupNamesConcurrencyAnnotationIssues(); + } - @Override - @Nonnull - public String getGroupDisplayName() { - return InspectionLocalize.groupNamesConcurrencyAnnotationIssues().get(); - } - - @Override - @Nls - @Nonnull - public String getDisplayName() { - return "Non-final @GuardedBy field"; - } + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return LocalizeValue.localizeTODO("Non-final @GuardedBy field"); + } - @Override - @Nonnull - public String getShortName() { - return "NonFinalGuard"; - } + @Override + @Nonnull + public String getShortName() { + return "NonFinalGuard"; + } - @Override - @Nonnull - public PsiElementVisitor buildVisitorImpl(@Nonnull ProblemsHolder holder, - boolean isOnTheFly, - LocalInspectionToolSession session, - Object state) { - return new Visitor(holder); - } + @Override + @Nonnull + public PsiElementVisitor buildVisitorImpl( + @Nonnull ProblemsHolder holder, + boolean isOnTheFly, + LocalInspectionToolSession session, + Object state + ) { + return new Visitor(holder); + } - private static class Visitor extends JavaElementVisitor { - private final ProblemsHolder myHolder; + private static class Visitor extends JavaElementVisitor { + private final ProblemsHolder myHolder; - public Visitor(ProblemsHolder holder) { + public Visitor(ProblemsHolder holder) { - myHolder = holder; - } + myHolder = holder; + } - @Override - public void visitAnnotation(PsiAnnotation annotation) { - super.visitAnnotation(annotation); - if (!JCiPUtil.isGuardedByAnnotation(annotation)) { - return; - } - final String guardValue = JCiPUtil.getGuardValue(annotation); - if (guardValue == null || "this".equals(guardValue)) { - return; - } - final PsiClass containingClass = PsiTreeUtil.getParentOfType(annotation, PsiClass.class); - if (containingClass == null) { - return; - } - final PsiField guardField = containingClass.findFieldByName(guardValue, true); - if (guardField == null) { - return; - } - if (guardField.hasModifierProperty(PsiModifier.FINAL)) { - return; - } - final PsiAnnotationMemberValue member = annotation.findAttributeValue("value"); - if (member == null) { - return; - } - myHolder.registerProblem(member, "Non-final @GuardedBy field #ref #loc"); - } + @Override + public void visitAnnotation(PsiAnnotation annotation) { + super.visitAnnotation(annotation); + if (!JCiPUtil.isGuardedByAnnotation(annotation)) { + return; + } + final String guardValue = JCiPUtil.getGuardValue(annotation); + if (guardValue == null || "this".equals(guardValue)) { + return; + } + final PsiClass containingClass = PsiTreeUtil.getParentOfType(annotation, PsiClass.class); + if (containingClass == null) { + return; + } + final PsiField guardField = containingClass.findFieldByName(guardValue, true); + if (guardField == null) { + return; + } + if (guardField.hasModifierProperty(PsiModifier.FINAL)) { + return; + } + final PsiAnnotationMemberValue member = annotation.findAttributeValue("value"); + if (member == null) { + return; + } + myHolder.registerProblem(member, "Non-final @GuardedBy field #ref #loc"); + } - @Override - public void visitDocTag(PsiDocTag psiDocTag) { - super.visitDocTag(psiDocTag); - if (!JCiPUtil.isGuardedByTag(psiDocTag)) { - return; - } - final String guardValue = JCiPUtil.getGuardValue(psiDocTag); - if ("this".equals(guardValue)) { - return; - } - final PsiClass containingClass = PsiTreeUtil.getParentOfType(psiDocTag, PsiClass.class); - if (containingClass == null) { - return; - } - final PsiField guardField = containingClass.findFieldByName(guardValue, true); - if (guardField == null) { - return; - } - if (guardField.hasModifierProperty(PsiModifier.FINAL)) { - return; - } - myHolder.registerProblem(psiDocTag, "Non-final @GuardedBy field \"" + guardValue + "\" #loc"); + @Override + public void visitDocTag(PsiDocTag psiDocTag) { + super.visitDocTag(psiDocTag); + if (!JCiPUtil.isGuardedByTag(psiDocTag)) { + return; + } + final String guardValue = JCiPUtil.getGuardValue(psiDocTag); + if ("this".equals(guardValue)) { + return; + } + final PsiClass containingClass = PsiTreeUtil.getParentOfType(psiDocTag, PsiClass.class); + if (containingClass == null) { + return; + } + final PsiField guardField = containingClass.findFieldByName(guardValue, true); + if (guardField == null) { + return; + } + if (guardField.hasModifierProperty(PsiModifier.FINAL)) { + return; + } + myHolder.registerProblem(psiDocTag, "Non-final @GuardedBy field \"" + guardValue + "\" #loc"); + } } - } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/codeInspection/concurrencyAnnotations/StaticGuardedByInstanceInspection.java b/plugin/src/main/java/com/intellij/java/impl/codeInspection/concurrencyAnnotations/StaticGuardedByInstanceInspection.java index 5e65a4f2ed..1eb1aff76d 100644 --- a/plugin/src/main/java/com/intellij/java/impl/codeInspection/concurrencyAnnotations/StaticGuardedByInstanceInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/codeInspection/concurrencyAnnotations/StaticGuardedByInstanceInspection.java @@ -26,121 +26,120 @@ import consulo.language.psi.PsiElement; import consulo.language.psi.PsiElementVisitor; import consulo.language.psi.util.PsiTreeUtil; -import org.jetbrains.annotations.Nls; - +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; @ExtensionImpl public class StaticGuardedByInstanceInspection extends BaseJavaLocalInspectionTool { + @Nonnull + @Override + public LocalizeValue getGroupDisplayName() { + return InspectionLocalize.groupNamesConcurrencyAnnotationIssues(); + } - @Override - @Nonnull - public String getGroupDisplayName() { - return InspectionLocalize.groupNamesConcurrencyAnnotationIssues().get(); - } - - @Override - @Nls - @Nonnull - public String getDisplayName() { - return "Static member guarded by instance field or this"; - } + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return LocalizeValue.localizeTODO("Static member guarded by instance field or this"); + } - @Override - @Nonnull - public String getShortName() { - return "StaticGuardedByInstance"; - } + @Override + @Nonnull + public String getShortName() { + return "StaticGuardedByInstance"; + } - @Override - @Nonnull - public PsiElementVisitor buildVisitorImpl(@Nonnull ProblemsHolder holder, - boolean isOnTheFly, - LocalInspectionToolSession session, - Object state) { - return new Visitor(holder); - } + @Override + @Nonnull + public PsiElementVisitor buildVisitorImpl( + @Nonnull ProblemsHolder holder, + boolean isOnTheFly, + LocalInspectionToolSession session, + Object state + ) { + return new Visitor(holder); + } - private static class Visitor extends JavaElementVisitor { - private final ProblemsHolder myHolder; + private static class Visitor extends JavaElementVisitor { + private final ProblemsHolder myHolder; - public Visitor(ProblemsHolder holder) { - myHolder = holder; - } + public Visitor(ProblemsHolder holder) { + myHolder = holder; + } - @Override - public void visitAnnotation(PsiAnnotation annotation) { - super.visitAnnotation(annotation); - if (!JCiPUtil.isGuardedByAnnotation(annotation)) { - return; - } - final PsiMember member = PsiTreeUtil.getParentOfType(annotation, PsiMember.class); - if (member == null) { - return; - } - if (!member.hasModifierProperty(PsiModifier.STATIC)) { - return; - } - final String guardValue = JCiPUtil.getGuardValue(annotation); - if (guardValue == null) { - return; - } + @Override + public void visitAnnotation(PsiAnnotation annotation) { + super.visitAnnotation(annotation); + if (!JCiPUtil.isGuardedByAnnotation(annotation)) { + return; + } + final PsiMember member = PsiTreeUtil.getParentOfType(annotation, PsiMember.class); + if (member == null) { + return; + } + if (!member.hasModifierProperty(PsiModifier.STATIC)) { + return; + } + final String guardValue = JCiPUtil.getGuardValue(annotation); + if (guardValue == null) { + return; + } - final PsiAnnotationMemberValue guardRef = annotation.findAttributeValue("value"); - if (guardRef == null) { - return; - } - if ("this".equals(guardValue)) { - registerError(guardRef); - } - final PsiClass containingClass = PsiTreeUtil.getParentOfType(annotation, PsiClass.class); - if (containingClass == null) { - return; - } - final PsiField guardField = containingClass.findFieldByName(guardValue, true); - if (guardField == null) { - return; - } - if (guardField.hasModifierProperty(PsiModifier.STATIC)) { - return; - } - registerError(guardRef); - } + final PsiAnnotationMemberValue guardRef = annotation.findAttributeValue("value"); + if (guardRef == null) { + return; + } + if ("this".equals(guardValue)) { + registerError(guardRef); + } + final PsiClass containingClass = PsiTreeUtil.getParentOfType(annotation, PsiClass.class); + if (containingClass == null) { + return; + } + final PsiField guardField = containingClass.findFieldByName(guardValue, true); + if (guardField == null) { + return; + } + if (guardField.hasModifierProperty(PsiModifier.STATIC)) { + return; + } + registerError(guardRef); + } - @Override - public void visitDocTag(PsiDocTag psiDocTag) { - super.visitDocTag(psiDocTag); - if (!JCiPUtil.isGuardedByTag(psiDocTag)) { - return; - } - final PsiMember member = PsiTreeUtil.getParentOfType(psiDocTag, PsiMember.class); - if (member == null) { - return; - } - if (!member.hasModifierProperty(PsiModifier.STATIC)) { - return; - } - final String guardValue = JCiPUtil.getGuardValue(psiDocTag); + @Override + public void visitDocTag(PsiDocTag psiDocTag) { + super.visitDocTag(psiDocTag); + if (!JCiPUtil.isGuardedByTag(psiDocTag)) { + return; + } + final PsiMember member = PsiTreeUtil.getParentOfType(psiDocTag, PsiMember.class); + if (member == null) { + return; + } + if (!member.hasModifierProperty(PsiModifier.STATIC)) { + return; + } + final String guardValue = JCiPUtil.getGuardValue(psiDocTag); - if ("this".equals(guardValue)) { - registerError(psiDocTag); - } - final PsiClass containingClass = PsiTreeUtil.getParentOfType(psiDocTag, PsiClass.class); - if (containingClass == null) { - return; - } - final PsiField guardField = containingClass.findFieldByName(guardValue, true); - if (guardField == null) { - return; - } - if (guardField.hasModifierProperty(PsiModifier.STATIC)) { - return; - } - myHolder.registerProblem(psiDocTag, "Static member guarded by instance \"" + guardValue + "\" #loc"); - } + if ("this".equals(guardValue)) { + registerError(psiDocTag); + } + final PsiClass containingClass = PsiTreeUtil.getParentOfType(psiDocTag, PsiClass.class); + if (containingClass == null) { + return; + } + final PsiField guardField = containingClass.findFieldByName(guardValue, true); + if (guardField == null) { + return; + } + if (guardField.hasModifierProperty(PsiModifier.STATIC)) { + return; + } + myHolder.registerProblem(psiDocTag, "Static member guarded by instance \"" + guardValue + "\" #loc"); + } - private void registerError(PsiElement element) { - myHolder.registerProblem(element, "Static member guarded by instance #ref #loc"); + private void registerError(PsiElement element) { + myHolder.registerProblem(element, "Static member guarded by instance #ref #loc"); + } } - } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/codeInspection/concurrencyAnnotations/UnknownGuardInspection.java b/plugin/src/main/java/com/intellij/java/impl/codeInspection/concurrencyAnnotations/UnknownGuardInspection.java index 7bb22ddfb5..68edfe1999 100644 --- a/plugin/src/main/java/com/intellij/java/impl/codeInspection/concurrencyAnnotations/UnknownGuardInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/codeInspection/concurrencyAnnotations/UnknownGuardInspection.java @@ -26,10 +26,9 @@ import consulo.language.psi.PsiElementVisitor; import consulo.language.psi.scope.GlobalSearchScope; import consulo.language.psi.util.PsiTreeUtil; +import consulo.localize.LocalizeValue; import consulo.project.Project; import consulo.util.lang.StringUtil; -import org.jetbrains.annotations.Nls; - import jakarta.annotation.Nonnull; /** @@ -37,145 +36,147 @@ */ @ExtensionImpl public class UnknownGuardInspection extends BaseJavaLocalInspectionTool { + @Nonnull + @Override + public LocalizeValue getGroupDisplayName() { + return InspectionLocalize.groupNamesConcurrencyAnnotationIssues(); + } - @Override - @Nonnull - public String getGroupDisplayName() { - return InspectionLocalize.groupNamesConcurrencyAnnotationIssues().get(); - } - - @Override - @Nls - @Nonnull - public String getDisplayName() { - return "Unknown @GuardedBy field"; - } - - @Override - @Nonnull - public String getShortName() { - return "UnknownGuard"; - } - - @Override - @Nonnull - public PsiElementVisitor buildVisitorImpl(@Nonnull ProblemsHolder holder, - boolean isOnTheFly, - LocalInspectionToolSession session, - Object state) { - return new Visitor(holder); - } - - private static class Visitor extends JavaElementVisitor { - private final ProblemsHolder myHolder; - - public Visitor(ProblemsHolder holder) { - myHolder = holder; + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return LocalizeValue.localizeTODO("Unknown @GuardedBy field"); } @Override - public void visitAnnotation(PsiAnnotation annotation) { - super.visitAnnotation(annotation); - if (!JCiPUtil.isGuardedByAnnotation(annotation)) { - return; - } - final String guardValue = JCiPUtil.getGuardValue(annotation); - if (guardValue == null || "this".equals(guardValue) || "itself".equals(guardValue)) { - return; - } - final PsiClass containingClass = PsiTreeUtil.getParentOfType(annotation, PsiClass.class); - if (containingClass == null) { - return; - } - - if (containsFieldOrMethod(containingClass, guardValue)) return; - - //class-name.class - final Project project = containingClass.getProject(); - final JavaPsiFacade facade = JavaPsiFacade.getInstance(project); - if (guardValue.endsWith(".class") && - facade.findClass(StringUtil.getPackageName(guardValue), GlobalSearchScope.allScope(project)) != null) { - return; - } - - //class-name.field-name - final String classFQName = StringUtil.getPackageName(guardValue); - final PsiClass gClass = facade.findClass(classFQName, GlobalSearchScope.allScope(project)); - if (gClass != null) { - final String fieldName = StringUtil.getShortName(guardValue); - if (gClass.findFieldByName(fieldName, true) != null) { - return; - } - //class-name.this - if (fieldName.equals("this")) { - return; - } - } - - //class-name.this.field-name/method-name - final int thisIdx = guardValue.indexOf("this"); - if (thisIdx > -1 && thisIdx + 1 < guardValue.length()) { - final PsiClass lockClass; - if (thisIdx == 0) { - lockClass = containingClass; - } - else { - final String fqn = guardValue.substring(0, thisIdx - 1); - lockClass = facade.findClass(fqn, GlobalSearchScope.allScope(project)); - } + @Nonnull + public String getShortName() { + return "UnknownGuard"; + } - if (lockClass != null) { - final String fieldName = guardValue.substring(thisIdx + "this".length() + 1); - if (containsFieldOrMethod(lockClass, fieldName)) { - return; - } + @Override + @Nonnull + public PsiElementVisitor buildVisitorImpl( + @Nonnull ProblemsHolder holder, + boolean isOnTheFly, + LocalInspectionToolSession session, + Object state + ) { + return new Visitor(holder); + } + + private static class Visitor extends JavaElementVisitor { + private final ProblemsHolder myHolder; + + public Visitor(ProblemsHolder holder) { + myHolder = holder; } - } - final PsiAnnotationMemberValue member = annotation.findAttributeValue("value"); - if (member == null) { - return; - } - myHolder.registerProblem(member, "Unknown @GuardedBy field #ref #loc"); - } + @Override + public void visitAnnotation(PsiAnnotation annotation) { + super.visitAnnotation(annotation); + if (!JCiPUtil.isGuardedByAnnotation(annotation)) { + return; + } + final String guardValue = JCiPUtil.getGuardValue(annotation); + if (guardValue == null || "this".equals(guardValue) || "itself".equals(guardValue)) { + return; + } + final PsiClass containingClass = PsiTreeUtil.getParentOfType(annotation, PsiClass.class); + if (containingClass == null) { + return; + } + + if (containsFieldOrMethod(containingClass, guardValue)) { + return; + } + + //class-name.class + final Project project = containingClass.getProject(); + final JavaPsiFacade facade = JavaPsiFacade.getInstance(project); + if (guardValue.endsWith(".class") && + facade.findClass(StringUtil.getPackageName(guardValue), GlobalSearchScope.allScope(project)) != null) { + return; + } + + //class-name.field-name + final String classFQName = StringUtil.getPackageName(guardValue); + final PsiClass gClass = facade.findClass(classFQName, GlobalSearchScope.allScope(project)); + if (gClass != null) { + final String fieldName = StringUtil.getShortName(guardValue); + if (gClass.findFieldByName(fieldName, true) != null) { + return; + } + //class-name.this + if (fieldName.equals("this")) { + return; + } + } + + //class-name.this.field-name/method-name + final int thisIdx = guardValue.indexOf("this"); + if (thisIdx > -1 && thisIdx + 1 < guardValue.length()) { + final PsiClass lockClass; + if (thisIdx == 0) { + lockClass = containingClass; + } + else { + final String fqn = guardValue.substring(0, thisIdx - 1); + lockClass = facade.findClass(fqn, GlobalSearchScope.allScope(project)); + } + + if (lockClass != null) { + final String fieldName = guardValue.substring(thisIdx + "this".length() + 1); + if (containsFieldOrMethod(lockClass, fieldName)) { + return; + } + } + } + + final PsiAnnotationMemberValue member = annotation.findAttributeValue("value"); + if (member == null) { + return; + } + myHolder.registerProblem(member, "Unknown @GuardedBy field #ref #loc"); + } - private static boolean containsFieldOrMethod(PsiClass containingClass, String fieldOrMethod) { - //field-name - if (containingClass.findFieldByName(fieldOrMethod, true) != null) { - return true; - } - - //method-name - if (fieldOrMethod.endsWith("()")) { - final PsiMethod[] methods = containingClass.findMethodsByName(StringUtil.trimEnd(fieldOrMethod, "()"), true); - for (PsiMethod method : methods) { - if (method.getParameterList().getParameters().length == 0) { - return true; - } + private static boolean containsFieldOrMethod(PsiClass containingClass, String fieldOrMethod) { + //field-name + if (containingClass.findFieldByName(fieldOrMethod, true) != null) { + return true; + } + + //method-name + if (fieldOrMethod.endsWith("()")) { + final PsiMethod[] methods = containingClass.findMethodsByName(StringUtil.trimEnd(fieldOrMethod, "()"), true); + for (PsiMethod method : methods) { + if (method.getParameterList().getParameters().length == 0) { + return true; + } + } + } + return false; } - } - return false; - } - @Override - public void visitDocTag(PsiDocTag psiDocTag) { - super.visitDocTag(psiDocTag); - if (!JCiPUtil.isGuardedByTag(psiDocTag)) { - return; - } - final String guardValue = JCiPUtil.getGuardValue(psiDocTag); - if ("this".equals(guardValue)) { - return; - } - final PsiClass containingClass = PsiTreeUtil.getParentOfType(psiDocTag, PsiClass.class); - if (containingClass == null) { - return; - } - final PsiField guardField = containingClass.findFieldByName(guardValue, true); - if (guardField != null) { - return; - } - myHolder.registerProblem(psiDocTag, "Unknown @GuardedBy field \"" + guardValue + "\" #loc"); + @Override + public void visitDocTag(PsiDocTag psiDocTag) { + super.visitDocTag(psiDocTag); + if (!JCiPUtil.isGuardedByTag(psiDocTag)) { + return; + } + final String guardValue = JCiPUtil.getGuardValue(psiDocTag); + if ("this".equals(guardValue)) { + return; + } + final PsiClass containingClass = PsiTreeUtil.getParentOfType(psiDocTag, PsiClass.class); + if (containingClass == null) { + return; + } + final PsiField guardField = containingClass.findFieldByName(guardValue, true); + if (guardField != null) { + return; + } + myHolder.registerProblem(psiDocTag, "Unknown @GuardedBy field \"" + guardValue + "\" #loc"); + } } - } } diff --git a/plugin/src/main/java/com/intellij/java/impl/codeInspection/deadCode/DummyEntryPointsTool.java b/plugin/src/main/java/com/intellij/java/impl/codeInspection/deadCode/DummyEntryPointsTool.java index f625d16059..ba44770f7e 100644 --- a/plugin/src/main/java/com/intellij/java/impl/codeInspection/deadCode/DummyEntryPointsTool.java +++ b/plugin/src/main/java/com/intellij/java/impl/codeInspection/deadCode/DummyEntryPointsTool.java @@ -30,41 +30,38 @@ */ @SuppressWarnings("ExtensionImplIsNotAnnotatedInspection") public class DummyEntryPointsTool extends UnusedDeclarationInspection { - public DummyEntryPointsTool() { - } + @Override + public void runInspection( + @Nonnull AnalysisScope scope, + @Nonnull InspectionManager manager, + @Nonnull GlobalInspectionContext globalContext, + @Nonnull ProblemDescriptionsProcessor problemDescriptionsProcessor, + Object state + ) { + } - @Override - public void runInspection( - @Nonnull AnalysisScope scope, - @Nonnull InspectionManager manager, - @Nonnull GlobalInspectionContext globalContext, - @Nonnull ProblemDescriptionsProcessor problemDescriptionsProcessor, - Object state - ) { - } + @Nullable + @Override + public JobDescriptor[] getAdditionalJobs() { + return JobDescriptor.EMPTY_ARRAY; + } - @Nullable - @Override - public JobDescriptor[] getAdditionalJobs() { - return JobDescriptor.EMPTY_ARRAY; - } + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionLocalize.inspectionDeadCodeEntryPointsDisplayName(); + } - @Override - @Nonnull - public LocalizeValue getDisplayName() { - return InspectionLocalize.inspectionDeadCodeEntryPointsDisplayName(); - } + @Override + @Nonnull + public LocalizeValue getGroupDisplayName() { + return LocalizeValue.of(); + } - @Override - @Nonnull - public LocalizeValue getGroupDisplayName() { - return LocalizeValue.of(); - } - - @Override - @Nonnull - public String getShortName() { - //noinspection InspectionDescriptionNotFoundInspection - return ""; - } + @Override + @Nonnull + public String getShortName() { + //noinspection InspectionDescriptionNotFoundInspection + return ""; + } } diff --git a/plugin/src/main/java/com/intellij/java/impl/codeInspection/inheritance/SuperClassHasFrequentlyUsedInheritorsInspection.java b/plugin/src/main/java/com/intellij/java/impl/codeInspection/inheritance/SuperClassHasFrequentlyUsedInheritorsInspection.java index 209d24718a..1223c92480 100644 --- a/plugin/src/main/java/com/intellij/java/impl/codeInspection/inheritance/SuperClassHasFrequentlyUsedInheritorsInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/codeInspection/inheritance/SuperClassHasFrequentlyUsedInheritorsInspection.java @@ -10,9 +10,9 @@ import consulo.language.editor.inspection.ProblemHighlightType; import consulo.language.editor.inspection.localize.InspectionLocalize; import consulo.language.editor.inspection.scheme.InspectionManager; +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; -import org.jetbrains.annotations.Nls; import java.util.ArrayList; import java.util.Collection; @@ -23,100 +23,109 @@ */ @ExtensionImpl public class SuperClassHasFrequentlyUsedInheritorsInspection extends BaseJavaLocalInspectionTool { - private final static int MIN_PERCENT_RATIO = 5; - public final static int MAX_QUICK_FIX_COUNTS = 4; + private final static int MIN_PERCENT_RATIO = 5; + public final static int MAX_QUICK_FIX_COUNTS = 4; - @Nls - @Nonnull - @Override - public String getGroupDisplayName() { - return InspectionLocalize.groupNamesInheritanceIssues().get(); - } - - @Nls - @Nonnull - @Override - public String getDisplayName() { - return "Class may extend a commonly used base class instead of implementing interface or extending abstract class"; - } + @Nonnull + @Override + public LocalizeValue getGroupDisplayName() { + return InspectionLocalize.groupNamesInheritanceIssues(); + } - @Override - public boolean isEnabledByDefault() { - return true; - } + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return LocalizeValue.localizeTODO( + "Class may extend a commonly used base class instead of implementing interface or extending abstract class" + ); + } - @Nullable - @Override - public ProblemDescriptor[] checkClass(@Nonnull final PsiClass aClass, - @Nonnull final InspectionManager manager, - final boolean isOnTheFly, Object state) { - if (aClass.isInterface() || - aClass instanceof PsiTypeParameter || - aClass.getMethods().length != 0 || - aClass.hasModifierProperty(PsiModifier.ABSTRACT)) { - return null; + @Override + public boolean isEnabledByDefault() { + return true; } - final PsiClass superClass = getSuperIfUnique(aClass); - if (superClass == null) return null; + @Nullable + @Override + public ProblemDescriptor[] checkClass( + @Nonnull final PsiClass aClass, + @Nonnull final InspectionManager manager, + final boolean isOnTheFly, Object state + ) { + if (aClass.isInterface() || + aClass instanceof PsiTypeParameter || + aClass.getMethods().length != 0 || + aClass.hasModifierProperty(PsiModifier.ABSTRACT)) { + return null; + } - final List topInheritors = - InheritorsStatisticalDataSearch.search(superClass, aClass, aClass.getResolveScope(), MIN_PERCENT_RATIO); + final PsiClass superClass = getSuperIfUnique(aClass); + if (superClass == null) { + return null; + } - if (topInheritors.isEmpty()) { - return null; - } + final List topInheritors = + InheritorsStatisticalDataSearch.search(superClass, aClass, aClass.getResolveScope(), MIN_PERCENT_RATIO); - final Collection topInheritorsQuickFix = new ArrayList(topInheritors.size()); + if (topInheritors.isEmpty()) { + return null; + } - boolean isFirst = true; - for (final InheritorsStatisticsSearchResult searchResult : topInheritors) { - final LocalQuickFix quickFix; - if (isFirst) { - quickFix = new ChangeSuperClassFix(searchResult.getPsiClass(), searchResult.getPercent(), superClass); - isFirst = false; - } else { - quickFix = new ChangeSuperClassFix.LowPriority(searchResult.getPsiClass(), searchResult.getPercent(), superClass); - } - topInheritorsQuickFix.add(quickFix); - if (topInheritorsQuickFix.size() >= MAX_QUICK_FIX_COUNTS) { - break; - } - } - return new ProblemDescriptor[]{manager - .createProblemDescriptor(aClass, "Class may extend a commonly used base class instead of implementing interface or extending abstract class", false, - topInheritorsQuickFix.toArray(new LocalQuickFix[topInheritorsQuickFix.size()]), - ProblemHighlightType.INFORMATION)}; - } + final Collection topInheritorsQuickFix = new ArrayList(topInheritors.size()); - @Nullable - private static PsiClass getSuperIfUnique(final @Nonnull PsiClass aClass) { - if (aClass instanceof PsiAnonymousClass) { - return (PsiClass)((PsiAnonymousClass)aClass).getBaseClassReference().resolve(); - } - final PsiReferenceList extendsList = aClass.getExtendsList(); - if (extendsList != null) { - final PsiJavaCodeReferenceElement[] referenceElements = extendsList.getReferenceElements(); - if (referenceElements.length == 1) { - PsiClass returnClass = (PsiClass)referenceElements[0].resolve(); - if (returnClass != null - && !CommonClassNames.JAVA_LANG_OBJECT.equals(returnClass.getQualifiedName()) - && !returnClass.isInterface()) { - return returnClass; + boolean isFirst = true; + for (final InheritorsStatisticsSearchResult searchResult : topInheritors) { + final LocalQuickFix quickFix; + if (isFirst) { + quickFix = new ChangeSuperClassFix(searchResult.getPsiClass(), searchResult.getPercent(), superClass); + isFirst = false; + } + else { + quickFix = new ChangeSuperClassFix.LowPriority(searchResult.getPsiClass(), searchResult.getPercent(), superClass); + } + topInheritorsQuickFix.add(quickFix); + if (topInheritorsQuickFix.size() >= MAX_QUICK_FIX_COUNTS) { + break; + } } - } + return new ProblemDescriptor[]{manager + .createProblemDescriptor( + aClass, + "Class may extend a commonly used base class instead of implementing interface or extending abstract class", + false, + topInheritorsQuickFix.toArray(new LocalQuickFix[topInheritorsQuickFix.size()]), + ProblemHighlightType.INFORMATION + )}; } - final PsiReferenceList implementsList = aClass.getImplementsList(); - if (implementsList != null) { - final PsiJavaCodeReferenceElement[] referenceElements = implementsList.getReferenceElements(); - if (referenceElements.length == 1) { - PsiClass returnClass = (PsiClass)referenceElements[0].resolve(); - if (returnClass != null && returnClass.isInterface()) { - return returnClass; + @Nullable + private static PsiClass getSuperIfUnique(final @Nonnull PsiClass aClass) { + if (aClass instanceof PsiAnonymousClass) { + return (PsiClass) ((PsiAnonymousClass) aClass).getBaseClassReference().resolve(); + } + final PsiReferenceList extendsList = aClass.getExtendsList(); + if (extendsList != null) { + final PsiJavaCodeReferenceElement[] referenceElements = extendsList.getReferenceElements(); + if (referenceElements.length == 1) { + PsiClass returnClass = (PsiClass) referenceElements[0].resolve(); + if (returnClass != null + && !CommonClassNames.JAVA_LANG_OBJECT.equals(returnClass.getQualifiedName()) + && !returnClass.isInterface()) { + return returnClass; + } + } + } + + final PsiReferenceList implementsList = aClass.getImplementsList(); + if (implementsList != null) { + final PsiJavaCodeReferenceElement[] referenceElements = implementsList.getReferenceElements(); + if (referenceElements.length == 1) { + PsiClass returnClass = (PsiClass) referenceElements[0].resolve(); + if (returnClass != null && returnClass.isInterface()) { + return returnClass; + } + } } - } + return null; } - return null; - } } 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 b9c213412d..5090365791 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 @@ -30,6 +30,7 @@ import consulo.language.editor.inspection.scheme.InspectionManager; import consulo.language.psi.PsiElement; import consulo.language.util.IncorrectOperationException; +import consulo.localize.LocalizeValue; import consulo.logging.Logger; import consulo.project.Project; import jakarta.annotation.Nonnull; @@ -44,173 +45,184 @@ */ @ExtensionImpl public class RedundantArrayForVarargsCallInspection extends GenericsInspectionToolBase { - private static final Logger LOG = Logger.getInstance(RedundantArrayForVarargsCallInspection.class); - private final LocalQuickFix myQuickFixAction = new MyQuickFix(); + private static final Logger LOG = Logger.getInstance(RedundantArrayForVarargsCallInspection.class); + private final LocalQuickFix myQuickFixAction = new MyQuickFix(); + + private static class MyQuickFix implements LocalQuickFix { + @Override + public void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor descriptor) { + PsiNewExpression arrayCreation = (PsiNewExpression) descriptor.getPsiElement(); + if (arrayCreation == null || !arrayCreation.isValid()) { + return; + } + if (!FileModificationService.getInstance().prepareFileForWrite(arrayCreation.getContainingFile())) { + return; + } + InlineUtil.inlineArrayCreationForVarargs(arrayCreation); + } - private static class MyQuickFix implements LocalQuickFix { - @Override - public void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor descriptor) { - PsiNewExpression arrayCreation = (PsiNewExpression) descriptor.getPsiElement(); - if (arrayCreation == null || !arrayCreation.isValid()) return; - if (!FileModificationService.getInstance().prepareFileForWrite(arrayCreation.getContainingFile())) return; - InlineUtil.inlineArrayCreationForVarargs(arrayCreation); + @Nonnull + @Override + public LocalizeValue getName() { + return InspectionLocalize.inspectionRedundantArrayCreationQuickfix(); + } } @Override - @Nonnull - public String getFamilyName() { - return getName(); - } + public ProblemDescriptor[] getDescriptions(PsiElement place, final InspectionManager manager, final boolean isOnTheFly, Object state) { + if (!PsiUtil.isLanguageLevel5OrHigher(place)) { + return null; + } + final List problems = new ArrayList<>(); + place.accept(new JavaRecursiveElementWalkingVisitor() { + @Override + public void visitCallExpression(@Nonnull PsiCallExpression expression) { + super.visitCallExpression(expression); + checkCall(expression); + } - @Override - @Nonnull - public String getName() { - return InspectionLocalize.inspectionRedundantArrayCreationQuickfix().get(); - } - } - - @Override - public ProblemDescriptor[] getDescriptions(PsiElement place, final InspectionManager manager, final boolean isOnTheFly, Object state) { - if (!PsiUtil.isLanguageLevel5OrHigher(place)) return null; - final List problems = new ArrayList<>(); - place.accept(new JavaRecursiveElementWalkingVisitor() { - @Override - public void visitCallExpression(@Nonnull PsiCallExpression expression) { - super.visitCallExpression(expression); - checkCall(expression); - } - - @Override - public void visitEnumConstant(@Nonnull PsiEnumConstant enumConstant) { - super.visitEnumConstant(enumConstant); - checkCall(enumConstant); - } - - @Override - public void visitClass(@Nonnull PsiClass aClass) { - //do not go inside to prevent multiple signals of the same problem - } - - 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()) { - PsiParameter[] parameters = method.getParameterList().getParameters(); - PsiExpressionList argumentList = expression.getArgumentList(); - if (argumentList != null) { - PsiExpression[] args = argumentList.getExpressions(); - if (parameters.length == args.length) { - PsiExpression lastArg = args[args.length - 1]; - PsiParameter lastParameter = parameters[args.length - 1]; - PsiType lastParamType = lastParameter.getType(); - LOG.assertTrue(lastParamType instanceof PsiEllipsisType); - 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); - } + @Override + public void visitEnumConstant(@Nonnull PsiEnumConstant enumConstant) { + super.visitEnumConstant(enumConstant); + checkCall(enumConstant); + } + + @Override + public void visitClass(@Nonnull PsiClass aClass) { + //do not go inside to prevent multiple signals of the same problem + } + + 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()) { + PsiParameter[] parameters = method.getParameterList().getParameters(); + PsiExpressionList argumentList = expression.getArgumentList(); + if (argumentList != null) { + PsiExpression[] args = argumentList.getExpressions(); + if (parameters.length == args.length) { + PsiExpression lastArg = args[args.length - 1]; + PsiParameter lastParameter = parameters[args.length - 1]; + PsiType lastParamType = lastParameter.getType(); + LOG.assertTrue(lastParamType instanceof PsiEllipsisType); + 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); + } + } + } + } + } } - } } - } + + private boolean isSafeToFlatten(PsiCall callExpression, PsiMethod oldRefMethod, PsiExpression[] arrayElements) { + if (arrayElements.length == 1) { + PsiType type = arrayElements[0].getType(); + // change foo(new Object[]{array}) to foo(array) is not safe + if (PsiType.NULL.equals(type) || type instanceof PsiArrayType) { + return false; + } + } + PsiCall copy = (PsiCall) callExpression.copy(); + PsiExpressionList copyArgumentList = copy.getArgumentList(); + LOG.assertTrue(copyArgumentList != null); + PsiExpression[] args = copyArgumentList.getExpressions(); + try { + args[args.length - 1].delete(); + if (arrayElements.length > 0) { + copyArgumentList.addRange(arrayElements[0], arrayElements[arrayElements.length - 1]); + } + final Project project = callExpression.getProject(); + final 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); + resolveResult = facade.getResolveHelper().resolveConstructor(classType, copyArgumentList, enumConstant); + return resolveResult.isValidResult() && resolveResult.getElement() == oldRefMethod; + } + else { + resolveResult = copy.resolveMethodGenerics(); + if (!resolveResult.isValidResult() || resolveResult.getElement() != oldRefMethod) { + return false; + } + final ExpectedTypeInfo[] expectedTypes = + ExpectedTypesProvider.getExpectedTypes((PsiCallExpression) callExpression, false); + final PsiType expressionType = ((PsiCallExpression) copy).getType(); + for (ExpectedTypeInfo expectedType : expectedTypes) { + if (!expectedType.getType().isAssignableFrom(expressionType)) { + return false; + } + } + return true; + } + } + catch (IncorrectOperationException e) { + return false; + } + } + }); + if (problems.isEmpty()) { + return null; } - } + return problems.toArray(new ProblemDescriptor[problems.size()]); + } - private boolean isSafeToFlatten(PsiCall callExpression, PsiMethod oldRefMethod, PsiExpression[] arrayElements) { - if (arrayElements.length == 1) { - PsiType type = arrayElements[0].getType(); - // change foo(new Object[]{array}) to foo(array) is not safe - if (PsiType.NULL.equals(type) || type instanceof PsiArrayType) return false; + @Nullable + private static PsiExpression[] getInitializers(final PsiNewExpression newExpression) { + PsiArrayInitializerExpression initializer = newExpression.getArrayInitializer(); + if (initializer != null) { + return initializer.getInitializers(); } - PsiCall copy = (PsiCall) callExpression.copy(); - PsiExpressionList copyArgumentList = copy.getArgumentList(); - LOG.assertTrue(copyArgumentList != null); - PsiExpression[] args = copyArgumentList.getExpressions(); - try { - args[args.length - 1].delete(); - if (arrayElements.length > 0) { - copyArgumentList.addRange(arrayElements[0], arrayElements[arrayElements.length - 1]); - } - final Project project = callExpression.getProject(); - final 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); - resolveResult = facade.getResolveHelper().resolveConstructor(classType, copyArgumentList, enumConstant); - return resolveResult.isValidResult() && resolveResult.getElement() == oldRefMethod; - } else { - resolveResult = copy.resolveMethodGenerics(); - if (!resolveResult.isValidResult() || resolveResult.getElement() != oldRefMethod) { - return false; + PsiExpression[] dims = newExpression.getArrayDimensions(); + if (dims.length > 0) { + PsiExpression firstDimension = dims[0]; + Object value = + JavaPsiFacade.getInstance(newExpression.getProject()) + .getConstantEvaluationHelper() + .computeConstantExpression(firstDimension); + if (value instanceof Integer intValue && intValue == 0) { + return PsiExpression.EMPTY_ARRAY; } - final ExpectedTypeInfo[] expectedTypes = ExpectedTypesProvider.getExpectedTypes((PsiCallExpression) callExpression, false); - final PsiType expressionType = ((PsiCallExpression) copy).getType(); - for (ExpectedTypeInfo expectedType : expectedTypes) { - if (!expectedType.getType().isAssignableFrom(expressionType)) { - return false; - } - } - return true; - } - } catch (IncorrectOperationException e) { - return false; } - } - }); - if (problems.isEmpty()) return null; - return problems.toArray(new ProblemDescriptor[problems.size()]); - } - - @Nullable - private static PsiExpression[] getInitializers(final PsiNewExpression newExpression) { - PsiArrayInitializerExpression initializer = newExpression.getArrayInitializer(); - if (initializer != null) { - return initializer.getInitializers(); + + return null; + } + + @Override + public boolean isEnabledByDefault() { + return true; + } + + @Nonnull + @Override + public LocalizeValue getGroupDisplayName() { + return InspectionLocalize.groupNamesVerboseOrRedundantCodeConstructs(); } - PsiExpression[] dims = newExpression.getArrayDimensions(); - if (dims.length > 0) { - PsiExpression firstDimension = dims[0]; - Object value = - JavaPsiFacade.getInstance(newExpression.getProject()).getConstantEvaluationHelper().computeConstantExpression(firstDimension); - if (value instanceof Integer intValue && intValue == 0) return PsiExpression.EMPTY_ARRAY; + + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionLocalize.inspectionRedundantArrayCreationDisplayName(); } - return null; - } - - @Override - public boolean isEnabledByDefault() { - return true; - } - - @Override - @Nonnull - public String getGroupDisplayName() { - return InspectionLocalize.groupNamesVerboseOrRedundantCodeConstructs().get(); - } - - @Override - @Nonnull - public String getDisplayName() { - return InspectionLocalize.inspectionRedundantArrayCreationDisplayName().get(); - } - - @Override - @Nonnull - @NonNls - public String getShortName() { - return "RedundantArrayCreation"; - } + @Override + @Nonnull + @NonNls + public String getShortName() { + return "RedundantArrayCreation"; + } } diff --git a/plugin/src/main/java/com/intellij/java/impl/codeInspection/miscGenerics/SuspiciousCollectionsMethodCallsInspection.java b/plugin/src/main/java/com/intellij/java/impl/codeInspection/miscGenerics/SuspiciousCollectionsMethodCallsInspection.java index 4c3add7012..58ca1b5ca6 100644 --- a/plugin/src/main/java/com/intellij/java/impl/codeInspection/miscGenerics/SuspiciousCollectionsMethodCallsInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/codeInspection/miscGenerics/SuspiciousCollectionsMethodCallsInspection.java @@ -15,6 +15,7 @@ import consulo.language.editor.inspection.ProblemsHolder; import consulo.language.editor.inspection.localize.InspectionLocalize; import consulo.language.psi.PsiElementVisitor; +import consulo.localize.LocalizeValue; import consulo.util.lang.ObjectUtil; import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; @@ -32,8 +33,14 @@ public class SuspiciousCollectionsMethodCallsInspection extends AbstractBaseJava @Nonnull @Override - public String getDisplayName() { - return InspectionLocalize.inspectionSuspiciousCollectionsMethodCallsDisplayName().get(); + public LocalizeValue getGroupDisplayName() { + return InspectionLocalize.groupNamesProbableBugs(); + } + + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionLocalize.inspectionSuspiciousCollectionsMethodCallsDisplayName(); } @Override @@ -100,12 +107,6 @@ public void visitMethodReferenceExpression(@Nonnull PsiMethodReferenceExpression }; } - @Override - @Nonnull - public String getGroupDisplayName() { - return InspectionLocalize.groupNamesProbableBugs().get(); - } - @Override @Nonnull public String getShortName() { 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 15fe3494d2..131a71d72a 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 @@ -39,6 +39,7 @@ import consulo.language.psi.search.ReferencesSearch; import consulo.language.psi.util.PsiTreeUtil; import consulo.language.util.IncorrectOperationException; +import consulo.localize.LocalizeValue; import consulo.logging.Logger; import consulo.project.Project; import consulo.ui.annotation.RequiredUIAccess; @@ -54,271 +55,223 @@ * @author max */ @ExtensionImpl -public class SameParameterValueInspection extends GlobalJavaInspectionTool -{ - private static final Logger LOG = Logger.getInstance(SameParameterValueInspection.class); +public class SameParameterValueInspection extends GlobalJavaInspectionTool { + private static final Logger LOG = Logger.getInstance(SameParameterValueInspection.class); - @Override - @Nullable - public CommonProblemDescriptor[] checkElement( - @Nonnull RefEntity refEntity, - @Nonnull AnalysisScope scope, - @Nonnull InspectionManager manager, - @Nonnull GlobalInspectionContext globalContext, - @Nonnull ProblemDescriptionsProcessor processor, - @Nonnull Object state - ) - { - ArrayList problems = null; - if (refEntity instanceof RefMethod refMethod) - { - if (refMethod.hasSuperMethods()) - { - return null; - } + @Override + @Nullable + public CommonProblemDescriptor[] checkElement( + @Nonnull RefEntity refEntity, + @Nonnull AnalysisScope scope, + @Nonnull InspectionManager manager, + @Nonnull GlobalInspectionContext globalContext, + @Nonnull ProblemDescriptionsProcessor processor, + @Nonnull Object state + ) { + ArrayList problems = null; + if (refEntity instanceof RefMethod refMethod) { + if (refMethod.hasSuperMethods()) { + return null; + } - if (refMethod.isEntry()) - { - return null; - } + if (refMethod.isEntry()) { + return null; + } - RefParameter[] parameters = refMethod.getParameters(); - for (RefParameter refParameter : parameters) - { - String value = refParameter.getActualValueIfSame(); - if (value != null) - { - 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 - )); - } - } - } + RefParameter[] parameters = refMethod.getParameters(); + for (RefParameter refParameter : parameters) { + String value = refParameter.getActualValueIfSame(); + if (value != null) { + 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 + )); + } + } + } - return problems == null ? null : problems.toArray(new CommonProblemDescriptor[problems.size()]); - } + return problems == null ? null : problems.toArray(new CommonProblemDescriptor[problems.size()]); + } - @Override - protected boolean queryExternalUsagesRequests( - final RefManager manager, final GlobalJavaInspectionContext globalContext, - final ProblemDescriptionsProcessor processor, Object state) - { - manager.iterate(new RefJavaVisitor() - { - @Override - 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) - { - globalContext.enqueueMethodUsagesProcessor(refMethod, psiReference -> { - processor.ignoreElement(refMethod); - return false; - }); - } - }); - } - } - }); + @Override + protected boolean queryExternalUsagesRequests( + final RefManager manager, final GlobalJavaInspectionContext globalContext, + final ProblemDescriptionsProcessor processor, Object state + ) { + manager.iterate(new RefJavaVisitor() { + @Override + 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) { + globalContext.enqueueMethodUsagesProcessor(refMethod, psiReference -> { + processor.ignoreElement(refMethod); + return false; + }); + } + }); + } + } + }); - return false; - } + return false; + } - @Override - @Nonnull - public String getDisplayName() - { - return InspectionLocalize.inspectionSameParameterDisplayName().get(); - } + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionLocalize.inspectionSameParameterDisplayName(); + } - @Override - @Nonnull - public String getGroupDisplayName() - { - return InspectionLocalize.groupNamesDeclarationRedundancy().get(); - } + @Nonnull + @Override + public LocalizeValue getGroupDisplayName() { + return InspectionLocalize.groupNamesDeclarationRedundancy(); + } - @Override - @Nonnull - public String getShortName() - { - return "SameParameterValue"; - } + @Override + @Nonnull + public String getShortName() { + return "SameParameterValue"; + } - @Override - @Nullable - public QuickFix getQuickFix(final String hint) - { - if (hint == null) - { - return null; - } - final 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); - return new InlineParameterValueFix(paramName, value); - } + @Override + @Nullable + public QuickFix getQuickFix(final String hint) { + if (hint == null) { + return null; + } + final 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); + return new InlineParameterValueFix(paramName, value); + } - @Override - @Nullable - public String getHint(@Nonnull final QuickFix fix) - { - final InlineParameterValueFix valueFix = (InlineParameterValueFix) fix; - return valueFix.getParamName() + " " + valueFix.getValue(); - } + @Override + @Nullable + public String getHint(@Nonnull final QuickFix fix) { + final InlineParameterValueFix valueFix = (InlineParameterValueFix) fix; + return valueFix.getParamName() + " " + valueFix.getValue(); + } - public static class InlineParameterValueFix implements LocalQuickFix - { - private final String myValue; - private final String myParameterName; + public static class InlineParameterValueFix implements LocalQuickFix { + private final String myValue; + private final String myParameterName; - public InlineParameterValueFix(final String parameterName, final String value) - { - myValue = value; - myParameterName = parameterName; - } + public InlineParameterValueFix(final String parameterName, final String value) { + myValue = value; + myParameterName = parameterName; + } - @Override - @Nonnull - public String getName() - { - return InspectionLocalize.inspectionSameParameterFixName(myParameterName, myValue).get(); - } + @Nonnull + @Override + public LocalizeValue getName() { + return InspectionLocalize.inspectionSameParameterFixName(myParameterName, myValue); + } - @Override - @Nonnull - public String getFamilyName() - { - return 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); + LOG.assertTrue(method != null); + PsiParameter parameter = PsiTreeUtil.getParentOfType(element, PsiParameter.class, false); + if (parameter == null) { + final PsiParameter[] parameters = method.getParameterList().getParameters(); + for (PsiParameter psiParameter : parameters) { + if (Comparing.strEqual(psiParameter.getName(), myParameterName)) { + parameter = psiParameter; + break; + } + } + } + if (parameter == null || !CommonRefactoringUtil.checkReadOnlyStatus(project, parameter)) { + return; + } - @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); - LOG.assertTrue(method != null); - PsiParameter parameter = PsiTreeUtil.getParentOfType(element, PsiParameter.class, false); - if (parameter == null) - { - final PsiParameter[] parameters = method.getParameterList().getParameters(); - for (PsiParameter psiParameter : parameters) - { - if (Comparing.strEqual(psiParameter.getName(), myParameterName)) - { - parameter = psiParameter; - break; - } - } - } - if (parameter == null || !CommonRefactoringUtil.checkReadOnlyStatus(project, parameter)) { - return; - } + final PsiExpression defToInline; + try { + defToInline = JavaPsiFacade.getInstance(project).getElementFactory().createExpressionFromText(myValue, parameter); + } + catch (IncorrectOperationException e) { + return; + } + final PsiParameter parameterToInline = parameter; + inlineSameParameterValue(method, parameterToInline, defToInline); + } - final PsiExpression defToInline; - try - { - defToInline = JavaPsiFacade.getInstance(project).getElementFactory().createExpressionFromText(myValue, parameter); - } - catch (IncorrectOperationException e) - { - return; - } - final 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(); - @RequiredUIAccess - public static void inlineSameParameterValue(final PsiMethod method, final PsiParameter parameter, final PsiExpression defToInline) - { - final Collection refsToInline = ReferencesSearch.search(parameter).findAll(); + method.getApplication().runWriteAction(() -> { + try { + PsiExpression[] exprs = new PsiExpression[refsToInline.size()]; + int idx = 0; + for (PsiReference reference : refsToInline) { + if (reference instanceof PsiJavaCodeReferenceElement javaCodeReferenceElement) { + exprs[idx++] = InlineUtil.inlineVariable(parameter, defToInline, javaCodeReferenceElement); + } + } - method.getApplication().runWriteAction(() -> { - try - { - PsiExpression[] exprs = new PsiExpression[refsToInline.size()]; - int idx = 0; - for (PsiReference reference : refsToInline) - { - if (reference instanceof PsiJavaCodeReferenceElement javaCodeReferenceElement) - { - exprs[idx++] = InlineUtil.inlineVariable(parameter, defToInline, javaCodeReferenceElement); - } - } + for (final PsiExpression expr : exprs) { + if (expr != null) { + InlineUtil.tryToInlineArrayCreationForVarargs(expr); + } + } + } + catch (IncorrectOperationException e) { + LOG.error(e); + } + }); - for (final PsiExpression expr : exprs) - { - if (expr != null) - { - InlineUtil.tryToInlineArrayCreationForVarargs(expr); - } - } - } - catch (IncorrectOperationException e) - { - LOG.error(e); - } - }); + removeParameter(method, parameter); + } - removeParameter(method, parameter); - } + public static void removeParameter(final PsiMethod method, final PsiParameter parameter) { + final PsiParameter[] parameters = method.getParameterList().getParameters(); + final List psiParameters = new ArrayList<>(); + int paramIdx = 0; + final String paramName = parameter.getName(); + for (PsiParameter param : parameters) { + if (!Comparing.strEqual(paramName, param.getName())) { + psiParameters.add(new ParameterInfoImpl(paramIdx, param.getName(), param.getType())); + } + paramIdx++; + } - public static void removeParameter(final PsiMethod method, final PsiParameter parameter) - { - final PsiParameter[] parameters = method.getParameterList().getParameters(); - final List psiParameters = new ArrayList<>(); - int paramIdx = 0; - final String paramName = parameter.getName(); - for (PsiParameter param : parameters) - { - if (!Comparing.strEqual(paramName, param.getName())) - { - psiParameters.add(new ParameterInfoImpl(paramIdx, param.getName(), param.getType())); - } - paramIdx++; - } + new ChangeSignatureProcessor( + method.getProject(), + method, + false, + null, + method.getName(), + method.getReturnType(), + psiParameters.toArray(new ParameterInfoImpl[psiParameters.size()]) + ).run(); + } - new ChangeSignatureProcessor( - method.getProject(), - method, - false, - null, - method.getName(), - method.getReturnType(), - psiParameters.toArray(new ParameterInfoImpl[psiParameters.size()]) - ).run(); - } + public String getValue() { + return myValue; + } - public String getValue() - { - return myValue; - } - - public String getParamName() - { - return myParameterName; - } - } + public String getParamName() { + return myParameterName; + } + } } diff --git a/plugin/src/main/java/com/intellij/java/impl/codeInspection/sameReturnValue/SameReturnValueInspection.java b/plugin/src/main/java/com/intellij/java/impl/codeInspection/sameReturnValue/SameReturnValueInspection.java index 74012de94b..1a9034f51e 100644 --- a/plugin/src/main/java/com/intellij/java/impl/codeInspection/sameReturnValue/SameReturnValueInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/codeInspection/sameReturnValue/SameReturnValueInspection.java @@ -35,110 +35,93 @@ * @author max */ @ExtensionImpl -public class SameReturnValueInspection extends GlobalJavaInspectionTool -{ - @Override - @Nullable - public CommonProblemDescriptor[] checkElement( - @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() || refMethod.hasSuperMethods()) - { - return null; - } +public class SameReturnValueInspection extends GlobalJavaInspectionTool { + @Override + @Nullable + public CommonProblemDescriptor[] checkElement( + @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() || refMethod.hasSuperMethods()) { + return null; + } - String returnValue = refMethod.getReturnValueIfSame(); - if (returnValue != null) - { - final LocalizeValue message; - if (refMethod.getDerivedMethods().isEmpty()) - { - message = InspectionLocalize.inspectionSameReturnValueProblemDescriptor("" + returnValue + ""); - } - else if (refMethod.hasBody()) - { - message = InspectionLocalize.inspectionSameReturnValueProblemDescriptor1("" + returnValue + ""); - } - else - { - message = InspectionLocalize.inspectionSameReturnValueProblemDescriptor2("" + returnValue + ""); - } + String returnValue = refMethod.getReturnValueIfSame(); + if (returnValue != null) { + final LocalizeValue message; + if (refMethod.getDerivedMethods().isEmpty()) { + message = InspectionLocalize.inspectionSameReturnValueProblemDescriptor("" + returnValue + ""); + } + else if (refMethod.hasBody()) { + message = InspectionLocalize.inspectionSameReturnValueProblemDescriptor1("" + returnValue + ""); + } + else { + message = InspectionLocalize.inspectionSameReturnValueProblemDescriptor2("" + returnValue + ""); + } - return new ProblemDescriptor[]{ - manager.createProblemDescriptor( - refMethod.getElement().getNavigationElement(), - message.get(), - false, - null, - ProblemHighlightType.GENERIC_ERROR_OR_WARNING - ) - }; - } - } + return new ProblemDescriptor[]{ + manager.createProblemDescriptor( + refMethod.getElement().getNavigationElement(), + message.get(), + false, + null, + ProblemHighlightType.GENERIC_ERROR_OR_WARNING + ) + }; + } + } - return null; - } + return null; + } - @Override - protected boolean queryExternalUsagesRequests( - final RefManager manager, - final GlobalJavaInspectionContext globalContext, - final ProblemDescriptionsProcessor processor, - Object state - ) - { - manager.iterate(new RefJavaVisitor() - { - @Override - 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) - { - globalContext.enqueueDerivedMethodsProcessor(refMethod, derivedMethod -> { - processor.ignoreElement(refMethod); - return false; - }); - } - }); - } - } - }); + @Override + protected boolean queryExternalUsagesRequests( + final RefManager manager, + final GlobalJavaInspectionContext globalContext, + final ProblemDescriptionsProcessor processor, + Object state + ) { + manager.iterate(new RefJavaVisitor() { + @Override + 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) { + globalContext.enqueueDerivedMethodsProcessor(refMethod, derivedMethod -> { + processor.ignoreElement(refMethod); + return false; + }); + } + }); + } + } + }); - return false; - } + return false; + } - @Override - @Nonnull - public String getDisplayName() - { - return InspectionLocalize.inspectionSameReturnValueDisplayName().get(); - } + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionLocalize.inspectionSameReturnValueDisplayName(); + } - @Override - @Nonnull - public String getGroupDisplayName() - { - return InspectionLocalize.groupNamesDeclarationRedundancy().get(); - } + @Nonnull + @Override + public LocalizeValue getGroupDisplayName() { + return InspectionLocalize.groupNamesDeclarationRedundancy(); + } - @Override - @Nonnull - public String getShortName() - { - return "SameReturnValue"; - } + @Override + @Nonnull + public String getShortName() { + return "SameReturnValue"; + } } diff --git a/plugin/src/main/java/com/intellij/java/impl/codeInspection/sillyAssignment/SillyAssignmentInspection.java b/plugin/src/main/java/com/intellij/java/impl/codeInspection/sillyAssignment/SillyAssignmentInspection.java index 0660594ea1..8773bcbcac 100644 --- a/plugin/src/main/java/com/intellij/java/impl/codeInspection/sillyAssignment/SillyAssignmentInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/codeInspection/sillyAssignment/SillyAssignmentInspection.java @@ -28,177 +28,196 @@ import consulo.language.psi.PsiElementVisitor; import consulo.language.psi.PsiManager; import consulo.language.psi.util.PsiTreeUtil; +import consulo.localize.LocalizeValue; import consulo.util.lang.Comparing; import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; -import org.jetbrains.annotations.NonNls; /** - * User: anna - * Date: 15-Nov-2005 + * @author anna + * @since 2005-11-15 */ @ExtensionImpl public class SillyAssignmentInspection extends BaseJavaLocalInspectionTool { - @Override - @Nonnull - public String getDisplayName() { - return InspectionLocalize.inspectionVariableAssignedToItselfDisplayName().get(); - } + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionLocalize.inspectionVariableAssignedToItselfDisplayName(); + } + + @Override + @Nonnull + public String getShortName() { + return "SillyAssignment"; + } + + @Override + public boolean isEnabledByDefault() { + return true; + } - @Override - @Nonnull - @NonNls - public String getShortName() { - return "SillyAssignment"; - } + @Override + @Nonnull + public PsiElementVisitor buildVisitorImpl( + @Nonnull final ProblemsHolder holder, + boolean isOnTheFly, + LocalInspectionToolSession session, + Object state + ) { + return new JavaElementVisitor() { - @Override - public boolean isEnabledByDefault() { - return true; - } + @Override + public void visitAssignmentExpression(@Nonnull PsiAssignmentExpression expression) { + checkSillyAssignment(expression, holder); + } - @Override - @Nonnull - public PsiElementVisitor buildVisitorImpl( - @Nonnull final ProblemsHolder holder, - boolean isOnTheFly, - LocalInspectionToolSession session, - Object state - ) { - return new JavaElementVisitor() { + @Override + public void visitReferenceExpression(@Nonnull PsiReferenceExpression expression) { + visitElement(expression); + } - @Override public void visitAssignmentExpression(@Nonnull PsiAssignmentExpression expression) { - checkSillyAssignment(expression, holder); - } + @Override + @RequiredReadAction + public void visitVariable(@Nonnull final PsiVariable variable) { + final PsiExpression initializer = PsiUtil.deparenthesizeExpression(variable.getInitializer()); + if (initializer instanceof PsiAssignmentExpression assignmentExpression) { + final PsiExpression lExpr = PsiUtil.deparenthesizeExpression(assignmentExpression.getLExpression()); + checkExpression(variable, lExpr); + } + else { + checkExpression(variable, initializer); + } + } - @Override - public void visitReferenceExpression(@Nonnull PsiReferenceExpression expression) { - visitElement(expression); - } + @RequiredReadAction + private void checkExpression(PsiVariable variable, PsiExpression expression) { + if (!(expression instanceof PsiReferenceExpression)) { + return; + } + final PsiReferenceExpression refExpr = (PsiReferenceExpression) expression; + final PsiExpression qualifier = refExpr.getQualifierExpression(); + if (qualifier == null || qualifier instanceof PsiThisExpression || qualifier instanceof PsiSuperExpression + || variable.hasModifierProperty(PsiModifier.STATIC)) { + if (refExpr.isReferenceTo(variable)) { + holder.registerProblem( + expression, + InspectionLocalize.assignmentToDeclaredVariableProblemDescriptor(variable.getName()).get(), + ProblemHighlightType.LIKE_UNUSED_SYMBOL + ); + } + } + } + }; + } - @Override - @RequiredReadAction - public void visitVariable(@Nonnull final PsiVariable variable) { - final PsiExpression initializer = PsiUtil.deparenthesizeExpression(variable.getInitializer()); - if (initializer instanceof PsiAssignmentExpression assignmentExpression) { - final PsiExpression lExpr = PsiUtil.deparenthesizeExpression(assignmentExpression.getLExpression()); - checkExpression(variable, lExpr); + private static void checkSillyAssignment(PsiAssignmentExpression assignment, ProblemsHolder holder) { + if (assignment.getOperationTokenType() != JavaTokenType.EQ) { + return; + } + PsiExpression lExpression = assignment.getLExpression(); + PsiExpression rExpression = assignment.getRExpression(); + if (rExpression == null) { + return; + } + lExpression = PsiUtil.deparenthesizeExpression(lExpression); + rExpression = PsiUtil.deparenthesizeExpression(rExpression); + if (!(lExpression instanceof PsiReferenceExpression)) { + return; + } + PsiReferenceExpression rRef; + if (rExpression instanceof PsiReferenceExpression rReferenceExpression) { + rRef = rReferenceExpression; + } + else if (rExpression instanceof PsiAssignmentExpression rAssignmentExpression) { + final PsiExpression assignee = PsiUtil.deparenthesizeExpression(rAssignmentExpression.getLExpression()); + if (assignee instanceof PsiReferenceExpression referenceExpressionAssignee) { + rRef = referenceExpressionAssignee; + } + else { + return; + } } else { - checkExpression(variable, initializer); + return; } - } - - @RequiredReadAction - private void checkExpression(PsiVariable variable, PsiExpression expression) { - if (!(expression instanceof PsiReferenceExpression)) { - return; - } - final PsiReferenceExpression refExpr = (PsiReferenceExpression)expression; - final PsiExpression qualifier = refExpr.getQualifierExpression(); - if (qualifier == null || qualifier instanceof PsiThisExpression || qualifier instanceof PsiSuperExpression - || variable.hasModifierProperty(PsiModifier.STATIC)) { - if (refExpr.isReferenceTo(variable)) { - holder.registerProblem( - expression, - InspectionLocalize.assignmentToDeclaredVariableProblemDescriptor(variable.getName()).get(), - ProblemHighlightType.LIKE_UNUSED_SYMBOL - ); - } - } - } - }; - } - - private static void checkSillyAssignment(PsiAssignmentExpression assignment, ProblemsHolder holder) { - if (assignment.getOperationTokenType() != JavaTokenType.EQ) return; - PsiExpression lExpression = assignment.getLExpression(); - PsiExpression rExpression = assignment.getRExpression(); - if (rExpression == null) return; - lExpression = PsiUtil.deparenthesizeExpression(lExpression); - rExpression = PsiUtil.deparenthesizeExpression(rExpression); - if (!(lExpression instanceof PsiReferenceExpression)) return; - PsiReferenceExpression rRef; - if (rExpression instanceof PsiReferenceExpression rReferenceExpression) { - rRef = rReferenceExpression; - } - else if (rExpression instanceof PsiAssignmentExpression rAssignmentExpression) { - final PsiExpression assignee = PsiUtil.deparenthesizeExpression(rAssignmentExpression.getLExpression()); - if (assignee instanceof PsiReferenceExpression referenceExpressionAssignee) { - rRef = referenceExpressionAssignee; - } - else { - return; - } - } - else { - return; - } - PsiReferenceExpression lRef = (PsiReferenceExpression)lExpression; - PsiManager manager = assignment.getManager(); - if (!sameInstanceReferences(lRef, rRef, manager)) { - return; - } - final PsiVariable variable = (PsiVariable)lRef.resolve(); - if (variable == null) { - return; + PsiReferenceExpression lRef = (PsiReferenceExpression) lExpression; + PsiManager manager = assignment.getManager(); + if (!sameInstanceReferences(lRef, rRef, manager)) { + return; + } + final PsiVariable variable = (PsiVariable) lRef.resolve(); + if (variable == null) { + return; + } + holder.registerProblem( + assignment, + InspectionLocalize.assignmentToItselfProblemDescriptor(variable.getName()).get(), + ProblemHighlightType.LIKE_UNUSED_SYMBOL + ); } - holder.registerProblem( - assignment, - InspectionLocalize.assignmentToItselfProblemDescriptor(variable.getName()).get(), - ProblemHighlightType.LIKE_UNUSED_SYMBOL - ); - } - /** - * @return true if both expressions resolve to the same variable/class or field in the same instance of the class - */ - @RequiredReadAction - private static boolean sameInstanceReferences( - @Nullable PsiJavaCodeReferenceElement lRef, - @Nullable PsiJavaCodeReferenceElement rRef, - PsiManager manager - ) { - if (lRef == null && rRef == null) return true; - if (lRef == null || rRef == null) return false; - PsiElement lResolved = lRef.resolve(); - PsiElement rResolved = rRef.resolve(); - if (!manager.areElementsEquivalent(lResolved, rResolved)) return false; - if (!(lResolved instanceof PsiVariable)) return false; - final PsiVariable variable = (PsiVariable)lResolved; - if (variable.hasModifierProperty(PsiModifier.STATIC)) return true; + /** + * @return true if both expressions resolve to the same variable/class or field in the same instance of the class + */ + @RequiredReadAction + private static boolean sameInstanceReferences( + @Nullable PsiJavaCodeReferenceElement lRef, + @Nullable PsiJavaCodeReferenceElement rRef, + PsiManager manager + ) { + if (lRef == null && rRef == null) { + return true; + } + if (lRef == null || rRef == null) { + return false; + } + PsiElement lResolved = lRef.resolve(); + PsiElement rResolved = rRef.resolve(); + if (!manager.areElementsEquivalent(lResolved, rResolved)) { + return false; + } + if (!(lResolved instanceof PsiVariable)) { + return false; + } + final PsiVariable variable = (PsiVariable) lResolved; + if (variable.hasModifierProperty(PsiModifier.STATIC)) { + return true; + } - final PsiElement lQualifier = lRef.getQualifier(); - final PsiElement rQualifier = rRef.getQualifier(); - if (lQualifier instanceof PsiJavaCodeReferenceElement lJavaRef && rQualifier instanceof PsiJavaCodeReferenceElement rJavaRef) { - return sameInstanceReferences(lJavaRef, rJavaRef, manager); - } + final PsiElement lQualifier = lRef.getQualifier(); + final PsiElement rQualifier = rRef.getQualifier(); + if (lQualifier instanceof PsiJavaCodeReferenceElement lJavaRef && rQualifier instanceof PsiJavaCodeReferenceElement rJavaRef) { + return sameInstanceReferences(lJavaRef, rJavaRef, manager); + } - if (Comparing.equal(lQualifier, rQualifier)) return true; - boolean lThis = lQualifier == null || lQualifier instanceof PsiThisExpression || lQualifier instanceof PsiSuperExpression; - boolean rThis = rQualifier == null || rQualifier instanceof PsiThisExpression || rQualifier instanceof PsiSuperExpression; - if (lThis && rThis) { - final PsiJavaCodeReferenceElement llQualifier = getQualifier(lQualifier); - final PsiJavaCodeReferenceElement rrQualifier = getQualifier(rQualifier); - return sameInstanceReferences(llQualifier, rrQualifier, manager); + if (Comparing.equal(lQualifier, rQualifier)) { + return true; + } + boolean lThis = lQualifier == null || lQualifier instanceof PsiThisExpression || lQualifier instanceof PsiSuperExpression; + boolean rThis = rQualifier == null || rQualifier instanceof PsiThisExpression || rQualifier instanceof PsiSuperExpression; + if (lThis && rThis) { + final PsiJavaCodeReferenceElement llQualifier = getQualifier(lQualifier); + final PsiJavaCodeReferenceElement rrQualifier = getQualifier(rQualifier); + return sameInstanceReferences(llQualifier, rrQualifier, manager); + } + return false; } - return false; - } - @RequiredReadAction - private static PsiJavaCodeReferenceElement getQualifier(PsiElement qualifier) { - if (qualifier instanceof PsiThisExpression thisExpression) { - final PsiJavaCodeReferenceElement thisQualifier = thisExpression.getQualifier(); - if (thisQualifier != null) { - final PsiClass innerMostClass = PsiTreeUtil.getParentOfType(thisQualifier, PsiClass.class); - if (innerMostClass == thisQualifier.resolve()) { - return null; - } - } - return thisQualifier; - } else if (qualifier != null) { - return ((PsiSuperExpression)qualifier).getQualifier(); + @RequiredReadAction + private static PsiJavaCodeReferenceElement getQualifier(PsiElement qualifier) { + if (qualifier instanceof PsiThisExpression thisExpression) { + final PsiJavaCodeReferenceElement thisQualifier = thisExpression.getQualifier(); + if (thisQualifier != null) { + final PsiClass innerMostClass = PsiTreeUtil.getParentOfType(thisQualifier, PsiClass.class); + if (innerMostClass == thisQualifier.resolve()) { + return null; + } + } + return thisQualifier; + } + else if (qualifier != null) { + return ((PsiSuperExpression) qualifier).getQualifier(); + } + return null; } - return null; - } } diff --git a/plugin/src/main/java/com/intellij/java/impl/codeInspection/suspiciousNameCombination/SuspiciousNameCombinationInspection.java b/plugin/src/main/java/com/intellij/java/impl/codeInspection/suspiciousNameCombination/SuspiciousNameCombinationInspection.java index b2078dc062..83b33beb9a 100644 --- a/plugin/src/main/java/com/intellij/java/impl/codeInspection/suspiciousNameCombination/SuspiciousNameCombinationInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/codeInspection/suspiciousNameCombination/SuspiciousNameCombinationInspection.java @@ -28,6 +28,7 @@ import consulo.language.psi.PsiElement; import consulo.language.psi.PsiElementVisitor; import consulo.language.psi.util.PsiTreeUtil; +import consulo.localize.LocalizeValue; import consulo.ui.ex.awt.AddEditDeleteListPanel; import consulo.ui.ex.awt.Messages; import consulo.ui.ex.awt.UIUtil; @@ -52,229 +53,237 @@ */ @ExtensionImpl public class SuspiciousNameCombinationInspection extends BaseLocalInspectionTool { - private final List myNameGroups = new ArrayList<>(); - private final Map myWordToGroupMap = new HashMap<>(); - @NonNls private static final String ELEMENT_GROUPS = "group"; - @NonNls private static final String ATTRIBUTE_NAMES = "names"; + private final List myNameGroups = new ArrayList<>(); + private final Map myWordToGroupMap = new HashMap<>(); + @NonNls + private static final String ELEMENT_GROUPS = "group"; + @NonNls + private static final String ATTRIBUTE_NAMES = "names"; - public SuspiciousNameCombinationInspection() { - addNameGroup("x,width,left,right"); - addNameGroup("y,height,top,bottom"); - } - - private void clearNameGroups() { - myNameGroups.clear(); - myWordToGroupMap.clear(); - } - - private void addNameGroup(@NonNls final String group) { - myNameGroups.add(group); - List words = StringUtil.split(group, ","); - for (String word: words) { - myWordToGroupMap.put(word.trim().toLowerCase(), group); + public SuspiciousNameCombinationInspection() { + addNameGroup("x,width,left,right"); + addNameGroup("y,height,top,bottom"); } - } - - @Override - public boolean isEnabledByDefault() { - return true; - } - - @Override - @Nonnull - public String getGroupDisplayName() { - return InspectionLocalize.groupNamesProbableBugs().get(); - } - @Override - @Nonnull - public String getDisplayName() { - return InspectionLocalize.suspiciousNameCombinationDisplayName().get(); - } - - @Override - @Nonnull - @NonNls - public String getShortName() { - return "SuspiciousNameCombination"; - } - - @Override - @Nonnull - public PsiElementVisitor buildVisitorImpl( - @Nonnull ProblemsHolder holder, - boolean isOnTheFly, - LocalInspectionToolSession session, - Object state - ) { - return new MyVisitor(holder); - } + private void clearNameGroups() { + myNameGroups.clear(); + myWordToGroupMap.clear(); + } - @Override @Nullable - public JComponent createOptionsPanel() { - return new MyOptionsPanel(); - } + private void addNameGroup(@NonNls final String group) { + myNameGroups.add(group); + List words = StringUtil.split(group, ","); + for (String word : words) { + myWordToGroupMap.put(word.trim().toLowerCase(), group); + } + } - @Override public void readSettings(@Nonnull Element node) throws InvalidDataException { - clearNameGroups(); - for (Object o: node.getChildren(ELEMENT_GROUPS)) { - Element e = (Element) o; - addNameGroup(e.getAttributeValue(ATTRIBUTE_NAMES)); + @Override + public boolean isEnabledByDefault() { + return true; } - } - @Override public void writeSettings(@Nonnull Element node) throws WriteExternalException { - for (String group: myNameGroups) { - Element e = new Element(ELEMENT_GROUPS); - node.addContent(e); - e.setAttribute(ATTRIBUTE_NAMES, group); + @Nonnull + @Override + public LocalizeValue getGroupDisplayName() { + return InspectionLocalize.groupNamesProbableBugs(); } - } - private class MyVisitor extends JavaElementVisitor { - private final ProblemsHolder myProblemsHolder; + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionLocalize.suspiciousNameCombinationDisplayName(); + } - public MyVisitor(final ProblemsHolder problemsHolder) { - myProblemsHolder = problemsHolder; + @Override + @Nonnull + @NonNls + public String getShortName() { + return "SuspiciousNameCombination"; } + @Override - @RequiredReadAction - public void visitVariable(PsiVariable variable) { - if (variable.hasInitializer()) { - PsiExpression expr = variable.getInitializer(); - if (expr instanceof PsiReferenceExpression refExpr) { - checkCombination(variable, variable.getName(), refExpr.getReferenceName(), "suspicious.name.assignment"); - } - } + @Nonnull + public PsiElementVisitor buildVisitorImpl( + @Nonnull ProblemsHolder holder, + boolean isOnTheFly, + LocalInspectionToolSession session, + Object state + ) { + return new MyVisitor(holder); } @Override - public void visitAssignmentExpression(PsiAssignmentExpression expression) { - PsiExpression lhs = expression.getLExpression(); - PsiExpression rhs = expression.getRExpression(); - if (lhs instanceof PsiReferenceExpression lhsExpr && rhs instanceof PsiReferenceExpression rhsExpr) { - checkCombination(lhsExpr, lhsExpr.getReferenceName(), rhsExpr.getReferenceName(), "suspicious.name.assignment"); - } + @Nullable + public JComponent createOptionsPanel() { + return new MyOptionsPanel(); } @Override - public void visitCallExpression(PsiCallExpression expression) { - final PsiMethod psiMethod = expression.resolveMethod(); - final PsiExpressionList argList = expression.getArgumentList(); - if (psiMethod != null && argList != null) { - final PsiExpression[] args = argList.getExpressions(); - final PsiParameter[] parameters = psiMethod.getParameterList().getParameters(); - for (int i = 0; i < parameters.length; i++) { - if (i >= args.length) break; - if (args[i] instanceof PsiReferenceExpression referenceExpression) { - // PsiParameter.getName() can be expensive for compiled class files, so check reference name before - // fetching parameter name - final String refName = referenceExpression.getReferenceName(); - if (findNameGroup(refName) != null) { - checkCombination(args[i], parameters[i].getName(), refName, "suspicious.name.parameter"); - } - } + public void readSettings(@Nonnull Element node) throws InvalidDataException { + clearNameGroups(); + for (Object o : node.getChildren(ELEMENT_GROUPS)) { + Element e = (Element) o; + addNameGroup(e.getAttributeValue(ATTRIBUTE_NAMES)); } - } } @Override - public void visitReturnStatement(final PsiReturnStatement statement) { - final PsiExpression returnValue = statement.getReturnValue(); - PsiMethod containingMethod = PsiTreeUtil.getParentOfType(returnValue, PsiMethod.class); - if (returnValue instanceof PsiReferenceExpression referenceExpression && containingMethod != null) { - final String refName = referenceExpression.getReferenceName(); - checkCombination(returnValue, containingMethod.getName(), refName, "suspicious.name.return"); - } + public void writeSettings(@Nonnull Element node) throws WriteExternalException { + for (String group : myNameGroups) { + Element e = new Element(ELEMENT_GROUPS); + node.addContent(e); + e.setAttribute(ATTRIBUTE_NAMES, group); + } } - private void checkCombination( - final PsiElement location, - @Nullable final String name, - @Nullable final String referenceName, - final String key - ) { - String nameGroup1 = findNameGroup(name); - String nameGroup2 = findNameGroup(referenceName); - if (nameGroup1 != null && nameGroup2 != null && !nameGroup1.equals(nameGroup2)) { - myProblemsHolder.registerProblem(location, JavaErrorBundle.message(key, referenceName, name)); - } - } + private class MyVisitor extends JavaElementVisitor { + private final ProblemsHolder myProblemsHolder; - @Nullable - private String findNameGroup(@Nullable final String name) { - if (name == null) { - return null; - } - String[] words = NameUtil.splitNameIntoWords(name); - String result = null; - for (String word: words) { - String group = myWordToGroupMap.get(word.toLowerCase()); - if (group != null) { - if (result == null) { - result = group; - } - else if (!result.equals(group)) { - result = null; - break; - } + public MyVisitor(final ProblemsHolder problemsHolder) { + myProblemsHolder = problemsHolder; } - } - return result; - } - } - private class MyOptionsPanel extends AddEditDeleteListPanel { + @Override + @RequiredReadAction + public void visitVariable(PsiVariable variable) { + if (variable.hasInitializer()) { + PsiExpression expr = variable.getInitializer(); + if (expr instanceof PsiReferenceExpression refExpr) { + checkCombination(variable, variable.getName(), refExpr.getReferenceName(), "suspicious.name.assignment"); + } + } + } - public MyOptionsPanel() { - super(InspectionLocalize.suspiciousNameCombinationOptionsTitle().get(), myNameGroups); - myListModel.addListDataListener(new ListDataListener() { @Override - public void intervalAdded(ListDataEvent e) { - saveChanges(); + public void visitAssignmentExpression(PsiAssignmentExpression expression) { + PsiExpression lhs = expression.getLExpression(); + PsiExpression rhs = expression.getRExpression(); + if (lhs instanceof PsiReferenceExpression lhsExpr && rhs instanceof PsiReferenceExpression rhsExpr) { + checkCombination(lhsExpr, lhsExpr.getReferenceName(), rhsExpr.getReferenceName(), "suspicious.name.assignment"); + } } @Override - public void intervalRemoved(ListDataEvent e) { - saveChanges(); + public void visitCallExpression(PsiCallExpression expression) { + final PsiMethod psiMethod = expression.resolveMethod(); + final PsiExpressionList argList = expression.getArgumentList(); + if (psiMethod != null && argList != null) { + final PsiExpression[] args = argList.getExpressions(); + final PsiParameter[] parameters = psiMethod.getParameterList().getParameters(); + for (int i = 0; i < parameters.length; i++) { + if (i >= args.length) { + break; + } + if (args[i] instanceof PsiReferenceExpression referenceExpression) { + // PsiParameter.getName() can be expensive for compiled class files, so check reference name before + // fetching parameter name + final String refName = referenceExpression.getReferenceName(); + if (findNameGroup(refName) != null) { + checkCombination(args[i], parameters[i].getName(), refName, "suspicious.name.parameter"); + } + } + } + } } @Override - public void contentsChanged(ListDataEvent e) { - saveChanges(); + public void visitReturnStatement(final PsiReturnStatement statement) { + final PsiExpression returnValue = statement.getReturnValue(); + PsiMethod containingMethod = PsiTreeUtil.getParentOfType(returnValue, PsiMethod.class); + if (returnValue instanceof PsiReferenceExpression referenceExpression && containingMethod != null) { + final String refName = referenceExpression.getReferenceName(); + checkCombination(returnValue, containingMethod.getName(), refName, "suspicious.name.return"); + } } - }); - } - @Override - protected String findItemToAdd() { - return Messages.showInputDialog( - this, - InspectionLocalize.suspiciousNameCombinationOptionsPrompt().get(), - InspectionLocalize.suspiciousNameCombinationAddTitile().get(), - UIUtil.getQuestionIcon(), - "", - null - ); - } + private void checkCombination( + final PsiElement location, + @Nullable final String name, + @Nullable final String referenceName, + final String key + ) { + String nameGroup1 = findNameGroup(name); + String nameGroup2 = findNameGroup(referenceName); + if (nameGroup1 != null && nameGroup2 != null && !nameGroup1.equals(nameGroup2)) { + myProblemsHolder.registerProblem(location, JavaErrorBundle.message(key, referenceName, name)); + } + } - @Override - protected String editSelectedItem(String inputValue) { - return Messages.showInputDialog( - this, - InspectionLocalize.suspiciousNameCombinationOptionsPrompt().get(), - InspectionLocalize.suspiciousNameCombinationEditTitle().get(), - UIUtil.getQuestionIcon(), - inputValue, - null - ); + @Nullable + private String findNameGroup(@Nullable final String name) { + if (name == null) { + return null; + } + String[] words = NameUtil.splitNameIntoWords(name); + String result = null; + for (String word : words) { + String group = myWordToGroupMap.get(word.toLowerCase()); + if (group != null) { + if (result == null) { + result = group; + } + else if (!result.equals(group)) { + result = null; + break; + } + } + } + return result; + } } - private void saveChanges() { - clearNameGroups(); - for (int i = 0; i < myListModel.getSize(); i++) { - addNameGroup(myListModel.getElementAt(i)); - } + private class MyOptionsPanel extends AddEditDeleteListPanel { + + public MyOptionsPanel() { + super(InspectionLocalize.suspiciousNameCombinationOptionsTitle().get(), myNameGroups); + myListModel.addListDataListener(new ListDataListener() { + @Override + public void intervalAdded(ListDataEvent e) { + saveChanges(); + } + + @Override + public void intervalRemoved(ListDataEvent e) { + saveChanges(); + } + + @Override + public void contentsChanged(ListDataEvent e) { + saveChanges(); + } + }); + } + + @Override + protected String findItemToAdd() { + return Messages.showInputDialog( + this, + InspectionLocalize.suspiciousNameCombinationOptionsPrompt().get(), + InspectionLocalize.suspiciousNameCombinationAddTitile().get(), + UIUtil.getQuestionIcon(), + "", + null + ); + } + + @Override + protected String editSelectedItem(String inputValue) { + return Messages.showInputDialog( + this, + InspectionLocalize.suspiciousNameCombinationOptionsPrompt().get(), + InspectionLocalize.suspiciousNameCombinationEditTitle().get(), + UIUtil.getQuestionIcon(), + inputValue, + null + ); + } + + private void saveChanges() { + clearNameGroups(); + for (int i = 0; i < myListModel.getSize(); i++) { + addNameGroup(myListModel.getElementAt(i)); + } + } } - } } diff --git a/plugin/src/main/java/com/intellij/java/impl/codeInspection/testOnly/TestOnlyInspection.java b/plugin/src/main/java/com/intellij/java/impl/codeInspection/testOnly/TestOnlyInspection.java index 35c1ef813d..7e3a4f64d4 100644 --- a/plugin/src/main/java/com/intellij/java/impl/codeInspection/testOnly/TestOnlyInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/codeInspection/testOnly/TestOnlyInspection.java @@ -38,88 +38,103 @@ @ExtensionImpl public class TestOnlyInspection extends BaseJavaLocalInspectionTool { - @Override - @Nonnull - public String getDisplayName() { - return InspectionLocalize.inspectionTestOnlyProblemsDisplayName().get(); - } + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionLocalize.inspectionTestOnlyProblemsDisplayName(); + } - @Override - @Nonnull - public String getShortName() { - return "TestOnlyProblems"; - } + @Override + @Nonnull + public String getShortName() { + return "TestOnlyProblems"; + } - @Override - @Nonnull - public String getGroupDisplayName() { - return "General"; - } + @Override + @Nonnull + public LocalizeValue getGroupDisplayName() { + return InspectionLocalize.inspectionGeneralToolsGroupName(); + } - @Override - @Nonnull - public PsiElementVisitor buildVisitorImpl( - @Nonnull final ProblemsHolder h, - boolean isOnTheFly, - LocalInspectionToolSession session, - Object state - ) { - return new JavaElementVisitor() { - @Override public void visitCallExpression(@Nonnull PsiCallExpression e) { - validate(e, h); - } - }; - } + @Override + @Nonnull + public PsiElementVisitor buildVisitorImpl( + @Nonnull final ProblemsHolder h, + boolean isOnTheFly, + LocalInspectionToolSession session, + Object state + ) { + return new JavaElementVisitor() { + @Override + public void visitCallExpression(@Nonnull PsiCallExpression e) { + validate(e, h); + } + }; + } - private void validate(PsiCallExpression e, ProblemsHolder h) { - if (!isTestOnlyMethodCalled(e)) return; - if (isInsideTestOnlyMethod(e)) return; - if (isInsideTestClass(e)) return; - if (isUnderTestSources(e)) return; + private void validate(PsiCallExpression e, ProblemsHolder h) { + if (!isTestOnlyMethodCalled(e)) { + return; + } + if (isInsideTestOnlyMethod(e)) { + return; + } + if (isInsideTestClass(e)) { + return; + } + if (isUnderTestSources(e)) { + return; + } - reportProblem(e, h); - } + reportProblem(e, h); + } - private boolean isTestOnlyMethodCalled(PsiCallExpression e) { - return isAnnotatedAsTestOnly(e.resolveMethod()); - } + private boolean isTestOnlyMethodCalled(PsiCallExpression e) { + return isAnnotatedAsTestOnly(e.resolveMethod()); + } - private boolean isInsideTestOnlyMethod(PsiCallExpression e) { - PsiMethod m = getTopLevelParentOfType(e, PsiMethod.class); - return isAnnotatedAsTestOnly(m); - } + private boolean isInsideTestOnlyMethod(PsiCallExpression e) { + PsiMethod m = getTopLevelParentOfType(e, PsiMethod.class); + return isAnnotatedAsTestOnly(m); + } - private static boolean isAnnotatedAsTestOnly(@Nullable PsiMethod m) { - if (m == null) return false; - return AnnotationUtil.isAnnotated(m, AnnotationUtil.TEST_ONLY, false, false) || - AnnotationUtil.isAnnotated(m, "com.google.common.annotations.VisibleForTesting", false, false); - } + private static boolean isAnnotatedAsTestOnly(@Nullable PsiMethod m) { + if (m == null) { + return false; + } + return AnnotationUtil.isAnnotated(m, AnnotationUtil.TEST_ONLY, false, false) || + AnnotationUtil.isAnnotated(m, "com.google.common.annotations.VisibleForTesting", false, false); + } - private boolean isInsideTestClass(PsiCallExpression e) { - PsiClass c = getTopLevelParentOfType(e, PsiClass.class); - return c != null && TestFrameworks.getInstance().isTestClass(c); - } + private boolean isInsideTestClass(PsiCallExpression e) { + PsiClass c = getTopLevelParentOfType(e, PsiClass.class); + return c != null && TestFrameworks.getInstance().isTestClass(c); + } - private T getTopLevelParentOfType(PsiElement e, Class c) { - T parent = PsiTreeUtil.getParentOfType(e, c); - if (parent == null) return null; + private T getTopLevelParentOfType(PsiElement e, Class c) { + T parent = PsiTreeUtil.getParentOfType(e, c); + if (parent == null) { + return null; + } - do { - T next = PsiTreeUtil.getParentOfType(parent, c); - if (next == null) return parent; - parent = next; + do { + T next = PsiTreeUtil.getParentOfType(parent, c); + if (next == null) { + return parent; + } + parent = next; + } + while (true); } - while (true); - } - private boolean isUnderTestSources(PsiCallExpression e) { - ProjectRootManager rm = ProjectRootManager.getInstance(e.getProject()); - VirtualFile f = e.getContainingFile().getVirtualFile(); - return f != null && rm.getFileIndex().isInTestSourceContent(f); - } + private boolean isUnderTestSources(PsiCallExpression e) { + ProjectRootManager rm = ProjectRootManager.getInstance(e.getProject()); + VirtualFile f = e.getContainingFile().getVirtualFile(); + return f != null && rm.getFileIndex().isInTestSourceContent(f); + } - private void reportProblem(PsiCallExpression e, ProblemsHolder h) { - LocalizeValue message = InspectionLocalize.inspectionTestOnlyProblemsTestOnlyMethodCall(); - h.registerProblem(e, message.get(), ProblemHighlightType.GENERIC_ERROR_OR_WARNING); - } + private void reportProblem(PsiCallExpression e, ProblemsHolder h) { + LocalizeValue message = InspectionLocalize.inspectionTestOnlyProblemsTestOnlyMethodCall(); + h.registerProblem(e, message.get(), ProblemHighlightType.GENERIC_ERROR_OR_WARNING); + } } diff --git a/plugin/src/main/java/com/intellij/java/impl/codeInspection/uncheckedWarnings/UncheckedWarningLocalInspectionBase.java b/plugin/src/main/java/com/intellij/java/impl/codeInspection/uncheckedWarnings/UncheckedWarningLocalInspectionBase.java index be1e26936b..663225c961 100644 --- a/plugin/src/main/java/com/intellij/java/impl/codeInspection/uncheckedWarnings/UncheckedWarningLocalInspectionBase.java +++ b/plugin/src/main/java/com/intellij/java/impl/codeInspection/uncheckedWarnings/UncheckedWarningLocalInspectionBase.java @@ -96,14 +96,14 @@ private static LocalQuickFix[] getChangeVariableTypeFixes( @Override @Nonnull - public String getGroupDisplayName() { - return ""; + public LocalizeValue getGroupDisplayName() { + return LocalizeValue.empty(); } @Override @Nonnull - public String getDisplayName() { - return InspectionLocalize.uncheckedWarning().get(); + public LocalizeValue getDisplayName() { + return InspectionLocalize.uncheckedWarning(); } @Nonnull diff --git a/plugin/src/main/java/com/intellij/java/impl/codeInspection/unnecessaryModuleDependency/UnnecessaryModuleDependencyInspection.java b/plugin/src/main/java/com/intellij/java/impl/codeInspection/unnecessaryModuleDependency/UnnecessaryModuleDependencyInspection.java index 9c89276884..14c603db91 100644 --- a/plugin/src/main/java/com/intellij/java/impl/codeInspection/unnecessaryModuleDependency/UnnecessaryModuleDependencyInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/codeInspection/unnecessaryModuleDependency/UnnecessaryModuleDependencyInspection.java @@ -26,157 +26,127 @@ 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; import java.util.Set; /** - * User: anna - * Date: 09-Jan-2006 + * @author anna + * @since 2006-01-09 */ @ExtensionImpl -public class UnnecessaryModuleDependencyInspection extends GlobalInspectionTool -{ - - @Nonnull - @Override - public HighlightDisplayLevel getDefaultLevel() - { - return HighlightDisplayLevel.WARNING; - } - - @Override - public boolean isEnabledByDefault() - { - return true; - } - - @Nullable - @Override - public Language getLanguage() - { - return JavaLanguage.INSTANCE; - } - - @Override - public RefGraphAnnotator getAnnotator(@Nonnull final RefManager refManager, @Nonnull Object state) - { - return new UnnecessaryModuleDependencyAnnotator(refManager); - } - - @Override - public CommonProblemDescriptor[] checkElement( - @Nonnull RefEntity refEntity, - @Nonnull AnalysisScope scope, - @Nonnull InspectionManager manager, - @Nonnull final GlobalInspectionContext globalContext, - @Nonnull Object state - ) - { - if(refEntity instanceof RefModule) - { - final RefModule refModule = (RefModule) refEntity; - final Module module = refModule.getModule(); - final Module[] declaredDependencies = ModuleRootManager.getInstance(module).getDependencies(); - List descriptors = new ArrayList<>(); - final Set modules = refModule.getUserData(UnnecessaryModuleDependencyAnnotator.DEPENDENCIES); - for(final Module dependency : declaredDependencies) - { - if(modules == null || !modules.contains(dependency)) - { - final CommonProblemDescriptor problemDescriptor; - if(scope.containsModule(dependency)) - { //external references are rejected -> annotator doesn't provide any information on them -> false positives - problemDescriptor = manager.createProblemDescriptor( - InspectionLocalize.unnecessaryModuleDependencyProblemDescriptor(module.getName(), dependency.getName()).get(), - new RemoveModuleDependencyFix(module, dependency) - ); - } - else - { - LocalizeValue message = InspectionLocalize.suspectedModuleDependencyProblemDescriptor( - module.getName(), - dependency.getName(), - scope.getDisplayName(), - dependency.getName() - ); - problemDescriptor = manager.createProblemDescriptor(message.get()); - } - descriptors.add(problemDescriptor); - } - } - return descriptors.isEmpty() ? null : descriptors.toArray(new CommonProblemDescriptor[descriptors.size()]); - } - return null; - } - - @Override - @Nonnull - public String getGroupDisplayName() - { - return InspectionLocalize.groupNamesDeclarationRedundancy().get(); - } - - @Override - @Nonnull - public String getDisplayName() - { - return InspectionLocalize.unnecessaryModuleDependencyDisplayName().get(); - } - - @Override - @Nonnull - @NonNls - public String getShortName() - { - return "UnnecessaryModuleDependencyInspection"; - } - - public static class RemoveModuleDependencyFix implements QuickFix - { - private final Module myModule; - private final Module myDependency; - - public RemoveModuleDependencyFix(Module module, Module dependency) - { - myModule = module; - myDependency = dependency; - } - - @Override - @Nonnull - public String getName() - { - return "Remove dependency"; - } - - @Override - @Nonnull - public String getFamilyName() - { - return getName(); - } - - @Override - @RequiredWriteAction - public void applyFix(@Nonnull Project project, @Nonnull CommonProblemDescriptor descriptor) - { - final ModifiableRootModel model = ModuleRootManager.getInstance(myModule).getModifiableModel(); - for(OrderEntry entry : model.getOrderEntries()) - { - if(entry instanceof ModuleOrderEntry) - { - final Module mDependency = ((ModuleOrderEntry) entry).getModule(); - if(Comparing.equal(mDependency, myDependency)) - { - model.removeOrderEntry(entry); - break; - } - } - } - model.commit(); - } - } +public class UnnecessaryModuleDependencyInspection extends GlobalInspectionTool { + + @Nonnull + @Override + public HighlightDisplayLevel getDefaultLevel() { + return HighlightDisplayLevel.WARNING; + } + + @Override + public boolean isEnabledByDefault() { + return true; + } + + @Nullable + @Override + public Language getLanguage() { + return JavaLanguage.INSTANCE; + } + + @Override + public RefGraphAnnotator getAnnotator(@Nonnull final RefManager refManager, @Nonnull Object state) { + return new UnnecessaryModuleDependencyAnnotator(refManager); + } + + @Override + public CommonProblemDescriptor[] checkElement( + @Nonnull RefEntity refEntity, + @Nonnull AnalysisScope scope, + @Nonnull InspectionManager manager, + @Nonnull final GlobalInspectionContext globalContext, + @Nonnull Object state + ) { + if (refEntity instanceof RefModule) { + final RefModule refModule = (RefModule) refEntity; + final Module module = refModule.getModule(); + final Module[] declaredDependencies = ModuleRootManager.getInstance(module).getDependencies(); + List descriptors = new ArrayList<>(); + final Set modules = refModule.getUserData(UnnecessaryModuleDependencyAnnotator.DEPENDENCIES); + for (final Module dependency : declaredDependencies) { + if (modules == null || !modules.contains(dependency)) { + final CommonProblemDescriptor problemDescriptor; + if (scope.containsModule(dependency)) { //external references are rejected -> annotator doesn't provide any information on them -> false positives + problemDescriptor = manager.createProblemDescriptor( + InspectionLocalize.unnecessaryModuleDependencyProblemDescriptor(module.getName(), dependency.getName()).get(), + new RemoveModuleDependencyFix(module, dependency) + ); + } + else { + LocalizeValue message = InspectionLocalize.suspectedModuleDependencyProblemDescriptor( + module.getName(), + dependency.getName(), + scope.getDisplayName(), + dependency.getName() + ); + problemDescriptor = manager.createProblemDescriptor(message.get()); + } + descriptors.add(problemDescriptor); + } + } + return descriptors.isEmpty() ? null : descriptors.toArray(new CommonProblemDescriptor[descriptors.size()]); + } + return null; + } + + @Nonnull + @Override + public LocalizeValue getGroupDisplayName() { + return InspectionLocalize.groupNamesDeclarationRedundancy(); + } + + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionLocalize.unnecessaryModuleDependencyDisplayName(); + } + + @Override + @Nonnull + public String getShortName() { + return "UnnecessaryModuleDependencyInspection"; + } + + public static class RemoveModuleDependencyFix implements QuickFix { + private final Module myModule; + private final Module myDependency; + + public RemoveModuleDependencyFix(Module module, Module dependency) { + myModule = module; + myDependency = dependency; + } + + @Nonnull + @Override + public LocalizeValue getName() { + return LocalizeValue.localizeTODO("Remove dependency"); + } + + @Override + @RequiredWriteAction + public void applyFix(@Nonnull Project project, @Nonnull CommonProblemDescriptor descriptor) { + final ModifiableRootModel model = ModuleRootManager.getInstance(myModule).getModifiableModel(); + for (OrderEntry entry : model.getOrderEntries()) { + if (entry instanceof ModuleOrderEntry) { + final Module mDependency = ((ModuleOrderEntry) entry).getModule(); + if (Comparing.equal(mDependency, myDependency)) { + model.removeOrderEntry(entry); + break; + } + } + } + model.commit(); + } + } } 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 41c4c03cba..4b771248cd 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 @@ -39,6 +39,7 @@ import consulo.language.psi.scope.GlobalSearchScope; import consulo.language.psi.util.PsiTreeUtil; import consulo.language.util.IncorrectOperationException; +import consulo.localize.LocalizeValue; import consulo.logging.Logger; import consulo.project.Project; import consulo.util.collection.BidirectionalMap; @@ -55,356 +56,294 @@ * @author max */ @ExtensionImpl -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 - public CommonProblemDescriptor[] checkElement( - @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() || refMethod.hasSuperMethods() || refMethod.isEntry()) { - return null; - } - - PsiClass[] unThrown = refMethod.getUnThrownExceptions(); - if (unThrown == null) - { - return null; - } - - PsiMethod psiMethod = (PsiMethod) refMethod.getElement(); - PsiClassType[] throwsList = psiMethod.getThrowsList().getReferencedTypes(); - PsiJavaCodeReferenceElement[] throwsRefs = psiMethod.getThrowsList().getReferenceElements(); - ArrayList problems = null; - - final 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]; - if (ExceptionUtil.isUncheckedException(throwsType) || declaredInRemotableMethod(psiMethod, throwsType)) { - continue; - } - - for (PsiClass s : unThrown) - { - final 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 - )); - } - else if (!refMethod.getDerivedMethods().isEmpty()) - { - problems.add(manager.createProblemDescriptor( - throwsRef, - InspectionLocalize.inspectionRedundantThrowsProblemDescriptor1("#ref").get(), - getFix(processor, throwsClassName), - ProblemHighlightType.LIKE_UNUSED_SYMBOL, - false - )); - } - else - { - problems.add(manager.createProblemDescriptor( - throwsRef, - InspectionLocalize.inspectionRedundantThrowsProblemDescriptor2("#ref").get(), - getFix(processor, throwsClassName), - ProblemHighlightType.LIKE_UNUSED_SYMBOL, - false - )); - } - } - } - } - - if (problems != null) - { - return problems.toArray(new ProblemDescriptorBase[problems.size()]); - } - } - - return null; - } - - private static boolean declaredInRemotableMethod(final PsiMethod psiMethod, final PsiClassType throwsType) - { - if (!throwsType.equalsToText("java.rmi.RemoteException")) - { - return false; - } - PsiClass aClass = psiMethod.getContainingClass(); - if (aClass == null) - { - return false; - } - PsiClass remote = - JavaPsiFacade.getInstance(aClass.getProject()).findClass("java.rmi.Remote", GlobalSearchScope.allScope(aClass.getProject())); - return remote != null && aClass.isInheritor(remote, true); - } - - - @Override - protected boolean queryExternalUsagesRequests( - final RefManager manager, final GlobalJavaInspectionContext globalContext, - final ProblemDescriptionsProcessor processor, Object state) - { - manager.iterate(new RefJavaVisitor() - { - @Override - public void visitElement(@Nonnull RefEntity refEntity) - { - if (processor.getDescriptions(refEntity) != null) - { - refEntity.accept(new RefJavaVisitor() - { - @Override - public void visitMethod(@Nonnull final RefMethod refMethod) - { - globalContext.enqueueDerivedMethodsProcessor(refMethod, derivedMethod -> { - processor.ignoreElement(refMethod); - return true; - }); - } - }); - } - } - }); - - return false; - } - - @Override - @Nonnull - public String getDisplayName() - { - return InspectionLocalize.inspectionRedundantThrowsDisplayName().get(); - } - - @Override - @Nonnull - public String getGroupDisplayName() - { - return InspectionLocalize.groupNamesDeclarationRedundancy().get(); - } - - @Override - @Nonnull - public String getShortName() - { - return SHORT_NAME; - } - - private LocalQuickFix getFix(final ProblemDescriptionsProcessor processor, final String hint) - { - QuickFix fix = myQuickFixes.get(hint); - if (fix == null) - { - fix = new MyQuickFix(processor, hint); - if (hint != null) - { - myQuickFixes.put(hint, fix); - } - } - return (LocalQuickFix) fix; - } - - - @Override - @Nullable - public QuickFix getQuickFix(String hint) - { - return getFix(null, hint); - } - - @Override - @Nullable - public String getHint(@Nonnull final QuickFix fix) - { - final List hints = myQuickFixes.getKeysByValue(fix); - LOG.assertTrue(hints != null && hints.size() == 1); - return hints.get(0); - } - - private static class MyQuickFix implements LocalQuickFix - { - private final ProblemDescriptionsProcessor myProcessor; - private final String myHint; - - public MyQuickFix(final ProblemDescriptionsProcessor processor, final String hint) - { - myProcessor = processor; - myHint = hint; - } - - @Override - @Nonnull - public String getName() - { - return InspectionLocalize.inspectionRedundantThrowsRemoveQuickfix().get(); - } - - @Override - @RequiredWriteAction - public void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor descriptor) - { - if (myProcessor != null) - { - RefElement refElement = (RefElement) myProcessor.getElement(descriptor); - if (refElement instanceof RefMethod refMethod && refElement.isValid()) - { - final CommonProblemDescriptor[] problems = myProcessor.getDescriptions(refMethod); - if (problems != null) - { - removeExcessiveThrows(refMethod, null, problems); - } - } - } - else - { - final PsiMethod psiMethod = PsiTreeUtil.getParentOfType(descriptor.getPsiElement(), PsiMethod.class); - if (psiMethod != null) - { - removeExcessiveThrows(null, psiMethod, new CommonProblemDescriptor[]{descriptor}); - } - } - } - - @Override - @Nonnull - public String getFamilyName() - { - return getName(); - } - - @RequiredReadAction - private void removeExcessiveThrows( - @Nullable RefMethod refMethod, - @Nullable final PsiModifierListOwner element, - final CommonProblemDescriptor[] problems - ) - { - try - { - @Nullable final PsiMethod psiMethod; - if (element == null) - { - LOG.assertTrue(refMethod != null); - psiMethod = (PsiMethod) refMethod.getElement(); - } - else - { - psiMethod = (PsiMethod) element; - } - if (psiMethod == null) - { - return; //invalid refMethod - } - final Project project = psiMethod.getProject(); - final PsiManager psiManager = PsiManager.getInstance(project); - final List refsToDelete = new ArrayList<>(); - for (CommonProblemDescriptor problem : problems) - { - final PsiElement psiElement = ((ProblemDescriptor) problem).getPsiElement(); - if (psiElement instanceof PsiJavaCodeReferenceElement classRef) - { - final 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(); - for (PsiClassType classType : classTypes) - { - final String text = classType.getClassName(); - if (Comparing.strEqual(myHint, text)) - { - removeException(refMethod, classType, refsToDelete, psiMethod); - break; - } - } - } - } - - //check read-only status for derived methods - if (!FileModificationService.getInstance().preparePsiElementsForWrite(refsToDelete)) - { - return; - } - - for (final PsiJavaCodeReferenceElement aRefsToDelete : refsToDelete) - { - aRefsToDelete.delete(); - } - } - catch (IncorrectOperationException e) - { - LOG.error(e); - } - } - - private static void removeException(final RefMethod refMethod, - final PsiType exceptionType, - final List refsToDelete, - final PsiMethod psiMethod) - { - PsiManager psiManager = psiMethod.getManager(); - - PsiJavaCodeReferenceElement[] refs = psiMethod.getThrowsList().getReferenceElements(); - for (PsiJavaCodeReferenceElement ref : refs) - { - PsiType refType = JavaPsiFacade.getInstance(psiManager.getProject()).getElementFactory().createType(ref); - if (exceptionType.isAssignableFrom(refType)) - { - refsToDelete.add(ref); - } - } - - if (refMethod != null) - { - for (RefMethod refDerived : refMethod.getDerivedMethods()) - { - removeException(refDerived, exceptionType, refsToDelete, (PsiMethod) refDerived.getElement()); - } - } - else - { - final Query> query = AllOverridingMethodsSearch.search(psiMethod.getContainingClass()); - query.forEach(pair -> { - if (pair.first == psiMethod) - { - removeException(null, exceptionType, refsToDelete, pair.second); - } - return true; - }); - } - } - } +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 + public CommonProblemDescriptor[] checkElement( + @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() || refMethod.hasSuperMethods() || refMethod.isEntry()) { + return null; + } + + PsiClass[] unThrown = refMethod.getUnThrownExceptions(); + if (unThrown == null) { + return null; + } + + PsiMethod psiMethod = (PsiMethod) refMethod.getElement(); + PsiClassType[] throwsList = psiMethod.getThrowsList().getReferencedTypes(); + PsiJavaCodeReferenceElement[] throwsRefs = psiMethod.getThrowsList().getReferenceElements(); + ArrayList problems = null; + + final 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]; + if (ExceptionUtil.isUncheckedException(throwsType) || declaredInRemotableMethod(psiMethod, throwsType)) { + continue; + } + + for (PsiClass s : unThrown) { + final 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 + )); + } + else if (!refMethod.getDerivedMethods().isEmpty()) { + problems.add(manager.createProblemDescriptor( + throwsRef, + InspectionLocalize.inspectionRedundantThrowsProblemDescriptor1("#ref").get(), + getFix(processor, throwsClassName), + ProblemHighlightType.LIKE_UNUSED_SYMBOL, + false + )); + } + else { + problems.add(manager.createProblemDescriptor( + throwsRef, + InspectionLocalize.inspectionRedundantThrowsProblemDescriptor2("#ref").get(), + getFix(processor, throwsClassName), + ProblemHighlightType.LIKE_UNUSED_SYMBOL, + false + )); + } + } + } + } + + if (problems != null) { + return problems.toArray(new ProblemDescriptorBase[problems.size()]); + } + } + + return null; + } + + private static boolean declaredInRemotableMethod(final PsiMethod psiMethod, final PsiClassType throwsType) { + if (!throwsType.equalsToText("java.rmi.RemoteException")) { + return false; + } + PsiClass aClass = psiMethod.getContainingClass(); + if (aClass == null) { + return false; + } + PsiClass remote = + JavaPsiFacade.getInstance(aClass.getProject()).findClass("java.rmi.Remote", GlobalSearchScope.allScope(aClass.getProject())); + return remote != null && aClass.isInheritor(remote, true); + } + + + @Override + protected boolean queryExternalUsagesRequests( + final RefManager manager, final GlobalJavaInspectionContext globalContext, + final ProblemDescriptionsProcessor processor, Object state + ) { + manager.iterate(new RefJavaVisitor() { + @Override + public void visitElement(@Nonnull RefEntity refEntity) { + if (processor.getDescriptions(refEntity) != null) { + refEntity.accept(new RefJavaVisitor() { + @Override + public void visitMethod(@Nonnull final RefMethod refMethod) { + globalContext.enqueueDerivedMethodsProcessor(refMethod, derivedMethod -> { + processor.ignoreElement(refMethod); + return true; + }); + } + }); + } + } + }); + + return false; + } + + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionLocalize.inspectionRedundantThrowsDisplayName(); + } + + @Nonnull + @Override + public LocalizeValue getGroupDisplayName() { + return InspectionLocalize.groupNamesDeclarationRedundancy(); + } + + @Override + @Nonnull + public String getShortName() { + return SHORT_NAME; + } + + private LocalQuickFix getFix(final ProblemDescriptionsProcessor processor, final String hint) { + QuickFix fix = myQuickFixes.get(hint); + if (fix == null) { + fix = new MyQuickFix(processor, hint); + if (hint != null) { + myQuickFixes.put(hint, fix); + } + } + return (LocalQuickFix) fix; + } + + + @Override + @Nullable + public QuickFix getQuickFix(String hint) { + return getFix(null, hint); + } + + @Override + @Nullable + public String getHint(@Nonnull final QuickFix fix) { + final List hints = myQuickFixes.getKeysByValue(fix); + LOG.assertTrue(hints != null && hints.size() == 1); + return hints.get(0); + } + + private static class MyQuickFix implements LocalQuickFix { + private final ProblemDescriptionsProcessor myProcessor; + private final String myHint; + + public MyQuickFix(final ProblemDescriptionsProcessor processor, final String hint) { + myProcessor = processor; + myHint = hint; + } + + @Nonnull + @Override + public LocalizeValue getName() { + return InspectionLocalize.inspectionRedundantThrowsRemoveQuickfix(); + } + + @Override + @RequiredWriteAction + public void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor descriptor) { + if (myProcessor != null) { + RefElement refElement = (RefElement) myProcessor.getElement(descriptor); + if (refElement instanceof RefMethod refMethod && refElement.isValid()) { + final CommonProblemDescriptor[] problems = myProcessor.getDescriptions(refMethod); + if (problems != null) { + removeExcessiveThrows(refMethod, null, problems); + } + } + } + else { + final PsiMethod psiMethod = PsiTreeUtil.getParentOfType(descriptor.getPsiElement(), PsiMethod.class); + if (psiMethod != null) { + removeExcessiveThrows(null, psiMethod, new CommonProblemDescriptor[]{descriptor}); + } + } + } + + @RequiredReadAction + private void removeExcessiveThrows( + @Nullable RefMethod refMethod, + @Nullable final PsiModifierListOwner element, + final CommonProblemDescriptor[] problems + ) { + try { + @Nullable final PsiMethod psiMethod; + if (element == null) { + LOG.assertTrue(refMethod != null); + psiMethod = (PsiMethod) refMethod.getElement(); + } + else { + psiMethod = (PsiMethod) element; + } + if (psiMethod == null) { + return; //invalid refMethod + } + final Project project = psiMethod.getProject(); + final PsiManager psiManager = PsiManager.getInstance(project); + final List refsToDelete = new ArrayList<>(); + for (CommonProblemDescriptor problem : problems) { + final PsiElement psiElement = ((ProblemDescriptor) problem).getPsiElement(); + if (psiElement instanceof PsiJavaCodeReferenceElement classRef) { + final 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(); + for (PsiClassType classType : classTypes) { + final String text = classType.getClassName(); + if (Comparing.strEqual(myHint, text)) { + removeException(refMethod, classType, refsToDelete, psiMethod); + break; + } + } + } + } + + //check read-only status for derived methods + if (!FileModificationService.getInstance().preparePsiElementsForWrite(refsToDelete)) { + return; + } + + for (final PsiJavaCodeReferenceElement aRefsToDelete : refsToDelete) { + aRefsToDelete.delete(); + } + } + catch (IncorrectOperationException e) { + LOG.error(e); + } + } + + private static void removeException( + final RefMethod refMethod, + final PsiType exceptionType, + final List refsToDelete, + final PsiMethod psiMethod + ) { + PsiManager psiManager = psiMethod.getManager(); + + PsiJavaCodeReferenceElement[] refs = psiMethod.getThrowsList().getReferenceElements(); + for (PsiJavaCodeReferenceElement ref : refs) { + PsiType refType = JavaPsiFacade.getInstance(psiManager.getProject()).getElementFactory().createType(ref); + if (exceptionType.isAssignableFrom(refType)) { + refsToDelete.add(ref); + } + } + + if (refMethod != null) { + for (RefMethod refDerived : refMethod.getDerivedMethods()) { + removeException(refDerived, exceptionType, refsToDelete, (PsiMethod) refDerived.getElement()); + } + } + else { + final Query> query = AllOverridingMethodsSearch.search(psiMethod.getContainingClass()); + query.forEach(pair -> { + if (pair.first == psiMethod) { + removeException(null, exceptionType, refsToDelete, pair.second); + } + return true; + }); + } + } + } } 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 b18d6af57d..ae541ae101 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 @@ -29,6 +29,7 @@ import consulo.language.editor.inspection.scheme.InspectionManager; import consulo.language.psi.PsiFile; import consulo.language.psi.PsiManager; +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; import org.jetbrains.annotations.NonNls; @@ -39,108 +40,129 @@ /** * @author anna - * @since 15-Nov-2005 + * @since 2005-11-15 */ @ExtensionImpl -public class RedundantThrowsDeclaration extends BaseJavaBatchLocalInspectionTool -{ - @Override - @Nonnull - public String getGroupDisplayName() { - return InspectionLocalize.groupNamesDeclarationRedundancy().get(); - } - - @Override - @Nonnull - public String getDisplayName() { - return InspectionLocalize.redundantThrowsDeclaration().get(); - } +public class RedundantThrowsDeclaration extends BaseJavaBatchLocalInspectionTool { + @Nonnull + @Override + public LocalizeValue getGroupDisplayName() { + return InspectionLocalize.groupNamesDeclarationRedundancy(); + } - @Override - @Nonnull - @NonNls - public String getShortName() { - return "RedundantThrowsDeclaration"; - } + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionLocalize.redundantThrowsDeclaration(); + } - @Override - @Nullable - public ProblemDescriptor[] checkFile(@Nonnull PsiFile file, @Nonnull final InspectionManager manager, final boolean isOnTheFly, Object state) { - final Set problems = new HashSet<>(); - file.accept(new JavaRecursiveElementWalkingVisitor() { - @Override public void visitReferenceElement(@Nonnull PsiJavaCodeReferenceElement reference) { - final ProblemDescriptor descriptor = checkExceptionsNeverThrown(reference, manager, isOnTheFly); - if (descriptor != null) { - problems.add(descriptor); - } - } + @Override + @Nonnull + @NonNls + public String getShortName() { + return "RedundantThrowsDeclaration"; + } - }); - return problems.isEmpty() ? null : problems.toArray(new ProblemDescriptor[problems.size()]); - } + @Override + @Nullable + public ProblemDescriptor[] checkFile( + @Nonnull PsiFile file, + @Nonnull final InspectionManager manager, + final boolean isOnTheFly, + Object state + ) { + final Set problems = new HashSet<>(); + file.accept(new JavaRecursiveElementWalkingVisitor() { + @Override + public void visitReferenceElement(@Nonnull PsiJavaCodeReferenceElement reference) { + final ProblemDescriptor descriptor = checkExceptionsNeverThrown(reference, manager, isOnTheFly); + if (descriptor != null) { + problems.add(descriptor); + } + } - private static ProblemDescriptor checkExceptionsNeverThrown( - PsiJavaCodeReferenceElement referenceElement, - InspectionManager inspectionManager, - boolean onTheFly - ) { - if (!(referenceElement.getParent() instanceof PsiReferenceList)) { - return null; - } - PsiReferenceList referenceList = (PsiReferenceList)referenceElement.getParent(); - if (!(referenceList.getParent() instanceof PsiMethod)) { - return null; - } - PsiMethod method = (PsiMethod)referenceList.getParent(); - if (referenceList != method.getThrowsList()) { - return null; - } - PsiClass containingClass = method.getContainingClass(); - if (containingClass == null) { - return null; + }); + return problems.isEmpty() ? null : problems.toArray(new ProblemDescriptor[problems.size()]); } - PsiManager manager = referenceElement.getManager(); - PsiClassType exceptionType = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory().createType(referenceElement); - if (ExceptionUtil.isUncheckedExceptionOrSuperclass(exceptionType)) return null; + private static ProblemDescriptor checkExceptionsNeverThrown( + PsiJavaCodeReferenceElement referenceElement, + InspectionManager inspectionManager, + boolean onTheFly + ) { + if (!(referenceElement.getParent() instanceof PsiReferenceList)) { + return null; + } + PsiReferenceList referenceList = (PsiReferenceList) referenceElement.getParent(); + if (!(referenceList.getParent() instanceof PsiMethod)) { + return null; + } + PsiMethod method = (PsiMethod) referenceList.getParent(); + if (referenceList != method.getThrowsList()) { + return null; + } + PsiClass containingClass = method.getContainingClass(); + if (containingClass == null) { + return null; + } - PsiCodeBlock body = method.getBody(); - if (body == null) return null; + PsiManager manager = referenceElement.getManager(); + PsiClassType exceptionType = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory().createType(referenceElement); + if (ExceptionUtil.isUncheckedExceptionOrSuperclass(exceptionType)) { + return null; + } - PsiModifierList modifierList = method.getModifierList(); - if (!modifierList.hasModifierProperty(PsiModifier.PRIVATE) - && !modifierList.hasModifierProperty(PsiModifier.STATIC) - && !modifierList.hasModifierProperty(PsiModifier.FINAL) - && !method.isConstructor() - && !(containingClass instanceof PsiAnonymousClass) - && !containingClass.hasModifierProperty(PsiModifier.FINAL)) { - return null; - } + PsiCodeBlock body = method.getBody(); + if (body == null) { + return null; + } - Collection types = ExceptionUtil.collectUnhandledExceptions(body, method); - Collection unhandled = new HashSet<>(types); - if (method.isConstructor()) { - // 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)) continue; - PsiExpression initializer = field.getInitializer(); - if (initializer == null) continue; - unhandled.addAll(ExceptionUtil.collectUnhandledExceptions(initializer, field)); - } - } + PsiModifierList modifierList = method.getModifierList(); + if (!modifierList.hasModifierProperty(PsiModifier.PRIVATE) + && !modifierList.hasModifierProperty(PsiModifier.STATIC) + && !modifierList.hasModifierProperty(PsiModifier.FINAL) + && !method.isConstructor() + && !(containingClass instanceof PsiAnonymousClass) + && !containingClass.hasModifierProperty(PsiModifier.FINAL)) { + return null; + } - for (PsiClassType unhandledException : unhandled) { - if (unhandledException.isAssignableFrom(exceptionType) || exceptionType.isAssignableFrom(unhandledException)) { - return null; - } - } + Collection types = ExceptionUtil.collectUnhandledExceptions(body, method); + Collection unhandled = new HashSet<>(types); + if (method.isConstructor()) { + // 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)) { + continue; + } + PsiExpression initializer = field.getInitializer(); + if (initializer == null) { + continue; + } + unhandled.addAll(ExceptionUtil.collectUnhandledExceptions(initializer, field)); + } + } - if (JavaHighlightUtil.isSerializationRelatedMethod(method, containingClass)) return null; + for (PsiClassType unhandledException : unhandled) { + if (unhandledException.isAssignableFrom(exceptionType) || exceptionType.isAssignableFrom(unhandledException)) { + 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); - } + if (JavaHighlightUtil.isSerializationRelatedMethod(method, containingClass)) { + 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 + ); + } } diff --git a/plugin/src/main/java/com/intellij/java/impl/codeInspection/varScopeCanBeNarrowed/ParameterCanBeLocalInspection.java b/plugin/src/main/java/com/intellij/java/impl/codeInspection/varScopeCanBeNarrowed/ParameterCanBeLocalInspection.java index 289ec2ac14..314d464c2d 100644 --- a/plugin/src/main/java/com/intellij/java/impl/codeInspection/varScopeCanBeNarrowed/ParameterCanBeLocalInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/codeInspection/varScopeCanBeNarrowed/ParameterCanBeLocalInspection.java @@ -30,11 +30,11 @@ import consulo.language.editor.inspection.scheme.InspectionManager; import consulo.language.psi.PsiElement; import consulo.language.psi.PsiReference; +import consulo.localize.LocalizeValue; import consulo.project.Project; import consulo.usage.UsageInfo; import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; -import org.jetbrains.annotations.NonNls; import java.util.*; import java.util.function.Function; @@ -44,170 +44,176 @@ */ @ExtensionImpl public class ParameterCanBeLocalInspection extends BaseJavaLocalInspectionTool { - @NonNls - public static final String SHORT_NAME = "ParameterCanBeLocal"; - - @Override - @Nonnull - public String getGroupDisplayName() { - return InspectionLocalize.groupNamesClassStructure().get(); - } - - @Override - public boolean isEnabledByDefault() { - return true; - } - - @Override - @Nonnull - public String getDisplayName() { - return InspectionLocalize.inspectionParameterCanBeLocalDisplayName().get(); - } - - @Override - @Nonnull - public String getShortName() { - return SHORT_NAME; - } - - @Override - @RequiredReadAction - public ProblemDescriptor[] checkMethod(@Nonnull PsiMethod method, @Nonnull InspectionManager manager, boolean isOnTheFly, Object state) { - final Collection parameters = filterFinal(method.getParameterList().getParameters()); - final PsiCodeBlock body = method.getBody(); - if (body == null || parameters.isEmpty() || isOverrides(method)) { - return ProblemDescriptor.EMPTY_ARRAY; - } + public static final String SHORT_NAME = "ParameterCanBeLocal"; - final List result = new ArrayList<>(); - for (PsiParameter parameter : getWriteBeforeRead(parameters, body)) { - final PsiIdentifier identifier = parameter.getNameIdentifier(); - if (identifier != null && identifier.isPhysical()) { - result.add(createProblem(manager, identifier, isOnTheFly)); - } + @Nonnull + @Override + public LocalizeValue getGroupDisplayName() { + return InspectionLocalize.groupNamesClassStructure(); } - return result.toArray(new ProblemDescriptor[result.size()]); - } - - @Nonnull - private static List filterFinal(PsiParameter[] parameters) { - final List result = new ArrayList<>(parameters.length); - for (PsiParameter parameter : parameters) { - if (!parameter.hasModifierProperty(PsiModifier.FINAL)) { - result.add(parameter); - } + + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionLocalize.inspectionParameterCanBeLocalDisplayName(); } - return result; - } - - - @Nonnull - private static ProblemDescriptor createProblem( - @Nonnull InspectionManager manager, - @Nonnull PsiIdentifier identifier, - boolean isOnTheFly - ) { - return manager.createProblemDescriptor( - identifier, - InspectionLocalize.inspectionParameterCanBeLocalProblemDescriptor().get(), - true, - ProblemHighlightType.LIKE_UNUSED_SYMBOL, - isOnTheFly, - new ConvertParameterToLocalQuickFix() - ); - } - - @RequiredReadAction - private static Collection getWriteBeforeRead(@Nonnull Collection parameters, @Nonnull PsiCodeBlock body) { - final ControlFlow controlFlow = getControlFlow(body); - if (controlFlow == null) return Collections.emptyList(); - - final Set result = filterParameters(controlFlow, parameters); - result.retainAll(ControlFlowUtil.getWrittenVariables(controlFlow, 0, controlFlow.getSize(), false)); - for (final PsiReferenceExpression readBeforeWrite : ControlFlowUtil.getReadBeforeWrite(controlFlow)) { - final PsiElement resolved = readBeforeWrite.resolve(); - if (resolved instanceof PsiParameter) { - result.remove(resolved); - } + + @Override + @Nonnull + public String getShortName() { + return SHORT_NAME; } - return result; - } + @Override + @RequiredReadAction + public ProblemDescriptor[] checkMethod( + @Nonnull PsiMethod method, + @Nonnull InspectionManager manager, + boolean isOnTheFly, + Object state + ) { + final Collection parameters = filterFinal(method.getParameterList().getParameters()); + final PsiCodeBlock body = method.getBody(); + if (body == null || parameters.isEmpty() || isOverrides(method)) { + return ProblemDescriptor.EMPTY_ARRAY; + } - private static Set filterParameters(@Nonnull ControlFlow controlFlow, @Nonnull Collection parameters) { - final Set usedVars = new HashSet<>(ControlFlowUtil.getUsedVariables(controlFlow, 0, controlFlow.getSize())); + final List result = new ArrayList<>(); + for (PsiParameter parameter : getWriteBeforeRead(parameters, body)) { + final PsiIdentifier identifier = parameter.getNameIdentifier(); + if (identifier != null && identifier.isPhysical()) { + result.add(createProblem(manager, identifier, isOnTheFly)); + } + } + return result.toArray(new ProblemDescriptor[result.size()]); + } - final Set result = new HashSet<>(); - for (PsiParameter parameter : parameters) { - if (usedVars.contains(parameter)) { - result.add(parameter); - } + @Nonnull + private static List filterFinal(PsiParameter[] parameters) { + final List result = new ArrayList<>(parameters.length); + for (PsiParameter parameter : parameters) { + if (!parameter.hasModifierProperty(PsiModifier.FINAL)) { + result.add(parameter); + } + } + return result; } - return result; - } - - private static boolean isOverrides(PsiMethod method) { - return SuperMethodsSearch.search(method, null, true, false).findFirst() != null; - } - - @Nullable - private static ControlFlow getControlFlow(final PsiElement context) { - try { - return ControlFlowFactory.getInstance(context.getProject()) - .getControlFlow(context, LocalsOrMyInstanceFieldsControlFlowPolicy.getInstance()); - } catch (AnalysisCanceledException e) { - return null; + + + @Nonnull + private static ProblemDescriptor createProblem( + @Nonnull InspectionManager manager, + @Nonnull PsiIdentifier identifier, + boolean isOnTheFly + ) { + return manager.createProblemDescriptor( + identifier, + InspectionLocalize.inspectionParameterCanBeLocalProblemDescriptor().get(), + true, + ProblemHighlightType.LIKE_UNUSED_SYMBOL, + isOnTheFly, + new ConvertParameterToLocalQuickFix() + ); } - } - public static class ConvertParameterToLocalQuickFix extends BaseConvertToLocalQuickFix { - @Override @RequiredReadAction - protected PsiParameter getVariable(@Nonnull ProblemDescriptor descriptor) { - return (PsiParameter) descriptor.getPsiElement().getParent(); + private static Collection getWriteBeforeRead(@Nonnull Collection parameters, @Nonnull PsiCodeBlock body) { + final ControlFlow controlFlow = getControlFlow(body); + if (controlFlow == null) { + return Collections.emptyList(); + } + + final Set result = filterParameters(controlFlow, parameters); + result.retainAll(ControlFlowUtil.getWrittenVariables(controlFlow, 0, controlFlow.getSize(), false)); + for (final PsiReferenceExpression readBeforeWrite : ControlFlowUtil.getReadBeforeWrite(controlFlow)) { + final PsiElement resolved = readBeforeWrite.resolve(); + if (resolved instanceof PsiParameter) { + result.remove(resolved); + } + } + + return result; } - @Override - protected PsiElement applyChanges( - @Nonnull final Project project, - @Nonnull final String localName, - @Nullable final PsiExpression initializer, - @Nonnull final PsiParameter parameter, - @Nonnull final Collection references, - @Nonnull final Function action - ) { - final PsiElement scope = parameter.getDeclarationScope(); - if (scope instanceof PsiMethod) { - final PsiMethod method = (PsiMethod) scope; - final PsiParameter[] parameters = method.getParameterList().getParameters(); - - final List info = new ArrayList<>(); - for (int i = 0; i < parameters.length; i++) { - PsiParameter psiParameter = parameters[i]; - if (psiParameter == parameter) continue; - info.add(new ParameterInfoImpl(i, psiParameter.getName(), psiParameter.getType())); + private static Set filterParameters(@Nonnull ControlFlow controlFlow, @Nonnull Collection parameters) { + final Set usedVars = new HashSet<>(ControlFlowUtil.getUsedVariables(controlFlow, 0, controlFlow.getSize())); + + final Set result = new HashSet<>(); + for (PsiParameter parameter : parameters) { + if (usedVars.contains(parameter)) { + result.add(parameter); + } } - final ParameterInfoImpl[] newParams = info.toArray(new ParameterInfoImpl[info.size()]); - final String visibilityModifier = VisibilityUtil.getVisibilityModifier(method.getModifierList()); - final ChangeSignatureProcessor cp = new ChangeSignatureProcessor(project, method, false, visibilityModifier, - method.getName(), method.getReturnType(), newParams) { - @Override - protected void performRefactoring(UsageInfo[] usages) { - final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project); - final PsiElement newDeclaration = moveDeclaration(elementFactory, localName, parameter, initializer, action, references); - super.performRefactoring(usages); - positionCaretToDeclaration(project, newDeclaration.getContainingFile(), newDeclaration); - } - }; - cp.run(); - } - return null; + return result; } - @Nonnull - @Override - protected String suggestLocalName(@Nonnull Project project, @Nonnull PsiParameter parameter, @Nonnull PsiCodeBlock scope) { - return parameter.getName(); + private static boolean isOverrides(PsiMethod method) { + return SuperMethodsSearch.search(method, null, true, false).findFirst() != null; + } + + @Nullable + private static ControlFlow getControlFlow(final PsiElement context) { + try { + return ControlFlowFactory.getInstance(context.getProject()) + .getControlFlow(context, LocalsOrMyInstanceFieldsControlFlowPolicy.getInstance()); + } + catch (AnalysisCanceledException e) { + return null; + } + } + + public static class ConvertParameterToLocalQuickFix extends BaseConvertToLocalQuickFix { + @Override + @RequiredReadAction + protected PsiParameter getVariable(@Nonnull ProblemDescriptor descriptor) { + return (PsiParameter) descriptor.getPsiElement().getParent(); + } + + @Override + protected PsiElement applyChanges( + @Nonnull final Project project, + @Nonnull final String localName, + @Nullable final PsiExpression initializer, + @Nonnull final PsiParameter parameter, + @Nonnull final Collection references, + @Nonnull final Function action + ) { + final PsiElement scope = parameter.getDeclarationScope(); + if (scope instanceof PsiMethod) { + final PsiMethod method = (PsiMethod) scope; + final PsiParameter[] parameters = method.getParameterList().getParameters(); + + final List info = new ArrayList<>(); + for (int i = 0; i < parameters.length; i++) { + PsiParameter psiParameter = parameters[i]; + if (psiParameter == parameter) { + continue; + } + info.add(new ParameterInfoImpl(i, psiParameter.getName(), psiParameter.getType())); + } + final ParameterInfoImpl[] newParams = info.toArray(new ParameterInfoImpl[info.size()]); + final String visibilityModifier = VisibilityUtil.getVisibilityModifier(method.getModifierList()); + final ChangeSignatureProcessor cp = new ChangeSignatureProcessor(project, method, false, visibilityModifier, + method.getName(), method.getReturnType(), newParams + ) { + @Override + protected void performRefactoring(UsageInfo[] usages) { + final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project); + final PsiElement newDeclaration = + moveDeclaration(elementFactory, localName, parameter, initializer, action, references); + super.performRefactoring(usages); + positionCaretToDeclaration(project, newDeclaration.getContainingFile(), newDeclaration); + } + }; + cp.run(); + } + return null; + } + + @Nonnull + @Override + protected String suggestLocalName(@Nonnull Project project, @Nonnull PsiParameter parameter, @Nonnull PsiCodeBlock scope) { + return parameter.getName(); + } } - } } diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/abstraction/ClassReferencesSubclassInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/abstraction/ClassReferencesSubclassInspection.java index 1de016b259..9fbffc9a76 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/abstraction/ClassReferencesSubclassInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/abstraction/ClassReferencesSubclassInspection.java @@ -28,8 +28,8 @@ @ExtensionImpl public class ClassReferencesSubclassInspection extends BaseInspection { - @Nonnull + @Override public LocalizeValue getDisplayName() { return InspectionGadgetsLocalize.classReferencesSubclassDisplayName(); } @@ -64,21 +64,24 @@ public void visitMethod(@Nonnull PsiMethod method) { @Override public void visitInstanceOfExpression( - @Nonnull PsiInstanceOfExpression expression) { + @Nonnull PsiInstanceOfExpression expression + ) { final PsiTypeElement typeElement = expression.getCheckType(); checkTypeElement(typeElement); } @Override public void visitTypeCastExpression( - @Nonnull PsiTypeCastExpression expression) { + @Nonnull PsiTypeCastExpression expression + ) { final PsiTypeElement typeElement = expression.getCastType(); checkTypeElement(typeElement); } @Override public void visitClassObjectAccessExpression( - @Nonnull PsiClassObjectAccessExpression expression) { + @Nonnull PsiClassObjectAccessExpression expression + ) { final PsiTypeElement typeElement = expression.getOperand(); checkTypeElement(typeElement); } @@ -105,8 +108,10 @@ private void checkTypeElement(PsiTypeElement typeElement) { registerError(typeElement, parentClass, Boolean.FALSE); } - private static boolean isSubclass(@Nullable PsiClass childClass, - @Nullable PsiClass parent) { + private static boolean isSubclass( + @Nullable PsiClass childClass, + @Nullable PsiClass parent + ) { if (childClass == null) { return false; } diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/classlayout/StaticFieldCanBeMovedToUseInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/classlayout/StaticFieldCanBeMovedToUseInspection.java index e216688642..e6fe8205ea 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/classlayout/StaticFieldCanBeMovedToUseInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/classlayout/StaticFieldCanBeMovedToUseInspection.java @@ -27,6 +27,7 @@ import consulo.language.editor.inspection.reference.RefEntity; import consulo.language.editor.inspection.scheme.InspectionManager; import consulo.language.editor.scope.AnalysisScope; +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; @@ -35,55 +36,54 @@ import java.util.Set; public abstract class StaticFieldCanBeMovedToUseInspection extends BaseGlobalInspection { - - @Nonnull - @Override - public String getDisplayName() { - return null; - //return InspectionGadgetsBundle.message( - // "static.field.can.be.moved.to.use.display.name"); - } - - @Nullable - public CommonProblemDescriptor[] checkElement( - RefEntity refEntity, AnalysisScope analysisScope, - InspectionManager inspectionManager, - GlobalInspectionContext globalInspectionContext) { - if (!(refEntity instanceof RefField)) { - return null; - } - final RefField refField = (RefField) refEntity; - final PsiField field = refField.getElement(); - if (field == null) { - return null; - } - final PsiType type = field.getType(); - if (!type.equals(PsiType.BOOLEAN)) { - return null; + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return LocalizeValue.empty(); + //return InspectionGadgetsBundle.message("static.field.can.be.moved.to.use.display.name"); } - final RefClass fieldClass = refField.getOwnerClass(); - final Collection inReferences = refField.getInReferences(); - final RefJavaUtil refUtil = RefJavaUtil.getInstance(); - final Set classesUsed = new HashSet(); - for (RefElement inReference : inReferences) { - final RefClass referringClass = refUtil.getOwnerClass(inReference); - if (referringClass == null) { - return null; - } - if (referringClass.equals(fieldClass)) { - return null; - } - classesUsed.add(referringClass); - if (classesUsed.size() > 1) { - return null; - } - } - if (classesUsed.size() != 1) { - return null; + @Nullable + public CommonProblemDescriptor[] checkElement( + RefEntity refEntity, AnalysisScope analysisScope, + InspectionManager inspectionManager, + GlobalInspectionContext globalInspectionContext + ) { + if (!(refEntity instanceof RefField)) { + return null; + } + final RefField refField = (RefField) refEntity; + final PsiField field = refField.getElement(); + if (field == null) { + return null; + } + final PsiType type = field.getType(); + if (!type.equals(PsiType.BOOLEAN)) { + return null; + } + + final RefClass fieldClass = refField.getOwnerClass(); + final Collection inReferences = refField.getInReferences(); + final RefJavaUtil refUtil = RefJavaUtil.getInstance(); + final Set classesUsed = new HashSet(); + for (RefElement inReference : inReferences) { + final RefClass referringClass = refUtil.getOwnerClass(inReference); + if (referringClass == null) { + return null; + } + if (referringClass.equals(fieldClass)) { + return null; + } + classesUsed.add(referringClass); + if (classesUsed.size() > 1) { + return null; + } + } + if (classesUsed.size() != 1) { + return null; + } + final RefClass referencingClass = classesUsed.iterator().next(); + final String errorString = "Static field " + refEntity.getName() + " is only accessed in subclass " + referencingClass.getName(); + return new CommonProblemDescriptor[]{inspectionManager.createProblemDescriptor(errorString)}; } - final RefClass referencingClass = classesUsed.iterator().next(); - final String errorString = "Static field " + refEntity.getName() + " is only accessed in subclass " + referencingClass.getName(); - return new CommonProblemDescriptor[]{inspectionManager.createProblemDescriptor(errorString)}; - } } diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/junit/ParameterizedParametersStaticCollectionInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/junit/ParameterizedParametersStaticCollectionInspection.java index 5a75f7017c..3c4415c8b2 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/junit/ParameterizedParametersStaticCollectionInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/junit/ParameterizedParametersStaticCollectionInspection.java @@ -13,162 +13,182 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -/* - * User: anna - * Date: 10-Jun-2009 - */ package com.intellij.java.impl.ig.junit; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import com.intellij.java.language.psi.*; -import consulo.annotation.component.ExtensionImpl; -import jakarta.annotation.Nonnull; -import org.jetbrains.annotations.Nls; -import com.intellij.java.language.codeInsight.AnnotationUtil; import com.intellij.java.impl.codeInsight.daemon.impl.quickfix.CreateMethodQuickFix; -import consulo.language.editor.inspection.ProblemDescriptor; -import consulo.project.Project; -import consulo.language.psi.*; -import consulo.language.psi.scope.GlobalSearchScope; -import com.intellij.java.language.psi.util.InheritanceUtil; -import consulo.language.psi.util.PsiTreeUtil; -import com.intellij.java.language.psi.util.PsiUtil; import com.intellij.java.impl.refactoring.changeSignature.ChangeSignatureProcessor; import com.intellij.java.impl.refactoring.changeSignature.ParameterInfoImpl; -import consulo.language.util.IncorrectOperationException; +import com.intellij.java.language.codeInsight.AnnotationUtil; +import com.intellij.java.language.psi.*; +import com.intellij.java.language.psi.util.InheritanceUtil; +import com.intellij.java.language.psi.util.PsiUtil; import com.siyeh.ig.BaseInspection; import com.siyeh.ig.BaseInspectionVisitor; import com.siyeh.ig.InspectionGadgetsFix; +import consulo.annotation.component.ExtensionImpl; +import consulo.language.editor.inspection.ProblemDescriptor; +import consulo.language.psi.PsiElement; +import consulo.language.psi.scope.GlobalSearchScope; +import consulo.language.psi.util.PsiTreeUtil; +import consulo.language.util.IncorrectOperationException; +import consulo.localize.LocalizeValue; +import consulo.project.Project; +import jakarta.annotation.Nonnull; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +/** + * @author anna + * @since 2009-01-10 + */ @ExtensionImpl public class ParameterizedParametersStaticCollectionInspection extends BaseInspection { - private static final String PARAMETERS_FQN = "org.junit.runners.Parameterized.Parameters"; - private static final String PARAMETERIZED_FQN = "org.junit.runners.Parameterized"; + private static final String PARAMETERS_FQN = "org.junit.runners.Parameterized.Parameters"; + private static final String PARAMETERIZED_FQN = "org.junit.runners.Parameterized"; - @Nonnull - protected String buildErrorString(Object... infos) { - return infos.length > 0 - ? (String)infos[1] - : "Class #ref annotated @RunWith(Parameterized.class) lacks data provider"; - } + @Nonnull + protected String buildErrorString(Object... infos) { + return infos.length > 0 + ? (String) infos[1] + : "Class #ref annotated @RunWith(Parameterized.class) lacks data provider"; + } - public BaseInspectionVisitor buildVisitor() { - return new BaseInspectionVisitor() { - @Override - public void visitClass(PsiClass aClass) { - final PsiAnnotation annotation = AnnotationUtil.findAnnotation(aClass, "org.junit.runner.RunWith"); - if (annotation != null) { - for (PsiNameValuePair pair : annotation.getParameterList().getAttributes()) { - final PsiAnnotationMemberValue value = pair.getValue(); - if (value instanceof PsiClassObjectAccessExpression) { - final PsiTypeElement typeElement = ((PsiClassObjectAccessExpression)value).getOperand(); - if (typeElement.getType().getCanonicalText().equals(PARAMETERIZED_FQN)) { - List candidates = new ArrayList(); - for (PsiMethod method : aClass.getMethods()) { - PsiType returnType = method.getReturnType(); - final PsiClass returnTypeClass = PsiUtil.resolveClassInType(returnType); - final Project project = aClass.getProject(); - final PsiClass collectionsClass = - JavaPsiFacade.getInstance(project).findClass(Collection.class.getName(), GlobalSearchScope.allScope(project)); - if (AnnotationUtil.isAnnotated(method, PARAMETERS_FQN, false)) { - final PsiModifierList modifierList = method.getModifierList(); - boolean hasToFixSignature = false; - String message = "Make method \'" + method.getName() + "\' "; - String errorString = "Method \'#ref()\' should be "; - if (!modifierList.hasModifierProperty(PsiModifier.PUBLIC)) { - message += PsiModifier.PUBLIC + " "; - errorString += PsiModifier.PUBLIC + " "; - hasToFixSignature = true; - } - if (!modifierList.hasModifierProperty(PsiModifier.STATIC)) { - message += PsiModifier.STATIC; - errorString += PsiModifier.STATIC; - hasToFixSignature = true; - } - if (collectionsClass != null && - (returnTypeClass == null || !InheritanceUtil.isInheritorOrSelf(returnTypeClass, collectionsClass, true))) { - message += (hasToFixSignature ? " and" : "") + " return Collection"; - errorString += (hasToFixSignature ? " and" : "") + " return Collection"; - returnType = JavaPsiFacade.getElementFactory(project).createType(collectionsClass); - hasToFixSignature = true; - } - if (hasToFixSignature) { - candidates.add(new MethodCandidate(method, message, errorString, returnType)); - continue; + public BaseInspectionVisitor buildVisitor() { + return new BaseInspectionVisitor() { + @Override + public void visitClass(PsiClass aClass) { + final PsiAnnotation annotation = AnnotationUtil.findAnnotation(aClass, "org.junit.runner.RunWith"); + if (annotation != null) { + for (PsiNameValuePair pair : annotation.getParameterList().getAttributes()) { + final PsiAnnotationMemberValue value = pair.getValue(); + if (value instanceof PsiClassObjectAccessExpression) { + final PsiTypeElement typeElement = ((PsiClassObjectAccessExpression) value).getOperand(); + if (typeElement.getType().getCanonicalText().equals(PARAMETERIZED_FQN)) { + List candidates = new ArrayList(); + for (PsiMethod method : aClass.getMethods()) { + PsiType returnType = method.getReturnType(); + final PsiClass returnTypeClass = PsiUtil.resolveClassInType(returnType); + final Project project = aClass.getProject(); + final PsiClass collectionsClass = + JavaPsiFacade.getInstance(project) + .findClass(Collection.class.getName(), GlobalSearchScope.allScope(project)); + if (AnnotationUtil.isAnnotated(method, PARAMETERS_FQN, false)) { + final PsiModifierList modifierList = method.getModifierList(); + boolean hasToFixSignature = false; + String message = "Make method \'" + method.getName() + "\' "; + String errorString = "Method \'#ref()\' should be "; + if (!modifierList.hasModifierProperty(PsiModifier.PUBLIC)) { + message += PsiModifier.PUBLIC + " "; + errorString += PsiModifier.PUBLIC + " "; + hasToFixSignature = true; + } + if (!modifierList.hasModifierProperty(PsiModifier.STATIC)) { + message += PsiModifier.STATIC; + errorString += PsiModifier.STATIC; + hasToFixSignature = true; + } + if (collectionsClass != null && + (returnTypeClass == null || !InheritanceUtil.isInheritorOrSelf( + returnTypeClass, + collectionsClass, + true + ))) { + message += (hasToFixSignature ? " and" : "") + " return Collection"; + errorString += (hasToFixSignature ? " and" : "") + " return Collection"; + returnType = JavaPsiFacade.getElementFactory(project).createType(collectionsClass); + hasToFixSignature = true; + } + if (hasToFixSignature) { + candidates.add(new MethodCandidate(method, message, errorString, returnType)); + continue; + } + return; + } + } + if (candidates.isEmpty()) { + registerClassError(aClass); + } + else { + for (MethodCandidate candidate : candidates) { + registerMethodError( + candidate.myMethod, + candidate.myProblem, + candidate.myErrorString, + candidate.myReturnType + ); + } + } + } + } } - return; - } } - if (candidates.isEmpty()) { - registerClassError(aClass); + } + }; + } + + @Override + protected InspectionGadgetsFix buildFix(final Object... infos) { + return new InspectionGadgetsFix() { + @Override + protected void doFix(final Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { + final PsiElement element = descriptor.getPsiElement(); + final PsiMethod method = PsiTreeUtil.getParentOfType(element, PsiMethod.class); + if (method != null) { + PsiType type = (PsiType) infos[1]; + if (type == null) { + type = method.getReturnType(); + } + final ChangeSignatureProcessor csp = + new ChangeSignatureProcessor( + project, + method, + false, + PsiModifier.PUBLIC, + method.getName(), + type, + new ParameterInfoImpl[0] + ); + csp.run(); } else { - for (MethodCandidate candidate : candidates) { - registerMethodError(candidate.myMethod, candidate.myProblem, candidate.myErrorString, candidate.myReturnType); - } + final PsiClass psiClass = PsiTreeUtil.getParentOfType(element, PsiClass.class); + if (psiClass != null) { + final CreateMethodQuickFix fix = CreateMethodQuickFix + .createFix(psiClass, "@" + PARAMETERS_FQN + " public static java.util.Collection parameters()", ""); + if (fix != null) { + fix.applyFix(project, descriptor); + } + } } - } } - } - } - } - }; - } - @Override - protected InspectionGadgetsFix buildFix(final Object... infos) { - return new InspectionGadgetsFix() { - @Override - protected void doFix(final Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { - final PsiElement element = descriptor.getPsiElement(); - final PsiMethod method = PsiTreeUtil.getParentOfType(element, PsiMethod.class); - if (method != null) { - PsiType type = (PsiType)infos[1]; - if (type == null) type = method.getReturnType(); - final ChangeSignatureProcessor csp = - new ChangeSignatureProcessor(project, method, false, PsiModifier.PUBLIC, method.getName(), type, new ParameterInfoImpl[0]); - csp.run(); - } - else { - final PsiClass psiClass = PsiTreeUtil.getParentOfType(element, PsiClass.class); - if (psiClass != null) { - final CreateMethodQuickFix fix = CreateMethodQuickFix - .createFix(psiClass, "@" + PARAMETERS_FQN + " public static java.util.Collection parameters()", ""); - if (fix != null) { - fix.applyFix(project, descriptor); + @Nonnull + @Override + public LocalizeValue getName() { + return LocalizeValue.localizeTODO(infos.length > 0 ? (String) infos[0] : "Create @Parameterized.Parameters data provider"); } - } - } - } - - @Nonnull - public String getName() { - return infos.length > 0 ? (String)infos[0] : "Create @Parameterized.Parameters data provider"; - } - }; - } + }; + } - @Nls - @Nonnull - public String getDisplayName() { - return "@RunWith(Parameterized.class) without data provider"; - } + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return LocalizeValue.localizeTODO("@RunWith(Parameterized.class) without data provider"); + } - private static class MethodCandidate { - PsiMethod myMethod; - String myProblem; - private final String myErrorString; - PsiType myReturnType; + private static class MethodCandidate { + PsiMethod myMethod; + String myProblem; + private final String myErrorString; + PsiType myReturnType; - public MethodCandidate(PsiMethod method, String problem, String errorString, PsiType returnType) { - myMethod = method; - myProblem = problem; - myErrorString = errorString; - myReturnType = returnType; + public MethodCandidate(PsiMethod method, String problem, String errorString, PsiType returnType) { + myMethod = method; + myProblem = problem; + myErrorString = errorString; + myReturnType = returnType; + } } - } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/junit/SimplifiableJUnitAssertionInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/junit/SimplifiableJUnitAssertionInspection.java index eca4f672a7..33a69c4b90 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/junit/SimplifiableJUnitAssertionInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/junit/SimplifiableJUnitAssertionInspection.java @@ -30,671 +30,674 @@ import consulo.language.editor.inspection.ProblemDescriptor; import consulo.language.psi.PsiElement; import consulo.language.util.IncorrectOperationException; +import consulo.localize.LocalizeValue; import consulo.project.Project; import jakarta.annotation.Nonnull; import org.jetbrains.annotations.NonNls; @ExtensionImpl public class SimplifiableJUnitAssertionInspection extends BaseInspection { - - @Override - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.simplifiableJunitAssertionDisplayName().get(); - } - - @Override - @Nonnull - protected String buildErrorString(Object... infos) { - return InspectionGadgetsLocalize.simplifiableJunitAssertionProblemDescriptor(infos[0]).get(); - } - - @Override - public InspectionGadgetsFix buildFix(Object... infos) { - return new SimplifyJUnitAssertFix(); - } - - private static class SimplifyJUnitAssertFix extends InspectionGadgetsFix { + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.simplifiableJunitAssertionDisplayName(); + } @Override @Nonnull - public String getName() { - return InspectionGadgetsLocalize.simplifyJunitAssertionSimplifyQuickfix().get(); + protected String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.simplifiableJunitAssertionProblemDescriptor(infos[0]).get(); } @Override - public void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { - final PsiElement methodNameIdentifier = descriptor.getPsiElement(); - final PsiElement parent = methodNameIdentifier.getParent(); - if (parent == null) { - return; - } - final PsiMethodCallExpression callExpression = (PsiMethodCallExpression)parent.getParent(); - if (isAssertThatCouldBeAssertNull(callExpression)) { - replaceAssertWithAssertNull(callExpression); - } - else if (isAssertThatCouldBeAssertSame(callExpression)) { - replaceAssertWithAssertSame(callExpression); - } - else if (isAssertTrueThatCouldBeAssertEquals(callExpression)) { - replaceAssertTrueWithAssertEquals(callExpression); - } - else if (isAssertEqualsThatCouldBeAssertLiteral(callExpression)) { - replaceAssertEqualsWithAssertLiteral(callExpression); - } - else if (isAssertThatCouldBeFail(callExpression)) { - replaceAssertWithFail(callExpression); - } + public InspectionGadgetsFix buildFix(Object... infos) { + return new SimplifyJUnitAssertFix(); } - private static void replaceAssertWithFail(PsiMethodCallExpression callExpression) throws IncorrectOperationException { - final PsiMethod method = callExpression.resolveMethod(); - if (method == null) { - return; - } - final PsiExpressionList argumentList = callExpression.getArgumentList(); - final PsiExpression[] arguments = argumentList.getExpressions(); - final PsiExpression message; - if (arguments.length == 2) { - message = arguments[0]; - } - else { - message = null; - } - @NonNls final StringBuilder newExpression = new StringBuilder(); - if (!ImportUtils.addStaticImport("org.junit.Assert", "fail", callExpression)) { - newExpression.append("org.junit.Assert."); - } - newExpression.append("fail("); - if (message != null) { - newExpression.append(message.getText()); - } - newExpression.append(')'); - replaceExpressionAndShorten(callExpression, newExpression.toString()); - } + private static class SimplifyJUnitAssertFix extends InspectionGadgetsFix { + @Nonnull + @Override + public LocalizeValue getName() { + return InspectionGadgetsLocalize.simplifyJunitAssertionSimplifyQuickfix(); + } - private static void replaceAssertTrueWithAssertEquals(PsiMethodCallExpression callExpression) throws IncorrectOperationException { - final PsiMethod method = callExpression.resolveMethod(); - if (method == null) { - return; - } - final PsiParameterList parameterList = method.getParameterList(); - final PsiParameter[] parameters = parameterList.getParameters(); - final PsiType stringType = TypeUtils.getStringType(callExpression); - final PsiType paramType1 = parameters[0].getType(); - final PsiExpressionList argumentList = callExpression.getArgumentList(); - final PsiExpression[] arguments = argumentList.getExpressions(); - final int testPosition; - final PsiExpression message; - if (paramType1.equals(stringType) && parameters.length >= 2) { - testPosition = 1; - message = arguments[0]; - } - else { - testPosition = 0; - message = null; - } - final PsiExpression testArgument = arguments[testPosition]; - PsiExpression lhs = null; - PsiExpression rhs = null; - if (testArgument instanceof PsiBinaryExpression) { - final PsiBinaryExpression binaryExpression = (PsiBinaryExpression)testArgument; - lhs = binaryExpression.getLOperand(); - rhs = binaryExpression.getROperand(); - } - else if (testArgument instanceof PsiMethodCallExpression) { - final PsiMethodCallExpression call = (PsiMethodCallExpression)testArgument; - final PsiReferenceExpression equalityMethodExpression = call.getMethodExpression(); - final PsiExpressionList equalityArgumentList = call.getArgumentList(); - final PsiExpression[] equalityArgs = equalityArgumentList.getExpressions(); - rhs = equalityArgs[0]; - lhs = equalityMethodExpression.getQualifierExpression(); - } - if (!(lhs instanceof PsiLiteralExpression) && rhs instanceof PsiLiteralExpression) { - final PsiExpression temp = lhs; - lhs = rhs; - rhs = temp; - } - if (lhs == null || rhs == null) { - return; - } - @NonNls final StringBuilder newExpression = new StringBuilder(); - if (!ImportUtils.addStaticImport("org.junit.Assert", "assertEquals", callExpression)) { - newExpression.append("org.junit.Assert."); - } - newExpression.append("assertEquals("); - if (message != null) { - newExpression.append(message.getText()).append(','); - } - newExpression.append(lhs.getText()).append(',').append(rhs.getText()); - if (TypeUtils.hasFloatingPointType(lhs) || TypeUtils.hasFloatingPointType(rhs)) { - newExpression.append(",0.0"); - } - newExpression.append(')'); - replaceExpressionAndShorten(callExpression, newExpression.toString()); - } + @Override + public void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { + final PsiElement methodNameIdentifier = descriptor.getPsiElement(); + final PsiElement parent = methodNameIdentifier.getParent(); + if (parent == null) { + return; + } + final PsiMethodCallExpression callExpression = (PsiMethodCallExpression) parent.getParent(); + if (isAssertThatCouldBeAssertNull(callExpression)) { + replaceAssertWithAssertNull(callExpression); + } + else if (isAssertThatCouldBeAssertSame(callExpression)) { + replaceAssertWithAssertSame(callExpression); + } + else if (isAssertTrueThatCouldBeAssertEquals(callExpression)) { + replaceAssertTrueWithAssertEquals(callExpression); + } + else if (isAssertEqualsThatCouldBeAssertLiteral(callExpression)) { + replaceAssertEqualsWithAssertLiteral(callExpression); + } + else if (isAssertThatCouldBeFail(callExpression)) { + replaceAssertWithFail(callExpression); + } + } - private static void replaceAssertWithAssertNull(PsiMethodCallExpression callExpression) throws IncorrectOperationException { - final PsiMethod method = callExpression.resolveMethod(); - if (method == null) { - return; - } - final PsiParameterList parameterList = method.getParameterList(); - final PsiParameter[] parameters = parameterList.getParameters(); - final PsiType stringType = TypeUtils.getStringType(callExpression); - final PsiType paramType1 = parameters[0].getType(); - final PsiExpressionList argumentList = callExpression.getArgumentList(); - final PsiExpression[] arguments = argumentList.getExpressions(); - final int testPosition; - final PsiExpression message; - if (paramType1.equals(stringType) && parameters.length >= 2) { - testPosition = 1; - message = arguments[0]; - } - else { - testPosition = 0; - message = null; - } - final PsiBinaryExpression binaryExpression = (PsiBinaryExpression)arguments[testPosition]; - final PsiExpression lhs = binaryExpression.getLOperand(); - PsiExpression rhs = binaryExpression.getROperand(); - if (rhs == null) { - return; - } - final IElementType tokenType = binaryExpression.getOperationTokenType(); - if (!(lhs instanceof PsiLiteralExpression) && rhs instanceof PsiLiteralExpression) { - rhs = lhs; - } - @NonNls final StringBuilder newExpression = new StringBuilder(); - final PsiReferenceExpression methodExpression = callExpression.getMethodExpression(); - @NonNls final String methodName = methodExpression.getReferenceName(); - @NonNls final String memberName; - if ("assertFalse".equals(methodName) ^ tokenType.equals(JavaTokenType.NE)) { - memberName = "assertNotNull"; - } - else { - memberName = "assertNull"; - } - if (!ImportUtils.addStaticImport("org.junit.Assert", memberName, callExpression)) { - newExpression.append("org.junit.Assert."); - } - newExpression.append(memberName).append('('); - if (message != null) { - newExpression.append(message.getText()).append(','); - } - newExpression.append(rhs.getText()).append(')'); - replaceExpressionAndShorten(callExpression, newExpression.toString()); - } + private static void replaceAssertWithFail(PsiMethodCallExpression callExpression) throws IncorrectOperationException { + final PsiMethod method = callExpression.resolveMethod(); + if (method == null) { + return; + } + final PsiExpressionList argumentList = callExpression.getArgumentList(); + final PsiExpression[] arguments = argumentList.getExpressions(); + final PsiExpression message; + if (arguments.length == 2) { + message = arguments[0]; + } + else { + message = null; + } + @NonNls final StringBuilder newExpression = new StringBuilder(); + if (!ImportUtils.addStaticImport("org.junit.Assert", "fail", callExpression)) { + newExpression.append("org.junit.Assert."); + } + newExpression.append("fail("); + if (message != null) { + newExpression.append(message.getText()); + } + newExpression.append(')'); + replaceExpressionAndShorten(callExpression, newExpression.toString()); + } - private static void replaceAssertWithAssertSame(PsiMethodCallExpression callExpression) throws IncorrectOperationException { - final PsiMethod method = callExpression.resolveMethod(); - if (method == null) { - return; - } - final PsiParameterList parameterList = method.getParameterList(); - final PsiParameter[] parameters = parameterList.getParameters(); - final PsiType stringType = TypeUtils.getStringType(callExpression); - final PsiType paramType1 = parameters[0].getType(); - final PsiExpressionList argumentList = callExpression.getArgumentList(); - final PsiExpression[] arguments = argumentList.getExpressions(); - final int testPosition; - final PsiExpression message; - if (paramType1.equals(stringType) && parameters.length >= 2) { - testPosition = 1; - message = arguments[0]; - } - else { - testPosition = 0; - message = null; - } - final PsiBinaryExpression binaryExpression = (PsiBinaryExpression)arguments[testPosition]; - PsiExpression lhs = binaryExpression.getLOperand(); - PsiExpression rhs = binaryExpression.getROperand(); - final IElementType tokenType = binaryExpression.getOperationTokenType(); - if (!(lhs instanceof PsiLiteralExpression) && rhs instanceof PsiLiteralExpression) { - final PsiExpression temp = lhs; - lhs = rhs; - rhs = temp; - } - if (rhs == null) { - return; - } - @NonNls final StringBuilder newExpression = new StringBuilder(); - final PsiReferenceExpression methodExpression = callExpression.getMethodExpression(); - @NonNls final String methodName = methodExpression.getReferenceName(); - @NonNls final String memberName; - if ("assertFalse".equals(methodName) ^ tokenType.equals(JavaTokenType.NE)) { - memberName = "assertNotSame"; - } - else { - memberName = "assertSame"; - } - if (!ImportUtils.addStaticImport("org.junit.Assert", memberName, callExpression)) { - newExpression.append("org.junit.Assert."); - } - newExpression.append(memberName).append('('); - if (message != null) { - newExpression.append(message.getText()).append(','); - } - newExpression.append(lhs.getText()).append(',').append(rhs.getText()).append(')'); - replaceExpressionAndShorten(callExpression, newExpression.toString()); - } + private static void replaceAssertTrueWithAssertEquals(PsiMethodCallExpression callExpression) throws IncorrectOperationException { + final PsiMethod method = callExpression.resolveMethod(); + if (method == null) { + return; + } + final PsiParameterList parameterList = method.getParameterList(); + final PsiParameter[] parameters = parameterList.getParameters(); + final PsiType stringType = TypeUtils.getStringType(callExpression); + final PsiType paramType1 = parameters[0].getType(); + final PsiExpressionList argumentList = callExpression.getArgumentList(); + final PsiExpression[] arguments = argumentList.getExpressions(); + final int testPosition; + final PsiExpression message; + if (paramType1.equals(stringType) && parameters.length >= 2) { + testPosition = 1; + message = arguments[0]; + } + else { + testPosition = 0; + message = null; + } + final PsiExpression testArgument = arguments[testPosition]; + PsiExpression lhs = null; + PsiExpression rhs = null; + if (testArgument instanceof PsiBinaryExpression) { + final PsiBinaryExpression binaryExpression = (PsiBinaryExpression) testArgument; + lhs = binaryExpression.getLOperand(); + rhs = binaryExpression.getROperand(); + } + else if (testArgument instanceof PsiMethodCallExpression) { + final PsiMethodCallExpression call = (PsiMethodCallExpression) testArgument; + final PsiReferenceExpression equalityMethodExpression = call.getMethodExpression(); + final PsiExpressionList equalityArgumentList = call.getArgumentList(); + final PsiExpression[] equalityArgs = equalityArgumentList.getExpressions(); + rhs = equalityArgs[0]; + lhs = equalityMethodExpression.getQualifierExpression(); + } + if (!(lhs instanceof PsiLiteralExpression) && rhs instanceof PsiLiteralExpression) { + final PsiExpression temp = lhs; + lhs = rhs; + rhs = temp; + } + if (lhs == null || rhs == null) { + return; + } + @NonNls final StringBuilder newExpression = new StringBuilder(); + if (!ImportUtils.addStaticImport("org.junit.Assert", "assertEquals", callExpression)) { + newExpression.append("org.junit.Assert."); + } + newExpression.append("assertEquals("); + if (message != null) { + newExpression.append(message.getText()).append(','); + } + newExpression.append(lhs.getText()).append(',').append(rhs.getText()); + if (TypeUtils.hasFloatingPointType(lhs) || TypeUtils.hasFloatingPointType(rhs)) { + newExpression.append(",0.0"); + } + newExpression.append(')'); + replaceExpressionAndShorten(callExpression, newExpression.toString()); + } - private static void replaceAssertEqualsWithAssertLiteral( - PsiMethodCallExpression callExpression) - throws IncorrectOperationException { - final PsiMethod method = callExpression.resolveMethod(); - if (method == null) { - return; - } - final PsiParameterList parameterList = method.getParameterList(); - final PsiParameter[] parameters = parameterList.getParameters(); - final PsiType stringType = TypeUtils.getStringType(callExpression); - final PsiType paramType1 = parameters[0].getType(); - final PsiExpressionList argumentList = callExpression.getArgumentList(); - final PsiExpression[] arguments = argumentList.getExpressions(); - final int firstTestPosition; - final int secondTestPosition; - final PsiExpression message; - if (paramType1.equals(stringType) && parameters.length >= 3) { - firstTestPosition = 1; - secondTestPosition = 2; - message = arguments[0]; - } - else { - firstTestPosition = 0; - secondTestPosition = 1; - message = null; - } - final PsiExpression firstTestArgument = arguments[firstTestPosition]; - final PsiExpression secondTestArgument = arguments[secondTestPosition]; - final String literalValue; - final String compareValue; - if (isSimpleLiteral(firstTestArgument, secondTestArgument)) { - literalValue = firstTestArgument.getText(); - compareValue = secondTestArgument.getText(); - } - else { - literalValue = secondTestArgument.getText(); - compareValue = firstTestArgument.getText(); - } - final String uppercaseLiteralValue = Character.toUpperCase(literalValue.charAt(0)) + literalValue.substring(1); - @NonNls final StringBuilder newExpression = new StringBuilder(); - @NonNls final String methodName = "assert" + uppercaseLiteralValue; - if (!ImportUtils.addStaticImport("org.junit.Assert", methodName, callExpression)) { - newExpression.append("org.junit.Assert."); - } - newExpression.append(methodName).append('('); - if (message != null) { - newExpression.append(message.getText()).append(','); - } - newExpression.append(compareValue).append(')'); - replaceExpressionAndShorten(callExpression, newExpression.toString()); - } - } + private static void replaceAssertWithAssertNull(PsiMethodCallExpression callExpression) throws IncorrectOperationException { + final PsiMethod method = callExpression.resolveMethod(); + if (method == null) { + return; + } + final PsiParameterList parameterList = method.getParameterList(); + final PsiParameter[] parameters = parameterList.getParameters(); + final PsiType stringType = TypeUtils.getStringType(callExpression); + final PsiType paramType1 = parameters[0].getType(); + final PsiExpressionList argumentList = callExpression.getArgumentList(); + final PsiExpression[] arguments = argumentList.getExpressions(); + final int testPosition; + final PsiExpression message; + if (paramType1.equals(stringType) && parameters.length >= 2) { + testPosition = 1; + message = arguments[0]; + } + else { + testPosition = 0; + message = null; + } + final PsiBinaryExpression binaryExpression = (PsiBinaryExpression) arguments[testPosition]; + final PsiExpression lhs = binaryExpression.getLOperand(); + PsiExpression rhs = binaryExpression.getROperand(); + if (rhs == null) { + return; + } + final IElementType tokenType = binaryExpression.getOperationTokenType(); + if (!(lhs instanceof PsiLiteralExpression) && rhs instanceof PsiLiteralExpression) { + rhs = lhs; + } + @NonNls final StringBuilder newExpression = new StringBuilder(); + final PsiReferenceExpression methodExpression = callExpression.getMethodExpression(); + @NonNls final String methodName = methodExpression.getReferenceName(); + @NonNls final String memberName; + if ("assertFalse".equals(methodName) ^ tokenType.equals(JavaTokenType.NE)) { + memberName = "assertNotNull"; + } + else { + memberName = "assertNull"; + } + if (!ImportUtils.addStaticImport("org.junit.Assert", memberName, callExpression)) { + newExpression.append("org.junit.Assert."); + } + newExpression.append(memberName).append('('); + if (message != null) { + newExpression.append(message.getText()).append(','); + } + newExpression.append(rhs.getText()).append(')'); + replaceExpressionAndShorten(callExpression, newExpression.toString()); + } - @Override - public BaseInspectionVisitor buildVisitor() { - return new SimplifiableJUnitAssertionVisitor(); - } + private static void replaceAssertWithAssertSame(PsiMethodCallExpression callExpression) throws IncorrectOperationException { + final PsiMethod method = callExpression.resolveMethod(); + if (method == null) { + return; + } + final PsiParameterList parameterList = method.getParameterList(); + final PsiParameter[] parameters = parameterList.getParameters(); + final PsiType stringType = TypeUtils.getStringType(callExpression); + final PsiType paramType1 = parameters[0].getType(); + final PsiExpressionList argumentList = callExpression.getArgumentList(); + final PsiExpression[] arguments = argumentList.getExpressions(); + final int testPosition; + final PsiExpression message; + if (paramType1.equals(stringType) && parameters.length >= 2) { + testPosition = 1; + message = arguments[0]; + } + else { + testPosition = 0; + message = null; + } + final PsiBinaryExpression binaryExpression = (PsiBinaryExpression) arguments[testPosition]; + PsiExpression lhs = binaryExpression.getLOperand(); + PsiExpression rhs = binaryExpression.getROperand(); + final IElementType tokenType = binaryExpression.getOperationTokenType(); + if (!(lhs instanceof PsiLiteralExpression) && rhs instanceof PsiLiteralExpression) { + final PsiExpression temp = lhs; + lhs = rhs; + rhs = temp; + } + if (rhs == null) { + return; + } + @NonNls final StringBuilder newExpression = new StringBuilder(); + final PsiReferenceExpression methodExpression = callExpression.getMethodExpression(); + @NonNls final String methodName = methodExpression.getReferenceName(); + @NonNls final String memberName; + if ("assertFalse".equals(methodName) ^ tokenType.equals(JavaTokenType.NE)) { + memberName = "assertNotSame"; + } + else { + memberName = "assertSame"; + } + if (!ImportUtils.addStaticImport("org.junit.Assert", memberName, callExpression)) { + newExpression.append("org.junit.Assert."); + } + newExpression.append(memberName).append('('); + if (message != null) { + newExpression.append(message.getText()).append(','); + } + newExpression.append(lhs.getText()).append(',').append(rhs.getText()).append(')'); + replaceExpressionAndShorten(callExpression, newExpression.toString()); + } - private static class SimplifiableJUnitAssertionVisitor extends BaseInspectionVisitor { + private static void replaceAssertEqualsWithAssertLiteral( + PsiMethodCallExpression callExpression + ) + throws IncorrectOperationException { + final PsiMethod method = callExpression.resolveMethod(); + if (method == null) { + return; + } + final PsiParameterList parameterList = method.getParameterList(); + final PsiParameter[] parameters = parameterList.getParameters(); + final PsiType stringType = TypeUtils.getStringType(callExpression); + final PsiType paramType1 = parameters[0].getType(); + final PsiExpressionList argumentList = callExpression.getArgumentList(); + final PsiExpression[] arguments = argumentList.getExpressions(); + final int firstTestPosition; + final int secondTestPosition; + final PsiExpression message; + if (paramType1.equals(stringType) && parameters.length >= 3) { + firstTestPosition = 1; + secondTestPosition = 2; + message = arguments[0]; + } + else { + firstTestPosition = 0; + secondTestPosition = 1; + message = null; + } + final PsiExpression firstTestArgument = arguments[firstTestPosition]; + final PsiExpression secondTestArgument = arguments[secondTestPosition]; + final String literalValue; + final String compareValue; + if (isSimpleLiteral(firstTestArgument, secondTestArgument)) { + literalValue = firstTestArgument.getText(); + compareValue = secondTestArgument.getText(); + } + else { + literalValue = secondTestArgument.getText(); + compareValue = firstTestArgument.getText(); + } + final String uppercaseLiteralValue = Character.toUpperCase(literalValue.charAt(0)) + literalValue.substring(1); + @NonNls final StringBuilder newExpression = new StringBuilder(); + @NonNls final String methodName = "assert" + uppercaseLiteralValue; + if (!ImportUtils.addStaticImport("org.junit.Assert", methodName, callExpression)) { + newExpression.append("org.junit.Assert."); + } + newExpression.append(methodName).append('('); + if (message != null) { + newExpression.append(message.getText()).append(','); + } + newExpression.append(compareValue).append(')'); + replaceExpressionAndShorten(callExpression, newExpression.toString()); + } + } @Override - public void visitMethodCallExpression(@Nonnull PsiMethodCallExpression expression) { - super.visitMethodCallExpression(expression); - if (isAssertThatCouldBeAssertNull(expression)) { - if (hasEqEqExpressionArgument(expression)) { - registerMethodCallError(expression, "assertNull()"); + public BaseInspectionVisitor buildVisitor() { + return new SimplifiableJUnitAssertionVisitor(); + } + + private static class SimplifiableJUnitAssertionVisitor extends BaseInspectionVisitor { + + @Override + public void visitMethodCallExpression(@Nonnull PsiMethodCallExpression expression) { + super.visitMethodCallExpression(expression); + if (isAssertThatCouldBeAssertNull(expression)) { + if (hasEqEqExpressionArgument(expression)) { + registerMethodCallError(expression, "assertNull()"); + } + else { + registerMethodCallError(expression, "assertNotNull()"); + } + } + else if (isAssertThatCouldBeAssertSame(expression)) { + if (hasEqEqExpressionArgument(expression)) { + registerMethodCallError(expression, "assertSame()"); + } + else { + registerMethodCallError(expression, "assertNotSame()"); + } + } + else if (isAssertTrueThatCouldBeAssertEquals(expression)) { + registerMethodCallError(expression, "assertEquals()"); + } + else if (isAssertEqualsThatCouldBeAssertLiteral(expression)) { + registerMethodCallError(expression, getReplacementMethodName(expression)); + } + else if (isAssertThatCouldBeFail(expression)) { + registerMethodCallError(expression, "fail()"); + } } - else { - registerMethodCallError(expression, "assertNotNull()"); + + @NonNls + private static String getReplacementMethodName(PsiMethodCallExpression expression) { + final PsiExpressionList argumentList = expression.getArgumentList(); + final PsiExpression[] arguments = argumentList.getExpressions(); + final PsiExpression firstArgument = arguments[0]; + if (firstArgument instanceof PsiLiteralExpression) { + final PsiLiteralExpression literalExpression = (PsiLiteralExpression) firstArgument; + final Object value = literalExpression.getValue(); + if (value == Boolean.TRUE) { + return "assertTrue()"; + } + else if (value == Boolean.FALSE) { + return "assertFalse()"; + } + else if (value == null) { + return "assertNull()"; + } + } + final PsiExpression secondArgument = arguments[1]; + if (secondArgument instanceof PsiLiteralExpression) { + final PsiLiteralExpression literalExpression = (PsiLiteralExpression) secondArgument; + final Object value = literalExpression.getValue(); + if (value == Boolean.TRUE) { + return "assertTrue()"; + } + else if (value == Boolean.FALSE) { + return "assertFalse()"; + } + else if (value == null) { + return "assertNull()"; + } + } + return ""; } - } - else if (isAssertThatCouldBeAssertSame(expression)) { - if (hasEqEqExpressionArgument(expression)) { - registerMethodCallError(expression, "assertSame()"); + + private static boolean hasEqEqExpressionArgument(PsiMethodCallExpression expression) { + final PsiExpressionList list = expression.getArgumentList(); + final PsiExpression[] arguments = list.getExpressions(); + final PsiExpression argument = arguments[0]; + if (!(argument instanceof PsiBinaryExpression)) { + return false; + } + final PsiBinaryExpression binaryExpression = (PsiBinaryExpression) argument; + final IElementType tokenType = binaryExpression.getOperationTokenType(); + return JavaTokenType.EQEQ.equals(tokenType); } - else { - registerMethodCallError(expression, "assertNotSame()"); - } - } - else if (isAssertTrueThatCouldBeAssertEquals(expression)) { - registerMethodCallError(expression, "assertEquals()"); - } - else if (isAssertEqualsThatCouldBeAssertLiteral(expression)) { - registerMethodCallError(expression, getReplacementMethodName(expression)); - } - else if (isAssertThatCouldBeFail(expression)) { - registerMethodCallError(expression, "fail()"); - } } - @NonNls - private static String getReplacementMethodName(PsiMethodCallExpression expression) { - final PsiExpressionList argumentList = expression.getArgumentList(); - final PsiExpression[] arguments = argumentList.getExpressions(); - final PsiExpression firstArgument = arguments[0]; - if (firstArgument instanceof PsiLiteralExpression) { - final PsiLiteralExpression literalExpression = (PsiLiteralExpression)firstArgument; - final Object value = literalExpression.getValue(); - if (value == Boolean.TRUE) { - return "assertTrue()"; - } - else if (value == Boolean.FALSE) { - return "assertFalse()"; - } - else if (value == null) { - return "assertNull()"; - } - } - final PsiExpression secondArgument = arguments[1]; - if (secondArgument instanceof PsiLiteralExpression) { - final PsiLiteralExpression literalExpression = (PsiLiteralExpression)secondArgument; - final Object value = literalExpression.getValue(); - if (value == Boolean.TRUE) { - return "assertTrue()"; - } - else if (value == Boolean.FALSE) { - return "assertFalse()"; - } - else if (value == null) { - return "assertNull()"; - } - } - return ""; + static boolean isAssertTrueThatCouldBeAssertEquals( + PsiMethodCallExpression expression + ) { + if (!isAssertTrue(expression)) { + return false; + } + final PsiReferenceExpression methodExpression = expression.getMethodExpression(); + final PsiMethod method = (PsiMethod) methodExpression.resolve(); + if (method == null) { + return false; + } + final PsiParameterList parameterList = method.getParameterList(); + if (parameterList.getParametersCount() < 1) { + return false; + } + final PsiType stringType = TypeUtils.getStringType(expression); + final PsiParameter[] parameters = parameterList.getParameters(); + final PsiType paramType1 = parameters[0].getType(); + final int testPosition; + if (paramType1.equals(stringType) && parameters.length > 1) { + testPosition = 1; + } + else { + testPosition = 0; + } + final PsiExpressionList argumentList = expression.getArgumentList(); + final PsiExpression[] arguments = argumentList.getExpressions(); + final PsiExpression testArgument = arguments[testPosition]; + return testArgument != null && isEqualityComparison(testArgument); } - private static boolean hasEqEqExpressionArgument(PsiMethodCallExpression expression) { - final PsiExpressionList list = expression.getArgumentList(); - final PsiExpression[] arguments = list.getExpressions(); - final PsiExpression argument = arguments[0]; - if (!(argument instanceof PsiBinaryExpression)) { - return false; - } - final PsiBinaryExpression binaryExpression = (PsiBinaryExpression)argument; - final IElementType tokenType = binaryExpression.getOperationTokenType(); - return JavaTokenType.EQEQ.equals(tokenType); + static boolean isAssertThatCouldBeAssertSame(PsiMethodCallExpression expression) { + if (!isAssertTrue(expression) && !isAssertFalse(expression)) { + return false; + } + final PsiReferenceExpression methodExpression = expression.getMethodExpression(); + final PsiMethod method = (PsiMethod) methodExpression.resolve(); + if (method == null) { + return false; + } + final PsiParameterList parameterList = method.getParameterList(); + if (parameterList.getParametersCount() < 1) { + return false; + } + final PsiType stringType = TypeUtils.getStringType(expression); + final PsiParameter[] parameters = parameterList.getParameters(); + final PsiType paramType1 = parameters[0].getType(); + final int testPosition; + if (paramType1.equals(stringType) && parameters.length > 1) { + testPosition = 1; + } + else { + testPosition = 0; + } + final PsiExpressionList argumentList = expression.getArgumentList(); + final PsiExpression[] arguments = argumentList.getExpressions(); + final PsiExpression testArgument = arguments[testPosition]; + return testArgument != null && isIdentityComparison(testArgument); } - } - static boolean isAssertTrueThatCouldBeAssertEquals( - PsiMethodCallExpression expression) { - if (!isAssertTrue(expression)) { - return false; - } - final PsiReferenceExpression methodExpression = expression.getMethodExpression(); - final PsiMethod method = (PsiMethod)methodExpression.resolve(); - if (method == null) { - return false; - } - final PsiParameterList parameterList = method.getParameterList(); - if (parameterList.getParametersCount() < 1) { - return false; - } - final PsiType stringType = TypeUtils.getStringType(expression); - final PsiParameter[] parameters = parameterList.getParameters(); - final PsiType paramType1 = parameters[0].getType(); - final int testPosition; - if (paramType1.equals(stringType) && parameters.length > 1) { - testPosition = 1; - } - else { - testPosition = 0; + static boolean isAssertThatCouldBeAssertNull(PsiMethodCallExpression expression) { + if (!isAssertTrue(expression) && !isAssertFalse(expression)) { + return false; + } + final PsiReferenceExpression methodExpression = expression.getMethodExpression(); + final PsiMethod method = (PsiMethod) methodExpression.resolve(); + if (method == null) { + return false; + } + final PsiParameterList parameterList = method.getParameterList(); + if (parameterList.getParametersCount() < 1) { + return false; + } + final PsiType stringType = TypeUtils.getStringType(expression); + final PsiParameter[] parameters = parameterList.getParameters(); + final PsiType paramType1 = parameters[0].getType(); + final int testPosition; + if (paramType1.equals(stringType) && parameters.length > 1) { + testPosition = 1; + } + else { + testPosition = 0; + } + final PsiExpressionList argumentList = expression.getArgumentList(); + final PsiExpression[] arguments = argumentList.getExpressions(); + final PsiExpression testArgument = arguments[testPosition]; + return testArgument != null && isNullComparison(testArgument); } - final PsiExpressionList argumentList = expression.getArgumentList(); - final PsiExpression[] arguments = argumentList.getExpressions(); - final PsiExpression testArgument = arguments[testPosition]; - return testArgument != null && isEqualityComparison(testArgument); - } - static boolean isAssertThatCouldBeAssertSame(PsiMethodCallExpression expression) { - if (!isAssertTrue(expression) && !isAssertFalse(expression)) { - return false; - } - final PsiReferenceExpression methodExpression = expression.getMethodExpression(); - final PsiMethod method = (PsiMethod)methodExpression.resolve(); - if (method == null) { - return false; - } - final PsiParameterList parameterList = method.getParameterList(); - if (parameterList.getParametersCount() < 1) { - return false; - } - final PsiType stringType = TypeUtils.getStringType(expression); - final PsiParameter[] parameters = parameterList.getParameters(); - final PsiType paramType1 = parameters[0].getType(); - final int testPosition; - if (paramType1.equals(stringType) && parameters.length > 1) { - testPosition = 1; - } - else { - testPosition = 0; - } - final PsiExpressionList argumentList = expression.getArgumentList(); - final PsiExpression[] arguments = argumentList.getExpressions(); - final PsiExpression testArgument = arguments[testPosition]; - return testArgument != null && isIdentityComparison(testArgument); - } - static boolean isAssertThatCouldBeAssertNull(PsiMethodCallExpression expression) { - if (!isAssertTrue(expression) && !isAssertFalse(expression)) { - return false; - } - final PsiReferenceExpression methodExpression = expression.getMethodExpression(); - final PsiMethod method = (PsiMethod)methodExpression.resolve(); - if (method == null) { - return false; - } - final PsiParameterList parameterList = method.getParameterList(); - if (parameterList.getParametersCount() < 1) { - return false; - } - final PsiType stringType = TypeUtils.getStringType(expression); - final PsiParameter[] parameters = parameterList.getParameters(); - final PsiType paramType1 = parameters[0].getType(); - final int testPosition; - if (paramType1.equals(stringType) && parameters.length > 1) { - testPosition = 1; - } - else { - testPosition = 0; + static boolean isAssertThatCouldBeFail(PsiMethodCallExpression expression) { + final boolean checkTrue; + if (isAssertFalse(expression)) { + checkTrue = true; + } + else if (isAssertTrue(expression)) { + checkTrue = false; + } + else { + return false; + } + final PsiReferenceExpression methodExpression = expression.getMethodExpression(); + final PsiMethod method = (PsiMethod) methodExpression.resolve(); + if (method == null) { + return false; + } + final PsiParameterList parameterList = method.getParameterList(); + if (parameterList.getParametersCount() < 1) { + return false; + } + final PsiType stringType = TypeUtils.getStringType(expression); + final PsiParameter[] parameters = parameterList.getParameters(); + final PsiType paramType1 = parameters[0].getType(); + final int testPosition; + if (paramType1.equals(stringType) && parameters.length > 1) { + testPosition = 1; + } + else { + testPosition = 0; + } + final PsiExpressionList argumentList = expression.getArgumentList(); + final PsiExpression[] arguments = argumentList.getExpressions(); + final PsiExpression testArgument = arguments[testPosition]; + if (testArgument == null) { + return false; + } + final String testArgumentText = testArgument.getText(); + if (checkTrue) { + return PsiKeyword.TRUE.equals(testArgumentText); + } + else { + return PsiKeyword.FALSE.equals(testArgumentText); + } } - final PsiExpressionList argumentList = expression.getArgumentList(); - final PsiExpression[] arguments = argumentList.getExpressions(); - final PsiExpression testArgument = arguments[testPosition]; - return testArgument != null && isNullComparison(testArgument); - } - - static boolean isAssertThatCouldBeFail(PsiMethodCallExpression expression) { - final boolean checkTrue; - if (isAssertFalse(expression)) { - checkTrue = true; - } - else if (isAssertTrue(expression)) { - checkTrue = false; - } - else { - return false; - } - final PsiReferenceExpression methodExpression = expression.getMethodExpression(); - final PsiMethod method = (PsiMethod)methodExpression.resolve(); - if (method == null) { - return false; - } - final PsiParameterList parameterList = method.getParameterList(); - if (parameterList.getParametersCount() < 1) { - return false; - } - final PsiType stringType = TypeUtils.getStringType(expression); - final PsiParameter[] parameters = parameterList.getParameters(); - final PsiType paramType1 = parameters[0].getType(); - final int testPosition; - if (paramType1.equals(stringType) && parameters.length > 1) { - testPosition = 1; - } - else { - testPosition = 0; - } - final PsiExpressionList argumentList = expression.getArgumentList(); - final PsiExpression[] arguments = argumentList.getExpressions(); - final PsiExpression testArgument = arguments[testPosition]; - if (testArgument == null) { - return false; - } - final String testArgumentText = testArgument.getText(); - if (checkTrue) { - return PsiKeyword.TRUE.equals(testArgumentText); - } - else { - return PsiKeyword.FALSE.equals(testArgumentText); + static boolean isAssertEqualsThatCouldBeAssertLiteral(PsiMethodCallExpression expression) { + if (!isAssertEquals(expression)) { + return false; + } + final PsiReferenceExpression methodExpression = expression.getMethodExpression(); + final PsiMethod method = (PsiMethod) methodExpression.resolve(); + if (method == null) { + return false; + } + final PsiParameterList parameterList = method.getParameterList(); + if (parameterList.getParametersCount() < 2) { + return false; + } + final PsiType stringType = TypeUtils.getStringType(expression); + final PsiParameter[] parameters = parameterList.getParameters(); + final PsiType paramType1 = parameters[0].getType(); + final int firstTestPosition; + final int secondTestPosition; + if (paramType1.equals(stringType) && parameters.length > 2) { + firstTestPosition = 1; + secondTestPosition = 2; + } + else { + firstTestPosition = 0; + secondTestPosition = 1; + } + final PsiExpressionList argumentList = expression.getArgumentList(); + final PsiExpression[] arguments = argumentList.getExpressions(); + final PsiExpression firstTestArgument = arguments[firstTestPosition]; + final PsiExpression secondTestArgument = arguments[secondTestPosition]; + if (firstTestArgument == null || secondTestArgument == null) { + return false; + } + return isSimpleLiteral(firstTestArgument, secondTestArgument) || + isSimpleLiteral(secondTestArgument, firstTestArgument); } - } - static boolean isAssertEqualsThatCouldBeAssertLiteral(PsiMethodCallExpression expression) { - if (!isAssertEquals(expression)) { - return false; - } - final PsiReferenceExpression methodExpression = expression.getMethodExpression(); - final PsiMethod method = (PsiMethod)methodExpression.resolve(); - if (method == null) { - return false; - } - final PsiParameterList parameterList = method.getParameterList(); - if (parameterList.getParametersCount() < 2) { - return false; - } - final PsiType stringType = TypeUtils.getStringType(expression); - final PsiParameter[] parameters = parameterList.getParameters(); - final PsiType paramType1 = parameters[0].getType(); - final int firstTestPosition; - final int secondTestPosition; - if (paramType1.equals(stringType) && parameters.length > 2) { - firstTestPosition = 1; - secondTestPosition = 2; - } - else { - firstTestPosition = 0; - secondTestPosition = 1; - } - final PsiExpressionList argumentList = expression.getArgumentList(); - final PsiExpression[] arguments = argumentList.getExpressions(); - final PsiExpression firstTestArgument = arguments[firstTestPosition]; - final PsiExpression secondTestArgument = arguments[secondTestPosition]; - if (firstTestArgument == null || secondTestArgument == null) { - return false; + static boolean isSimpleLiteral(PsiExpression expression1, PsiExpression expression2) { + if (!(expression1 instanceof PsiLiteralExpression)) { + return false; + } + final String text = expression1.getText(); + if (PsiKeyword.NULL.equals(text)) { + return true; + } + if (!PsiKeyword.TRUE.equals(text) && !PsiKeyword.FALSE.equals(text)) { + return false; + } + final PsiType type = expression2.getType(); + return PsiType.BOOLEAN.equals(type); + } + + private static boolean isEqualityComparison(PsiExpression expression) { + if (expression instanceof PsiBinaryExpression) { + final PsiBinaryExpression binaryExpression = (PsiBinaryExpression) expression; + final IElementType tokenType = binaryExpression.getOperationTokenType(); + if (!tokenType.equals(JavaTokenType.EQEQ)) { + return false; + } + final PsiExpression lhs = binaryExpression.getLOperand(); + final PsiExpression rhs = binaryExpression.getROperand(); + if (rhs == null) { + return false; + } + final PsiType type = lhs.getType(); + return type != null && ClassUtils.isPrimitive(type); + } + else if (expression instanceof PsiMethodCallExpression) { + final PsiMethodCallExpression call = (PsiMethodCallExpression) expression; + if (!MethodCallUtils.isEqualsCall(call)) { + return false; + } + final PsiReferenceExpression methodExpression = call.getMethodExpression(); + return methodExpression.getQualifierExpression() != null; + } + return false; } - return isSimpleLiteral(firstTestArgument, secondTestArgument) || - isSimpleLiteral(secondTestArgument, firstTestArgument); - } - static boolean isSimpleLiteral(PsiExpression expression1, PsiExpression expression2) { - if (!(expression1 instanceof PsiLiteralExpression)) { - return false; - } - final String text = expression1.getText(); - if (PsiKeyword.NULL.equals(text)) { - return true; - } - if (!PsiKeyword.TRUE.equals(text) && !PsiKeyword.FALSE.equals(text)) { - return false; + private static boolean isIdentityComparison(PsiExpression expression) { + if (!(expression instanceof PsiBinaryExpression)) { + return false; + } + final PsiBinaryExpression binaryExpression = (PsiBinaryExpression) expression; + if (!ComparisonUtils.isEqualityComparison(binaryExpression)) { + return false; + } + final PsiExpression rhs = binaryExpression.getROperand(); + if (rhs == null) { + return false; + } + final PsiExpression lhs = binaryExpression.getLOperand(); + final PsiType lhsType = lhs.getType(); + if (lhsType instanceof PsiPrimitiveType) { + return false; + } + final PsiType rhsType = rhs.getType(); + return !(rhsType instanceof PsiPrimitiveType); } - final PsiType type = expression2.getType(); - return PsiType.BOOLEAN.equals(type); - } - private static boolean isEqualityComparison(PsiExpression expression) { - if (expression instanceof PsiBinaryExpression) { - final PsiBinaryExpression binaryExpression = (PsiBinaryExpression)expression; - final IElementType tokenType = binaryExpression.getOperationTokenType(); - if (!tokenType.equals(JavaTokenType.EQEQ)) { - return false; - } - final PsiExpression lhs = binaryExpression.getLOperand(); - final PsiExpression rhs = binaryExpression.getROperand(); - if (rhs == null) { - return false; - } - final PsiType type = lhs.getType(); - return type != null && ClassUtils.isPrimitive(type); - } - else if (expression instanceof PsiMethodCallExpression) { - final PsiMethodCallExpression call = (PsiMethodCallExpression)expression; - if (!MethodCallUtils.isEqualsCall(call)) { - return false; - } - final PsiReferenceExpression methodExpression = call.getMethodExpression(); - return methodExpression.getQualifierExpression() != null; + private static boolean isNullComparison(PsiExpression expression) { + if (!(expression instanceof PsiBinaryExpression)) { + return false; + } + final PsiBinaryExpression binaryExpression = (PsiBinaryExpression) expression; + if (!ComparisonUtils.isEqualityComparison(binaryExpression)) { + return false; + } + final PsiExpression rhs = binaryExpression.getROperand(); + if (rhs == null) { + return false; + } + final PsiExpression lhs = binaryExpression.getLOperand(); + return PsiKeyword.NULL.equals(lhs.getText()) || PsiKeyword.NULL.equals(rhs.getText()); } - return false; - } - private static boolean isIdentityComparison(PsiExpression expression) { - if (!(expression instanceof PsiBinaryExpression)) { - return false; - } - final PsiBinaryExpression binaryExpression = (PsiBinaryExpression)expression; - if (!ComparisonUtils.isEqualityComparison(binaryExpression)) { - return false; - } - final PsiExpression rhs = binaryExpression.getROperand(); - if (rhs == null) { - return false; + private static boolean isAssertTrue(@Nonnull PsiMethodCallExpression expression) { + return isAssertMethodCall(expression, "assertTrue"); } - final PsiExpression lhs = binaryExpression.getLOperand(); - final PsiType lhsType = lhs.getType(); - if (lhsType instanceof PsiPrimitiveType) { - return false; - } - final PsiType rhsType = rhs.getType(); - return !(rhsType instanceof PsiPrimitiveType); - } - private static boolean isNullComparison(PsiExpression expression) { - if (!(expression instanceof PsiBinaryExpression)) { - return false; - } - final PsiBinaryExpression binaryExpression = (PsiBinaryExpression)expression; - if (!ComparisonUtils.isEqualityComparison(binaryExpression)) { - return false; + private static boolean isAssertFalse(@Nonnull PsiMethodCallExpression expression) { + return isAssertMethodCall(expression, "assertFalse"); } - final PsiExpression rhs = binaryExpression.getROperand(); - if (rhs == null) { - return false; - } - final PsiExpression lhs = binaryExpression.getLOperand(); - return PsiKeyword.NULL.equals(lhs.getText()) || PsiKeyword.NULL.equals(rhs.getText()); - } - - private static boolean isAssertTrue(@Nonnull PsiMethodCallExpression expression) { - return isAssertMethodCall(expression, "assertTrue"); - } - private static boolean isAssertFalse(@Nonnull PsiMethodCallExpression expression) { - return isAssertMethodCall(expression, "assertFalse"); - } - - private static boolean isAssertEquals(@Nonnull PsiMethodCallExpression expression) { - return isAssertMethodCall(expression, "assertEquals"); - } - - private static boolean isAssertMethodCall(@Nonnull PsiMethodCallExpression expression, - @NonNls @Nonnull String assertMethodName) { - final PsiReferenceExpression methodExpression = expression.getMethodExpression(); - @NonNls final String methodName = methodExpression.getReferenceName(); - if (!assertMethodName.equals(methodName)) { - return false; + private static boolean isAssertEquals(@Nonnull PsiMethodCallExpression expression) { + return isAssertMethodCall(expression, "assertEquals"); } - final PsiMethod method = (PsiMethod)methodExpression.resolve(); - if (method == null) { - return false; - } - final PsiClass targetClass = method.getContainingClass(); - if (targetClass == null) { - return false; + + private static boolean isAssertMethodCall( + @Nonnull PsiMethodCallExpression expression, + @NonNls @Nonnull String assertMethodName + ) { + final PsiReferenceExpression methodExpression = expression.getMethodExpression(); + @NonNls final String methodName = methodExpression.getReferenceName(); + if (!assertMethodName.equals(methodName)) { + return false; + } + final PsiMethod method = (PsiMethod) methodExpression.resolve(); + if (method == null) { + return false; + } + final PsiClass targetClass = method.getContainingClass(); + if (targetClass == null) { + return false; + } + final String qualifiedName = targetClass.getQualifiedName(); + return "junit.framework.Assert".equals(qualifiedName) || "org.junit.Assert".equals(qualifiedName); } - final String qualifiedName = targetClass.getQualifiedName(); - return "junit.framework.Assert".equals(qualifiedName) || "org.junit.Assert".equals(qualifiedName); - } } diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/junit/StaticSuiteInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/junit/StaticSuiteInspection.java index e4d66cf20d..2df95297fc 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/junit/StaticSuiteInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/junit/StaticSuiteInspection.java @@ -24,60 +24,63 @@ import com.siyeh.ig.BaseInspectionVisitor; import com.siyeh.localize.InspectionGadgetsLocalize; import consulo.annotation.component.ExtensionImpl; +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; import org.jetbrains.annotations.NonNls; @ExtensionImpl public class StaticSuiteInspection extends BaseInspection { - @Override - @Nonnull - public String getID() { - return "SuiteNotDeclaredStatic"; - } + @Override + @Nonnull + public String getID() { + return "SuiteNotDeclaredStatic"; + } - @Override - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.staticSuiteDisplayName().get(); - } + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.staticSuiteDisplayName(); + } - @Override - @Nonnull - protected String buildErrorString(Object... infos) { - return InspectionGadgetsLocalize.staticSuiteProblemDescriptor().get(); - } + @Override + @Nonnull + protected String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.staticSuiteProblemDescriptor().get(); + } - @Override - public BaseInspectionVisitor buildVisitor() { - return new StaticSuiteVisitor(); - } + @Override + public BaseInspectionVisitor buildVisitor() { + return new StaticSuiteVisitor(); + } - private static class StaticSuiteVisitor extends BaseInspectionVisitor { + private static class StaticSuiteVisitor extends BaseInspectionVisitor { - @Override - public void visitMethod(@Nonnull PsiMethod method) { - //note: no call to super - @NonNls final String methodName = method.getName(); - if (!"suite".equals(methodName)) { - return; - } - final PsiClass aClass = method.getContainingClass(); - if (aClass == null) { - return; - } - if (!InheritanceUtil.isInheritor(aClass, - "junit.framework.TestCase")) { - return; - } - final PsiParameterList parameterList = method.getParameterList(); - if (parameterList.getParametersCount() != 0) { - return; - } - if (method.hasModifierProperty(PsiModifier.STATIC)) { - return; - } - registerMethodError(method); + @Override + public void visitMethod(@Nonnull PsiMethod method) { + //note: no call to super + @NonNls final String methodName = method.getName(); + if (!"suite".equals(methodName)) { + return; + } + final PsiClass aClass = method.getContainingClass(); + if (aClass == null) { + return; + } + if (!InheritanceUtil.isInheritor( + aClass, + "junit.framework.TestCase" + )) { + return; + } + final PsiParameterList parameterList = method.getParameterList(); + if (parameterList.getParametersCount() != 0) { + return; + } + if (method.hasModifierProperty(PsiModifier.STATIC)) { + return; + } + registerMethodError(method); + } } - } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/junit/TestCaseInProductCodeInspectionBase.java b/plugin/src/main/java/com/intellij/java/impl/ig/junit/TestCaseInProductCodeInspectionBase.java index 5bed9b4db6..8aa18638c2 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/junit/TestCaseInProductCodeInspectionBase.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/junit/TestCaseInProductCodeInspectionBase.java @@ -21,55 +21,47 @@ import com.siyeh.ig.psiutils.TestUtils; import com.siyeh.localize.InspectionGadgetsLocalize; import consulo.annotation.component.ExtensionImpl; +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; @ExtensionImpl -public class TestCaseInProductCodeInspectionBase extends BaseInspection -{ - @Override - @Nonnull - public String getDisplayName() - { - return InspectionGadgetsLocalize.testCaseInProductCodeDisplayName().get(); - } +public class TestCaseInProductCodeInspectionBase extends BaseInspection { + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.testCaseInProductCodeDisplayName(); + } - @Override - @Nonnull - public String getID() - { - return "JUnitTestCaseInProductSource"; - } + @Override + @Nonnull + public String getID() { + return "JUnitTestCaseInProductSource"; + } - @Override - @Nonnull - protected String buildErrorString(Object... infos) - { - return InspectionGadgetsLocalize.testCaseInProductCodeProblemDescriptor().get(); - } + @Override + @Nonnull + protected String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.testCaseInProductCodeProblemDescriptor().get(); + } - @Override - protected boolean buildQuickFixesOnlyForOnTheFlyErrors() - { - return true; - } + @Override + protected boolean buildQuickFixesOnlyForOnTheFlyErrors() { + return true; + } - @Override - public BaseInspectionVisitor buildVisitor() - { - return new TestCaseInProductCodeVisitor(); - } + @Override + public BaseInspectionVisitor buildVisitor() { + return new TestCaseInProductCodeVisitor(); + } - private static class TestCaseInProductCodeVisitor extends BaseInspectionVisitor - { + private static class TestCaseInProductCodeVisitor extends BaseInspectionVisitor { - @Override - public void visitClass(@Nonnull PsiClass aClass) - { - if(TestUtils.isInTestSourceContent(aClass) || !TestUtils.isJUnitTestClass(aClass)) - { - return; - } - registerClassError(aClass); - } - } + @Override + public void visitClass(@Nonnull PsiClass aClass) { + if (TestUtils.isInTestSourceContent(aClass) || !TestUtils.isJUnitTestClass(aClass)) { + return; + } + registerClassError(aClass); + } + } } diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/junit/TestCaseWithConstructorInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/junit/TestCaseWithConstructorInspection.java index 44290d0271..504adcbc75 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/junit/TestCaseWithConstructorInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/junit/TestCaseWithConstructorInspection.java @@ -21,6 +21,7 @@ import com.siyeh.ig.psiutils.TestUtils; import com.siyeh.localize.InspectionGadgetsLocalize; import consulo.annotation.component.ExtensionImpl; +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; @@ -33,8 +34,9 @@ public String getID() { } @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.testCaseWithConstructorDisplayName().get(); + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.testCaseWithConstructorDisplayName(); } @Nonnull diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/junit/TestCaseWithNoTestMethodsInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/junit/TestCaseWithNoTestMethodsInspection.java index eae7aa2fbe..c8b813638e 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/junit/TestCaseWithNoTestMethodsInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/junit/TestCaseWithNoTestMethodsInspection.java @@ -34,76 +34,77 @@ @ExtensionImpl public class TestCaseWithNoTestMethodsInspection extends BaseInspection { + @SuppressWarnings({"PublicField"}) + public boolean ignoreSupers = false; - @SuppressWarnings({"PublicField"}) - public boolean ignoreSupers = false; - - @Override - @Nonnull - public String getID() { - return "JUnitTestCaseWithNoTests"; - } + @Override + @Nonnull + public String getID() { + return "JUnitTestCaseWithNoTests"; + } - @Override - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.testCaseWithNoTestMethodsDisplayName().get(); - } + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.testCaseWithNoTestMethodsDisplayName(); + } - @Override - @Nonnull - protected String buildErrorString(Object... infos) { - return InspectionGadgetsLocalize.testCaseWithNoTestMethodsProblemDescriptor().get(); - } + @Override + @Nonnull + protected String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.testCaseWithNoTestMethodsProblemDescriptor().get(); + } - @Override - @Nullable - public JComponent createOptionsPanel() { - LocalizeValue message = InspectionGadgetsLocalize.testCaseWithNoTestMethodsOption(); - return new SingleCheckboxOptionsPanel(message.get(), this, "ignoreSupers"); - } + @Override + @Nullable + public JComponent createOptionsPanel() { + LocalizeValue message = InspectionGadgetsLocalize.testCaseWithNoTestMethodsOption(); + return new SingleCheckboxOptionsPanel(message.get(), this, "ignoreSupers"); + } - @Override - public BaseInspectionVisitor buildVisitor() { - return new TestCaseWithNoTestMethodsVisitor(); - } + @Override + public BaseInspectionVisitor buildVisitor() { + return new TestCaseWithNoTestMethodsVisitor(); + } - private class TestCaseWithNoTestMethodsVisitor - extends BaseInspectionVisitor { + private class TestCaseWithNoTestMethodsVisitor + extends BaseInspectionVisitor { - @Override - public void visitClass(@Nonnull PsiClass aClass) { - if (aClass.isInterface() - || aClass.isEnum() - || aClass.isAnnotationType() - || aClass.hasModifierProperty(PsiModifier.ABSTRACT)) { - return; - } - if (aClass instanceof PsiTypeParameter) { - return; - } - if (!InheritanceUtil.isInheritor(aClass, - "junit.framework.TestCase")) { - return; - } - final PsiMethod[] methods = aClass.getMethods(); - for (final PsiMethod method : methods) { - if (TestUtils.isJUnitTestMethod(method)) { - return; - } - } - if (ignoreSupers) { - final PsiClass superClass = aClass.getSuperClass(); - if (superClass != null) { - final PsiMethod[] superMethods = superClass.getMethods(); - for (PsiMethod superMethod : superMethods) { - if (TestUtils.isJUnitTestMethod(superMethod)) { - return; + @Override + public void visitClass(@Nonnull PsiClass aClass) { + if (aClass.isInterface() + || aClass.isEnum() + || aClass.isAnnotationType() + || aClass.hasModifierProperty(PsiModifier.ABSTRACT)) { + return; + } + if (aClass instanceof PsiTypeParameter) { + return; + } + if (!InheritanceUtil.isInheritor( + aClass, + "junit.framework.TestCase" + )) { + return; + } + final PsiMethod[] methods = aClass.getMethods(); + for (final PsiMethod method : methods) { + if (TestUtils.isJUnitTestMethod(method)) { + return; + } + } + if (ignoreSupers) { + final PsiClass superClass = aClass.getSuperClass(); + if (superClass != null) { + final PsiMethod[] superMethods = superClass.getMethods(); + for (PsiMethod superMethod : superMethods) { + if (TestUtils.isJUnitTestMethod(superMethod)) { + return; + } + } + } } - } + registerClassError(aClass); } - } - registerClassError(aClass); } - } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/junit/TestMethodInProductCodeInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/junit/TestMethodInProductCodeInspection.java index f52eadb740..008baa9414 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/junit/TestMethodInProductCodeInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/junit/TestMethodInProductCodeInspection.java @@ -22,51 +22,43 @@ import com.siyeh.ig.psiutils.TestUtils; import com.siyeh.localize.InspectionGadgetsLocalize; import consulo.annotation.component.ExtensionImpl; +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; @ExtensionImpl -public class TestMethodInProductCodeInspection extends BaseInspection -{ +public class TestMethodInProductCodeInspection extends BaseInspection { + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.testMethodInProductCodeDisplayName(); + } - @Override - @Nonnull - public String getDisplayName() - { - return InspectionGadgetsLocalize.testMethodInProductCodeDisplayName().get(); - } + @Override + @Nonnull + public String getID() { + return "JUnitTestMethodInProductSource"; + } - @Override - @Nonnull - public String getID() - { - return "JUnitTestMethodInProductSource"; - } + @Override + @Nonnull + protected String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.testMethodInProductCodeProblemDescriptor().get(); + } - @Override - @Nonnull - protected String buildErrorString(Object... infos) - { - return InspectionGadgetsLocalize.testMethodInProductCodeProblemDescriptor().get(); - } + @Override + public BaseInspectionVisitor buildVisitor() { + return new TestCaseInProductCodeVisitor(); + } - @Override - public BaseInspectionVisitor buildVisitor() - { - return new TestCaseInProductCodeVisitor(); - } + private static class TestCaseInProductCodeVisitor extends BaseInspectionVisitor { - private static class TestCaseInProductCodeVisitor extends BaseInspectionVisitor - { - - @Override - public void visitMethod(PsiMethod method) - { - final PsiClass containingClass = method.getContainingClass(); - if(TestUtils.isInTestSourceContent(containingClass) || !TestUtils.isAnnotatedTestMethod(method)) - { - return; - } - registerMethodError(method); - } - } + @Override + public void visitMethod(PsiMethod method) { + final PsiClass containingClass = method.getContainingClass(); + if (TestUtils.isInTestSourceContent(containingClass) || !TestUtils.isAnnotatedTestMethod(method)) { + return; + } + registerMethodError(method); + } + } } diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/junit/TestMethodIsPublicVoidNoArgInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/junit/TestMethodIsPublicVoidNoArgInspection.java index d52b06e9f5..5c0abcc4dc 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/junit/TestMethodIsPublicVoidNoArgInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/junit/TestMethodIsPublicVoidNoArgInspection.java @@ -23,82 +23,85 @@ import com.siyeh.ig.psiutils.TestUtils; import com.siyeh.localize.InspectionGadgetsLocalize; import consulo.annotation.component.ExtensionImpl; +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; import org.jetbrains.annotations.NonNls; @ExtensionImpl public class TestMethodIsPublicVoidNoArgInspection extends BaseInspection { + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.testMethodIsPublicVoidNoArgDisplayName(); + } - @Override - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.testMethodIsPublicVoidNoArgDisplayName().get(); - } - - @Override - @Nonnull - public String getID() { - return "TestMethodWithIncorrectSignature"; - } + @Override + @Nonnull + public String getID() { + return "TestMethodWithIncorrectSignature"; + } - @Override - @Nonnull - public String buildErrorString(Object... infos) { - final boolean isStatic = (Boolean)infos[1]; - if (isStatic) { - return InspectionGadgetsLocalize.testMethodIsPublicVoidNoArgProblemDescriptor3().get(); + @Override + @Nonnull + public String buildErrorString(Object... infos) { + final boolean isStatic = (Boolean) infos[1]; + if (isStatic) { + return InspectionGadgetsLocalize.testMethodIsPublicVoidNoArgProblemDescriptor3().get(); + } + final boolean takesArguments = (Boolean) infos[0]; + return takesArguments + ? InspectionGadgetsLocalize.testMethodIsPublicVoidNoArgProblemDescriptor1().get() + : InspectionGadgetsLocalize.testMethodIsPublicVoidNoArgProblemDescriptor2().get(); } - final boolean takesArguments = (Boolean)infos[0]; - return takesArguments - ? InspectionGadgetsLocalize.testMethodIsPublicVoidNoArgProblemDescriptor1().get() - : InspectionGadgetsLocalize.testMethodIsPublicVoidNoArgProblemDescriptor2().get(); - } - @Override - public BaseInspectionVisitor buildVisitor() { - return new TestMethodIsPublicVoidNoArgVisitor(); - } + @Override + public BaseInspectionVisitor buildVisitor() { + return new TestMethodIsPublicVoidNoArgVisitor(); + } - private static class TestMethodIsPublicVoidNoArgVisitor - extends BaseInspectionVisitor { + private static class TestMethodIsPublicVoidNoArgVisitor + extends BaseInspectionVisitor { - @Override - public void visitMethod(@Nonnull PsiMethod method) { - //note: no call to super; - @NonNls final String methodName = method.getName(); - if (!methodName.startsWith("test") && - !TestUtils.isJUnit4TestMethod(method)) { - return; - } - final PsiType returnType = method.getReturnType(); - if (returnType == null) { - return; - } - final PsiParameterList parameterList = method.getParameterList(); - final boolean takesArguments; - final boolean isStatic; - if (parameterList.getParametersCount() == 0) { - takesArguments = false; - isStatic = method.hasModifierProperty(PsiModifier.STATIC); - if (!isStatic && returnType.equals(PsiType.VOID) && - method.hasModifierProperty(PsiModifier.PUBLIC)) { - return; - } - } - else { - isStatic = false; - takesArguments = true; - } - final PsiClass targetClass = method.getContainingClass(); - if (!AnnotationUtil.isAnnotated(method, "org.junit.Test", true)) { - if (targetClass == null || - !InheritanceUtil.isInheritor(targetClass, - "junit.framework.TestCase")) { - return; + @Override + public void visitMethod(@Nonnull PsiMethod method) { + //note: no call to super; + @NonNls final String methodName = method.getName(); + if (!methodName.startsWith("test") && + !TestUtils.isJUnit4TestMethod(method)) { + return; + } + final PsiType returnType = method.getReturnType(); + if (returnType == null) { + return; + } + final PsiParameterList parameterList = method.getParameterList(); + final boolean takesArguments; + final boolean isStatic; + if (parameterList.getParametersCount() == 0) { + takesArguments = false; + isStatic = method.hasModifierProperty(PsiModifier.STATIC); + if (!isStatic && returnType.equals(PsiType.VOID) && + method.hasModifierProperty(PsiModifier.PUBLIC)) { + return; + } + } + else { + isStatic = false; + takesArguments = true; + } + final PsiClass targetClass = method.getContainingClass(); + if (!AnnotationUtil.isAnnotated(method, "org.junit.Test", true)) { + if (targetClass == null || + !InheritanceUtil.isInheritor( + targetClass, + "junit.framework.TestCase" + )) { + return; + } + } + registerMethodError(method, Boolean.valueOf(takesArguments), + Boolean.valueOf(isStatic) + ); } - } - registerMethodError(method, Boolean.valueOf(takesArguments), - Boolean.valueOf(isStatic)); } - } } diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/junit/UnconstructableTestCaseInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/junit/UnconstructableTestCaseInspection.java index 32c2bf1932..8239a8ef97 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/junit/UnconstructableTestCaseInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/junit/UnconstructableTestCaseInspection.java @@ -22,82 +22,77 @@ import com.siyeh.ig.psiutils.TypeUtils; import com.siyeh.localize.InspectionGadgetsLocalize; import consulo.annotation.component.ExtensionImpl; +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; @ExtensionImpl public class UnconstructableTestCaseInspection extends BaseInspection { + @Override + @Nonnull + public String getID() { + return "UnconstructableJUnitTestCase"; + } - @Override - @Nonnull - public String getID() { - return "UnconstructableJUnitTestCase"; - } - - @Override - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.unconstructableTestCaseDisplayName().get(); - } - - @Override - @Nonnull - protected String buildErrorString(Object... infos) { - return InspectionGadgetsLocalize.unconstructableTestCaseProblemDescriptor().get(); - } - - @Override - public BaseInspectionVisitor buildVisitor() { - return new UnconstructableTestCaseVisitor(); - } + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.unconstructableTestCaseDisplayName(); + } - private static class UnconstructableTestCaseVisitor - extends BaseInspectionVisitor { + @Override + @Nonnull + protected String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.unconstructableTestCaseProblemDescriptor().get(); + } @Override - public void visitClass(@Nonnull PsiClass aClass) { - if (aClass.isInterface() || aClass.isEnum() || - aClass.isAnnotationType() || - aClass.hasModifierProperty(PsiModifier.ABSTRACT)) { - return; - } - if (aClass instanceof PsiTypeParameter) { - return; - } - if (!InheritanceUtil.isInheritor(aClass, - "junit.framework.TestCase")) { - return; - } - final PsiMethod[] constructors = aClass.getConstructors(); - boolean hasStringConstructor = false; - boolean hasNoArgConstructor = false; - boolean hasConstructor = false; - for (final PsiMethod constructor : constructors) { - hasConstructor = true; - if (!constructor.hasModifierProperty(PsiModifier.PUBLIC)) { - continue; - } - final PsiParameterList parameterList = - constructor.getParameterList(); - final int parametersCount = parameterList.getParametersCount(); - if (parametersCount == 0) { - hasNoArgConstructor = true; - } - if (parametersCount == 1) { - final PsiParameter[] parameters = - parameterList.getParameters(); - final PsiType type = parameters[0].getType(); - if (TypeUtils.typeEquals(CommonClassNames.JAVA_LANG_STRING, type)) { - hasStringConstructor = true; - } + public BaseInspectionVisitor buildVisitor() { + return new UnconstructableTestCaseVisitor(); + } + + private static class UnconstructableTestCaseVisitor extends BaseInspectionVisitor { + @Override + public void visitClass(@Nonnull PsiClass aClass) { + if (aClass.isInterface() || aClass.isEnum() || + aClass.isAnnotationType() || + aClass.hasModifierProperty(PsiModifier.ABSTRACT)) { + return; + } + if (aClass instanceof PsiTypeParameter) { + return; + } + if (!InheritanceUtil.isInheritor(aClass, "junit.framework.TestCase")) { + return; + } + final PsiMethod[] constructors = aClass.getConstructors(); + boolean hasStringConstructor = false; + boolean hasNoArgConstructor = false; + boolean hasConstructor = false; + for (final PsiMethod constructor : constructors) { + hasConstructor = true; + if (!constructor.hasModifierProperty(PsiModifier.PUBLIC)) { + continue; + } + final PsiParameterList parameterList = constructor.getParameterList(); + final int parametersCount = parameterList.getParametersCount(); + if (parametersCount == 0) { + hasNoArgConstructor = true; + } + if (parametersCount == 1) { + final PsiParameter[] parameters = parameterList.getParameters(); + final PsiType type = parameters[0].getType(); + if (TypeUtils.typeEquals(CommonClassNames.JAVA_LANG_STRING, type)) { + hasStringConstructor = true; + } + } + } + if (!hasConstructor) { + return; + } + if (hasNoArgConstructor || hasStringConstructor) { + return; + } + registerClassError(aClass); } - } - if (!hasConstructor) { - return; - } - if (hasNoArgConstructor || hasStringConstructor) { - return; - } - registerClassError(aClass); } - } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/logging/NonStaticFinalLoggerInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/logging/NonStaticFinalLoggerInspection.java index 24eda32473..9e9ab5d71c 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/logging/NonStaticFinalLoggerInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/logging/NonStaticFinalLoggerInspection.java @@ -23,6 +23,7 @@ import com.siyeh.ig.InspectionGadgetsFix; import com.siyeh.localize.InspectionGadgetsLocalize; import consulo.annotation.component.ExtensionImpl; +import consulo.localize.LocalizeValue; import consulo.ui.ex.awt.table.ListTable; import consulo.ui.ex.awt.table.ListWrappingTableModel; import consulo.util.xml.serializer.InvalidDataException; @@ -37,90 +38,91 @@ @ExtensionImpl public class NonStaticFinalLoggerInspection extends BaseInspection { - @SuppressWarnings("PublicField") - public String loggerClassName = "java.util.logging.Logger" + ',' + - "org.slf4j.Logger" + ',' + - "org.apache.commons.logging.Log" + ',' + - "org.apache.log4j.Logger"; - - private final List loggerClassNames = new ArrayList(); - - @Override - @Nonnull - public String getID() { - return "NonConstantLogger"; - } - - @Override - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.nonConstantLoggerDisplayName().get(); - } - - @Override - @Nonnull - protected String buildErrorString(Object... infos) { - return InspectionGadgetsLocalize.nonConstantLoggerProblemDescriptor().get(); - } - - @Override - protected InspectionGadgetsFix buildFix(Object... infos) { - final PsiField field = (PsiField)infos[0]; - return MakeFieldStaticFinalFix.buildFixUnconditional(field); - } - - @Override - public void readSettings(@Nonnull Element element) throws InvalidDataException { - super.readSettings(element); - parseString(loggerClassName, loggerClassNames); - } - - @Override - public void writeSettings(@Nonnull Element element) throws WriteExternalException { - loggerClassName = formatString(loggerClassNames); - super.writeSettings(element); - } - - @Override - public JComponent createOptionsPanel() { - final ListTable table = new ListTable(new ListWrappingTableModel(loggerClassNames, InspectionGadgetsLocalize.loggerClassName().get())); - return UiUtils.createAddRemoveTreeClassChooserPanel(table, InspectionGadgetsLocalize.chooseLoggerClass().get()); - } - - @Override - public BaseInspectionVisitor buildVisitor() { - return new NonStaticFinalLoggerVisitor(); - } - - private class NonStaticFinalLoggerVisitor extends BaseInspectionVisitor { + @SuppressWarnings("PublicField") + public String loggerClassName = "java.util.logging.Logger" + ',' + + "org.slf4j.Logger" + ',' + + "org.apache.commons.logging.Log" + ',' + + "org.apache.log4j.Logger"; + + private final List loggerClassNames = new ArrayList(); @Override - public void visitClass(@Nonnull PsiClass aClass) { - if (aClass.isInterface() || aClass.isEnum() || aClass.isAnnotationType()) { - return; - } - if (aClass instanceof PsiTypeParameter) { - return; - } - if (aClass.getContainingClass() != null) { - return; - } - final PsiField[] fields = aClass.getFields(); - for (final PsiField field : fields) { - if (!isLogger(field)) { - continue; - } - if (field.hasModifierProperty(PsiModifier.STATIC) && field.hasModifierProperty(PsiModifier.FINAL)) { - continue; - } - registerFieldError(field, field); - } + @Nonnull + public String getID() { + return "NonConstantLogger"; + } + + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.nonConstantLoggerDisplayName(); + } + + @Override + @Nonnull + protected String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.nonConstantLoggerProblemDescriptor().get(); } - private boolean isLogger(PsiVariable variable) { - final PsiType type = variable.getType(); - final String text = type.getCanonicalText(); - return loggerClassNames.contains(text); + @Override + protected InspectionGadgetsFix buildFix(Object... infos) { + final PsiField field = (PsiField) infos[0]; + return MakeFieldStaticFinalFix.buildFixUnconditional(field); + } + + @Override + public void readSettings(@Nonnull Element element) throws InvalidDataException { + super.readSettings(element); + parseString(loggerClassName, loggerClassNames); + } + + @Override + public void writeSettings(@Nonnull Element element) throws WriteExternalException { + loggerClassName = formatString(loggerClassNames); + super.writeSettings(element); + } + + @Override + public JComponent createOptionsPanel() { + final ListTable table = + new ListTable(new ListWrappingTableModel(loggerClassNames, InspectionGadgetsLocalize.loggerClassName().get())); + return UiUtils.createAddRemoveTreeClassChooserPanel(table, InspectionGadgetsLocalize.chooseLoggerClass().get()); + } + + @Override + public BaseInspectionVisitor buildVisitor() { + return new NonStaticFinalLoggerVisitor(); + } + + private class NonStaticFinalLoggerVisitor extends BaseInspectionVisitor { + + @Override + public void visitClass(@Nonnull PsiClass aClass) { + if (aClass.isInterface() || aClass.isEnum() || aClass.isAnnotationType()) { + return; + } + if (aClass instanceof PsiTypeParameter) { + return; + } + if (aClass.getContainingClass() != null) { + return; + } + final PsiField[] fields = aClass.getFields(); + for (final PsiField field : fields) { + if (!isLogger(field)) { + continue; + } + if (field.hasModifierProperty(PsiModifier.STATIC) && field.hasModifierProperty(PsiModifier.FINAL)) { + continue; + } + registerFieldError(field, field); + } + } + + private boolean isLogger(PsiVariable variable) { + final PsiType type = variable.getType(); + final String text = type.getCanonicalText(); + return loggerClassNames.contains(text); + } } - } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/logging/PlaceholderCountMatchesArgumentCountInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/logging/PlaceholderCountMatchesArgumentCountInspection.java index 1217e256a2..cac3c5a11f 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/logging/PlaceholderCountMatchesArgumentCountInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/logging/PlaceholderCountMatchesArgumentCountInspection.java @@ -23,103 +23,100 @@ import com.siyeh.localize.InspectionGadgetsLocalize; import consulo.annotation.component.ExtensionImpl; import consulo.ide.impl.idea.util.containers.ContainerUtilRt; +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; -import org.jetbrains.annotations.Nls; -import org.jetbrains.annotations.NonNls; import java.util.Set; @ExtensionImpl public class PlaceholderCountMatchesArgumentCountInspection extends BaseInspection { + private static final Set loggingMethodNames = ContainerUtilRt.newHashSet("trace", "debug", "info", "warn", "error"); - @NonNls - private static final Set loggingMethodNames = ContainerUtilRt.newHashSet("trace", "debug", "info", "warn", "error"); - - @Nls - @Nonnull - @Override - public String getDisplayName() { - return InspectionGadgetsLocalize.placeholderCountMatchesArgumentCountDisplayName().get(); - } + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.placeholderCountMatchesArgumentCountDisplayName(); + } - @Nonnull - @Override - protected String buildErrorString(Object... infos) { - final int argumentCount = (Integer)infos[0]; - final int placeholderCount = (Integer)infos[1]; - return argumentCount > placeholderCount - ? InspectionGadgetsLocalize.placeholderCountMatchesArgumentCountMoreProblemDescriptor(argumentCount, placeholderCount).get() - : InspectionGadgetsLocalize.placeholderCountMatchesArgumentCountFewerProblemDescriptor(argumentCount, placeholderCount).get(); - } + @Nonnull + @Override + protected String buildErrorString(Object... infos) { + final int argumentCount = (Integer) infos[0]; + final int placeholderCount = (Integer) infos[1]; + return argumentCount > placeholderCount + ? InspectionGadgetsLocalize.placeholderCountMatchesArgumentCountMoreProblemDescriptor(argumentCount, placeholderCount).get() + : InspectionGadgetsLocalize.placeholderCountMatchesArgumentCountFewerProblemDescriptor(argumentCount, placeholderCount).get(); + } - @Override - public BaseInspectionVisitor buildVisitor() { - return new PlaceholderCountMatchesArgumentCountVisitor(); - } + @Override + public BaseInspectionVisitor buildVisitor() { + return new PlaceholderCountMatchesArgumentCountVisitor(); + } - private static class PlaceholderCountMatchesArgumentCountVisitor extends BaseInspectionVisitor { + private static class PlaceholderCountMatchesArgumentCountVisitor extends BaseInspectionVisitor { - @Override - public void visitMethodCallExpression(PsiMethodCallExpression expression) { - super.visitMethodCallExpression(expression); - final PsiReferenceExpression methodExpression = expression.getMethodExpression(); - final String name = methodExpression.getReferenceName(); - if (!loggingMethodNames.contains(name)) { - return; - } - final PsiExpressionList argumentList = expression.getArgumentList(); - final PsiExpression[] arguments = argumentList.getExpressions(); - if (arguments.length == 0) { - return; - } - final PsiExpression firstArgument = arguments[0]; - final int placeholderCount; - final int argumentCount; - if (InheritanceUtil.isInheritor(firstArgument.getType(), "org.slf4j.Marker")) { - if (arguments.length < 2) { - return; - } - final PsiExpression secondArgument = arguments[1]; - if (!ExpressionUtils.hasStringType(secondArgument)) { - return; - } - final String value = (String)ExpressionUtils.computeConstantExpression(secondArgument); - if (value == null) { - return; - } - placeholderCount = countPlaceholders(value); - argumentCount = hasThrowableType(arguments[arguments.length - 1]) ? arguments.length - 3 : arguments.length - 2; - } - else if (ExpressionUtils.hasStringType(firstArgument)) { - final String value = (String)ExpressionUtils.computeConstantExpression(firstArgument); - if (value == null) { - return; + @Override + public void visitMethodCallExpression(PsiMethodCallExpression expression) { + super.visitMethodCallExpression(expression); + final PsiReferenceExpression methodExpression = expression.getMethodExpression(); + final String name = methodExpression.getReferenceName(); + if (!loggingMethodNames.contains(name)) { + return; + } + final PsiExpressionList argumentList = expression.getArgumentList(); + final PsiExpression[] arguments = argumentList.getExpressions(); + if (arguments.length == 0) { + return; + } + final PsiExpression firstArgument = arguments[0]; + final int placeholderCount; + final int argumentCount; + if (InheritanceUtil.isInheritor(firstArgument.getType(), "org.slf4j.Marker")) { + if (arguments.length < 2) { + return; + } + final PsiExpression secondArgument = arguments[1]; + if (!ExpressionUtils.hasStringType(secondArgument)) { + return; + } + final String value = (String) ExpressionUtils.computeConstantExpression(secondArgument); + if (value == null) { + return; + } + placeholderCount = countPlaceholders(value); + argumentCount = hasThrowableType(arguments[arguments.length - 1]) ? arguments.length - 3 : arguments.length - 2; + } + else if (ExpressionUtils.hasStringType(firstArgument)) { + final String value = (String) ExpressionUtils.computeConstantExpression(firstArgument); + if (value == null) { + return; + } + placeholderCount = countPlaceholders(value); + argumentCount = hasThrowableType(arguments[arguments.length - 1]) ? arguments.length - 2 : arguments.length - 1; + } + else { + return; + } + if (placeholderCount == argumentCount) { + return; + } + registerMethodCallError(expression, argumentCount, placeholderCount); } - placeholderCount = countPlaceholders(value); - argumentCount = hasThrowableType(arguments[arguments.length - 1]) ? arguments.length - 2 : arguments.length - 1; - } else { - return; - } - if (placeholderCount == argumentCount) { - return; - } - registerMethodCallError(expression, argumentCount, placeholderCount); - } - private static boolean hasThrowableType(PsiExpression lastArgument) { - return InheritanceUtil.isInheritor(lastArgument.getType(), CommonClassNames.JAVA_LANG_THROWABLE); - } + private static boolean hasThrowableType(PsiExpression lastArgument) { + return InheritanceUtil.isInheritor(lastArgument.getType(), CommonClassNames.JAVA_LANG_THROWABLE); + } - public static int countPlaceholders(String value) { - int count = 0; - int index = value.indexOf("{}"); - while (index >= 0) { - if (index <= 0 || value.charAt(index - 1) != '\\') { - count++; + public static int countPlaceholders(String value) { + int count = 0; + int index = value.indexOf("{}"); + while (index >= 0) { + if (index <= 0 || value.charAt(index - 1) != '\\') { + count++; + } + index = value.indexOf("{}", index + 1); + } + return count; } - index = value.indexOf("{}", index + 1); - } - return count; } - } } diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/logging/PublicMethodWithoutLoggingInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/logging/PublicMethodWithoutLoggingInspection.java index 243f9cf646..c7ca1d6410 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/logging/PublicMethodWithoutLoggingInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/logging/PublicMethodWithoutLoggingInspection.java @@ -23,6 +23,7 @@ import com.siyeh.localize.InspectionGadgetsLocalize; import consulo.annotation.component.ExtensionImpl; import consulo.language.psi.PsiElement; +import consulo.localize.LocalizeValue; import consulo.ui.ex.awt.table.ListTable; import consulo.ui.ex.awt.table.ListWrappingTableModel; import consulo.util.xml.serializer.InvalidDataException; @@ -37,121 +38,121 @@ @ExtensionImpl public class PublicMethodWithoutLoggingInspection extends BaseInspection { - @SuppressWarnings("PublicField") - public String loggerClassName = "java.util.logging.Logger" + ',' + - "org.slf4j.Logger" + ',' + - "org.apache.commons.logging.Log" + ',' + - "org.apache.log4j.Logger"; - - private final List loggerClassNames = new ArrayList(); - - @Override - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.publicMethodWithoutLoggingDisplayName().get(); - } - - @Override - @Nonnull - public String buildErrorString(Object... infos) { - return InspectionGadgetsLocalize.publicMethodWithoutLoggingProblemDescriptor().get(); - } - - @Override - public JComponent createOptionsPanel() { - final ListTable table = new ListTable( - new ListWrappingTableModel(loggerClassNames, InspectionGadgetsLocalize.loggerClassName().get())); - return UiUtils.createAddRemoveTreeClassChooserPanel(table, InspectionGadgetsLocalize.chooseLoggerClass().get()); - } - - @Override - public void readSettings(@Nonnull Element element) throws InvalidDataException { - super.readSettings(element); - parseString(loggerClassName, loggerClassNames); - } - - @Override - public void writeSettings(@Nonnull Element element) throws WriteExternalException { - loggerClassName = formatString(loggerClassNames); - super.writeSettings(element); - } - - @Override - public BaseInspectionVisitor buildVisitor() { - return new PublicMethodWithoutLoggingVisitor(); - } - - private class PublicMethodWithoutLoggingVisitor extends BaseInspectionVisitor { + @SuppressWarnings("PublicField") + public String loggerClassName = "java.util.logging.Logger" + ',' + + "org.slf4j.Logger" + ',' + + "org.apache.commons.logging.Log" + ',' + + "org.apache.log4j.Logger"; + private final List loggerClassNames = new ArrayList(); + + @Nonnull @Override - public void visitMethod(@Nonnull PsiMethod method) { - //no drilldown - if (method.getNameIdentifier() == null) { - return; - } - if (!method.hasModifierProperty(PsiModifier.PUBLIC)) { - return; - } - final PsiCodeBlock body = method.getBody(); - if (body == null) { - return; - } - if (method.isConstructor()) { - return; - } - if (PropertyUtil.isSimpleGetter(method) || PropertyUtil.isSimpleSetter(method)) { - return; - } - if (containsLoggingCall(body)) { - return; - } - registerMethodError(method); + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.publicMethodWithoutLoggingDisplayName(); } - private boolean containsLoggingCall(PsiCodeBlock block) { - final ContainsLoggingCallVisitor visitor = new ContainsLoggingCallVisitor(); - block.accept(visitor); - return visitor.containsLoggingCall(); + @Override + @Nonnull + public String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.publicMethodWithoutLoggingProblemDescriptor().get(); } - } - private class ContainsLoggingCallVisitor extends JavaRecursiveElementVisitor { + @Override + public JComponent createOptionsPanel() { + final ListTable table = new ListTable( + new ListWrappingTableModel(loggerClassNames, InspectionGadgetsLocalize.loggerClassName().get())); + return UiUtils.createAddRemoveTreeClassChooserPanel(table, InspectionGadgetsLocalize.chooseLoggerClass().get()); + } - private boolean containsLoggingCall = false; + @Override + public void readSettings(@Nonnull Element element) throws InvalidDataException { + super.readSettings(element); + parseString(loggerClassName, loggerClassNames); + } @Override - public void visitElement(@Nonnull PsiElement element) { - if (containsLoggingCall) { - return; - } - super.visitElement(element); + public void writeSettings(@Nonnull Element element) throws WriteExternalException { + loggerClassName = formatString(loggerClassNames); + super.writeSettings(element); } @Override - public void visitMethodCallExpression(@Nonnull PsiMethodCallExpression expression) { - if (containsLoggingCall) { - return; - } - super.visitMethodCallExpression(expression); - final PsiMethod method = expression.resolveMethod(); - if (method == null) { - return; - } - final PsiClass containingClass = method.getContainingClass(); - if (containingClass == null) { - return; - } - final String containingClassName = containingClass.getQualifiedName(); - if (containingClassName == null) { - return; - } - if (loggerClassNames.contains(containingClassName)) { - containsLoggingCall = true; - } + public BaseInspectionVisitor buildVisitor() { + return new PublicMethodWithoutLoggingVisitor(); + } + + private class PublicMethodWithoutLoggingVisitor extends BaseInspectionVisitor { + + @Override + public void visitMethod(@Nonnull PsiMethod method) { + //no drilldown + if (method.getNameIdentifier() == null) { + return; + } + if (!method.hasModifierProperty(PsiModifier.PUBLIC)) { + return; + } + final PsiCodeBlock body = method.getBody(); + if (body == null) { + return; + } + if (method.isConstructor()) { + return; + } + if (PropertyUtil.isSimpleGetter(method) || PropertyUtil.isSimpleSetter(method)) { + return; + } + if (containsLoggingCall(body)) { + return; + } + registerMethodError(method); + } + + private boolean containsLoggingCall(PsiCodeBlock block) { + final ContainsLoggingCallVisitor visitor = new ContainsLoggingCallVisitor(); + block.accept(visitor); + return visitor.containsLoggingCall(); + } } - public boolean containsLoggingCall() { - return containsLoggingCall; + private class ContainsLoggingCallVisitor extends JavaRecursiveElementVisitor { + + private boolean containsLoggingCall = false; + + @Override + public void visitElement(@Nonnull PsiElement element) { + if (containsLoggingCall) { + return; + } + super.visitElement(element); + } + + @Override + public void visitMethodCallExpression(@Nonnull PsiMethodCallExpression expression) { + if (containsLoggingCall) { + return; + } + super.visitMethodCallExpression(expression); + final PsiMethod method = expression.resolveMethod(); + if (method == null) { + return; + } + final PsiClass containingClass = method.getContainingClass(); + if (containingClass == null) { + return; + } + final String containingClassName = containingClass.getQualifiedName(); + if (containingClassName == null) { + return; + } + if (loggerClassNames.contains(containingClassName)) { + containsLoggingCall = true; + } + } + + public boolean containsLoggingCall() { + return containsLoggingCall; + } } - } } diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/logging/StringConcatenationArgumentToLogCallInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/logging/StringConcatenationArgumentToLogCallInspection.java index 811873291a..c49864f4da 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/logging/StringConcatenationArgumentToLogCallInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/logging/StringConcatenationArgumentToLogCallInspection.java @@ -27,11 +27,11 @@ import consulo.language.editor.inspection.ProblemDescriptor; import consulo.language.psi.PsiElement; import consulo.language.util.IncorrectOperationException; +import consulo.localize.LocalizeValue; import consulo.project.Project; import consulo.util.lang.StringUtil; import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; -import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NonNls; import java.util.ArrayList; @@ -45,258 +45,259 @@ @ExtensionImpl public class StringConcatenationArgumentToLogCallInspection extends BaseInspection { - @NonNls - private static final Set logNames = new HashSet(); - static { - logNames.add("trace"); - logNames.add("debug"); - logNames.add("info"); - logNames.add("warn"); - logNames.add("error"); - } + @NonNls + private static final Set logNames = new HashSet(); - @Nls - @Nonnull - @Override - public String getDisplayName() { - return InspectionGadgetsLocalize.stringConcatenationArgumentToLogCallDisplayName().get(); - } - - @Nonnull - @Override - protected String buildErrorString(Object... infos) { - return InspectionGadgetsLocalize.stringConcatenationArgumentToLogCallProblemDescriptor().get(); - } - - @Nullable - @Override - protected InspectionGadgetsFix buildFix(Object... infos) { - if (!StringConcatenationArgumentToLogCallFix.isAvailable((PsiExpression)infos[0])) { - return null; + static { + logNames.add("trace"); + logNames.add("debug"); + logNames.add("info"); + logNames.add("warn"); + logNames.add("error"); } - return new StringConcatenationArgumentToLogCallFix(); - } - - private static class StringConcatenationArgumentToLogCallFix extends InspectionGadgetsFix { - - public StringConcatenationArgumentToLogCallFix() {} + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.stringConcatenationArgumentToLogCallDisplayName(); + } @Nonnull @Override - public String getName() { - return InspectionGadgetsLocalize.stringConcatenationInFormatCallQuickfix().get(); + protected String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.stringConcatenationArgumentToLogCallProblemDescriptor().get(); } + @Nullable @Override - protected void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { - final PsiElement element = descriptor.getPsiElement(); - final PsiElement grandParent = element.getParent().getParent(); - if (!(grandParent instanceof PsiMethodCallExpression)) { - return; - } - final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression)grandParent; - final PsiExpressionList argumentList = methodCallExpression.getArgumentList(); - final PsiExpression[] arguments = argumentList.getExpressions(); - if (arguments.length == 0) { - return; - } - @NonNls final StringBuilder newMethodCall = new StringBuilder(methodCallExpression.getMethodExpression().getText()); - newMethodCall.append('('); - PsiExpression argument = arguments[0]; - int usedArguments; - if (!(argument instanceof PsiPolyadicExpression)) { - if (!TypeUtils.expressionHasTypeOrSubtype(argument, "org.slf4j.Marker") || arguments.length < 2) { - return; + protected InspectionGadgetsFix buildFix(Object... infos) { + if (!StringConcatenationArgumentToLogCallFix.isAvailable((PsiExpression) infos[0])) { + return null; } - newMethodCall.append(argument.getText()).append(','); - argument = arguments[1]; - usedArguments = 2; - if (!(argument instanceof PsiPolyadicExpression)) { - return; + return new StringConcatenationArgumentToLogCallFix(); + } + + private static class StringConcatenationArgumentToLogCallFix extends InspectionGadgetsFix { + + + public StringConcatenationArgumentToLogCallFix() { } - } - else { - usedArguments = 1; - } - final PsiPolyadicExpression polyadicExpression = (PsiPolyadicExpression)argument; - final PsiMethod method = methodCallExpression.resolveMethod(); - if (method == null) { - return; - } - final String methodName = method.getName(); - final PsiClass containingClass = method.getContainingClass(); - if (containingClass == null) { - return; - } - final PsiMethod[] methods = containingClass.findMethodsByName(methodName, false); - boolean varArgs = false; - for (PsiMethod otherMethod : methods) { - if (otherMethod.isVarArgs()) { - varArgs = true; - break; + + @Nonnull + @Override + public LocalizeValue getName() { + return InspectionGadgetsLocalize.stringConcatenationInFormatCallQuickfix(); } - } - final List newArguments = new ArrayList(); - final PsiExpression[] operands = polyadicExpression.getOperands(); - boolean addPlus = false; - boolean inStringLiteral = false; - for (PsiExpression operand : operands) { - if (ExpressionUtils.isEvaluatedAtCompileTime(operand)) { - if (ExpressionUtils.hasStringType(operand) && operand instanceof PsiLiteralExpression) { - final String text = operand.getText(); - final int count = StringUtil.getOccurrenceCount(text, "{}"); - for (int i = 0; i < count && usedArguments + i < arguments.length; i++) { - newArguments.add(ParenthesesUtils.stripParentheses((PsiExpression)arguments[i + usedArguments].copy())); + + @Override + protected void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { + final PsiElement element = descriptor.getPsiElement(); + final PsiElement grandParent = element.getParent().getParent(); + if (!(grandParent instanceof PsiMethodCallExpression)) { + return; + } + final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression) grandParent; + final PsiExpressionList argumentList = methodCallExpression.getArgumentList(); + final PsiExpression[] arguments = argumentList.getExpressions(); + if (arguments.length == 0) { + return; + } + @NonNls final StringBuilder newMethodCall = new StringBuilder(methodCallExpression.getMethodExpression().getText()); + newMethodCall.append('('); + PsiExpression argument = arguments[0]; + int usedArguments; + if (!(argument instanceof PsiPolyadicExpression)) { + if (!TypeUtils.expressionHasTypeOrSubtype(argument, "org.slf4j.Marker") || arguments.length < 2) { + return; + } + newMethodCall.append(argument.getText()).append(','); + argument = arguments[1]; + usedArguments = 2; + if (!(argument instanceof PsiPolyadicExpression)) { + return; + } + } + else { + usedArguments = 1; } - usedArguments += count; - if (!inStringLiteral) { - if (addPlus) { - newMethodCall.append('+'); - } - newMethodCall.append('"'); - inStringLiteral = true; + final PsiPolyadicExpression polyadicExpression = (PsiPolyadicExpression) argument; + final PsiMethod method = methodCallExpression.resolveMethod(); + if (method == null) { + return; + } + final String methodName = method.getName(); + final PsiClass containingClass = method.getContainingClass(); + if (containingClass == null) { + return; + } + final PsiMethod[] methods = containingClass.findMethodsByName(methodName, false); + boolean varArgs = false; + for (PsiMethod otherMethod : methods) { + if (otherMethod.isVarArgs()) { + varArgs = true; + break; + } + } + final List newArguments = new ArrayList(); + final PsiExpression[] operands = polyadicExpression.getOperands(); + boolean addPlus = false; + boolean inStringLiteral = false; + for (PsiExpression operand : operands) { + if (ExpressionUtils.isEvaluatedAtCompileTime(operand)) { + if (ExpressionUtils.hasStringType(operand) && operand instanceof PsiLiteralExpression) { + final String text = operand.getText(); + final int count = StringUtil.getOccurrenceCount(text, "{}"); + for (int i = 0; i < count && usedArguments + i < arguments.length; i++) { + newArguments.add(ParenthesesUtils.stripParentheses((PsiExpression) arguments[i + usedArguments].copy())); + } + usedArguments += count; + if (!inStringLiteral) { + if (addPlus) { + newMethodCall.append('+'); + } + newMethodCall.append('"'); + inStringLiteral = true; + } + newMethodCall.append(text.substring(1, text.length() - 1)); + } + else { + if (inStringLiteral) { + newMethodCall.append('"'); + inStringLiteral = false; + } + if (addPlus) { + newMethodCall.append('+'); + } + newMethodCall.append(operand.getText()); + } + } + else { + newArguments.add(ParenthesesUtils.stripParentheses((PsiExpression) operand.copy())); + if (!inStringLiteral) { + if (addPlus) { + newMethodCall.append('+'); + } + newMethodCall.append('"'); + inStringLiteral = true; + } + newMethodCall.append("{}"); + } + addPlus = true; + } + while (usedArguments < arguments.length) { + newArguments.add(arguments[usedArguments++]); } - newMethodCall.append(text.substring(1, text.length() - 1)); - } - else { if (inStringLiteral) { - newMethodCall.append('"'); - inStringLiteral = false; + newMethodCall.append('"'); } - if (addPlus) { - newMethodCall.append('+'); + if (!varArgs && newArguments.size() > 2) { + newMethodCall.append(", new Object[]{"); + boolean comma = false; + for (PsiExpression newArgument : newArguments) { + if (comma) { + newMethodCall.append(','); + } + else { + comma = true; + } + if (newArgument != null) { + newMethodCall.append(newArgument.getText()); + } + } + newMethodCall.append('}'); } - newMethodCall.append(operand.getText()); - } - } - else { - newArguments.add(ParenthesesUtils.stripParentheses((PsiExpression)operand.copy())); - if (!inStringLiteral) { - if (addPlus) { - newMethodCall.append('+'); + else { + for (PsiExpression newArgument : newArguments) { + newMethodCall.append(','); + if (newArgument != null) { + newMethodCall.append(newArgument.getText()); + } + } } - newMethodCall.append('"'); - inStringLiteral = true; - } - newMethodCall.append("{}"); + newMethodCall.append(')'); + replaceExpression(methodCallExpression, newMethodCall.toString()); } - addPlus = true; - } - while (usedArguments < arguments.length) { - newArguments.add(arguments[usedArguments++]); - } - if (inStringLiteral) { - newMethodCall.append('"'); - } - if (!varArgs && newArguments.size() > 2) { - newMethodCall.append(", new Object[]{"); - boolean comma = false; - for (PsiExpression newArgument : newArguments) { - if (comma) { - newMethodCall.append(','); - } - else { - comma =true; - } - if (newArgument != null) { - newMethodCall.append(newArgument.getText()); - } - } - newMethodCall.append('}'); - } - else { - for (PsiExpression newArgument : newArguments) { - newMethodCall.append(','); - if (newArgument != null) { - newMethodCall.append(newArgument.getText()); - } - } - } - newMethodCall.append(')'); - replaceExpression(methodCallExpression, newMethodCall.toString()); - } - public static boolean isAvailable(PsiExpression expression) { - if (!(expression instanceof PsiPolyadicExpression)) { - return false; - } - final PsiPolyadicExpression polyadicExpression = (PsiPolyadicExpression)expression; - final PsiExpression[] operands = polyadicExpression.getOperands(); - for (PsiExpression operand : operands) { - if (!ExpressionUtils.isEvaluatedAtCompileTime(operand)) { - return true; + public static boolean isAvailable(PsiExpression expression) { + if (!(expression instanceof PsiPolyadicExpression)) { + return false; + } + final PsiPolyadicExpression polyadicExpression = (PsiPolyadicExpression) expression; + final PsiExpression[] operands = polyadicExpression.getOperands(); + for (PsiExpression operand : operands) { + if (!ExpressionUtils.isEvaluatedAtCompileTime(operand)) { + return true; + } + } + return false; } - } - return false; } - } - - @Override - public BaseInspectionVisitor buildVisitor() { - return new StringConcatenationArgumentToLogCallVisitor(); - } - - private static class StringConcatenationArgumentToLogCallVisitor extends BaseInspectionVisitor { @Override - public void visitMethodCallExpression(PsiMethodCallExpression expression) { - super.visitMethodCallExpression(expression); - final PsiReferenceExpression methodExpression = expression.getMethodExpression(); - final String referenceName = methodExpression.getReferenceName(); - if (!logNames.contains(referenceName)) { - return; - } - final PsiMethod method = expression.resolveMethod(); - if (method == null) { - return; - } - final PsiClass containingClass = method.getContainingClass(); - if (containingClass == null || !"org.slf4j.Logger".equals(containingClass.getQualifiedName())) { - return; - } - final PsiExpressionList argumentList = expression.getArgumentList(); - final PsiExpression[] arguments = argumentList.getExpressions(); - if (arguments.length == 0) { - return; - } - PsiExpression argument = arguments[0]; - if (!ExpressionUtils.hasStringType(argument)) { - if (arguments.length < 2) { - return; - } - argument = arguments[1]; - if (!ExpressionUtils.hasStringType(argument)) { - return; - } - } - if (!containsNonConstantConcatenation(argument)) { - return; - } - registerMethodCallError(expression, argument); + public BaseInspectionVisitor buildVisitor() { + return new StringConcatenationArgumentToLogCallVisitor(); } - private static boolean containsNonConstantConcatenation(@Nullable PsiExpression expression) { - if (expression instanceof PsiParenthesizedExpression) { - final PsiParenthesizedExpression parenthesizedExpression = (PsiParenthesizedExpression)expression; - return containsNonConstantConcatenation(parenthesizedExpression.getExpression()); - } - else if (expression instanceof PsiPolyadicExpression) { - final PsiPolyadicExpression polyadicExpression = (PsiPolyadicExpression)expression; - if (!ExpressionUtils.hasStringType(polyadicExpression)) { - return false; - } - if (!JavaTokenType.PLUS.equals(polyadicExpression.getOperationTokenType())) { - return false; + private static class StringConcatenationArgumentToLogCallVisitor extends BaseInspectionVisitor { + + @Override + public void visitMethodCallExpression(PsiMethodCallExpression expression) { + super.visitMethodCallExpression(expression); + final PsiReferenceExpression methodExpression = expression.getMethodExpression(); + final String referenceName = methodExpression.getReferenceName(); + if (!logNames.contains(referenceName)) { + return; + } + final PsiMethod method = expression.resolveMethod(); + if (method == null) { + return; + } + final PsiClass containingClass = method.getContainingClass(); + if (containingClass == null || !"org.slf4j.Logger".equals(containingClass.getQualifiedName())) { + return; + } + final PsiExpressionList argumentList = expression.getArgumentList(); + final PsiExpression[] arguments = argumentList.getExpressions(); + if (arguments.length == 0) { + return; + } + PsiExpression argument = arguments[0]; + if (!ExpressionUtils.hasStringType(argument)) { + if (arguments.length < 2) { + return; + } + argument = arguments[1]; + if (!ExpressionUtils.hasStringType(argument)) { + return; + } + } + if (!containsNonConstantConcatenation(argument)) { + return; + } + registerMethodCallError(expression, argument); } - final PsiExpression[] operands = polyadicExpression.getOperands(); - for (PsiExpression operand : operands) { - if (!ExpressionUtils.isEvaluatedAtCompileTime(operand)) { - return true; - } + + private static boolean containsNonConstantConcatenation(@Nullable PsiExpression expression) { + if (expression instanceof PsiParenthesizedExpression) { + final PsiParenthesizedExpression parenthesizedExpression = (PsiParenthesizedExpression) expression; + return containsNonConstantConcatenation(parenthesizedExpression.getExpression()); + } + else if (expression instanceof PsiPolyadicExpression) { + final PsiPolyadicExpression polyadicExpression = (PsiPolyadicExpression) expression; + if (!ExpressionUtils.hasStringType(polyadicExpression)) { + return false; + } + if (!JavaTokenType.PLUS.equals(polyadicExpression.getOperationTokenType())) { + return false; + } + final PsiExpression[] operands = polyadicExpression.getOperands(); + for (PsiExpression operand : operands) { + if (!ExpressionUtils.isEvaluatedAtCompileTime(operand)) { + return true; + } + } + } + return false; } - } - return false; } - } } diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/maturity/ObsoleteCollectionInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/maturity/ObsoleteCollectionInspection.java index 261d9740df..76d99b69cd 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/maturity/ObsoleteCollectionInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/maturity/ObsoleteCollectionInspection.java @@ -40,214 +40,224 @@ @ExtensionImpl public class ObsoleteCollectionInspection extends BaseInspection { - @SuppressWarnings({"PublicField"}) - public boolean ignoreRequiredObsoleteCollectionTypes = false; - - @Override - @Nonnull - public String getID() { - return "UseOfObsoleteCollectionType"; - } - - @Override - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.useObsoleteCollectionTypeDisplayName().get(); - } - - @Override - @Nonnull - public String buildErrorString(Object... infos) { - return InspectionGadgetsLocalize.useObsoleteCollectionTypeProblemDescriptor().get(); - } - - @Override - @Nullable - public JComponent createOptionsPanel() { - LocalizeValue message = InspectionGadgetsLocalize.useObsoleteCollectionTypeIgnoreLibraryArgumentsOption(); - return new SingleCheckboxOptionsPanel(message.get(), this, "ignoreRequiredObsoleteCollectionTypes"); - } - - @Override - public BaseInspectionVisitor buildVisitor() { - return new ObsoleteCollectionVisitor(); - } - - private class ObsoleteCollectionVisitor - extends BaseInspectionVisitor { + @SuppressWarnings({"PublicField"}) + public boolean ignoreRequiredObsoleteCollectionTypes = false; @Override - public void visitVariable(@Nonnull PsiVariable variable) { - super.visitVariable(variable); - final PsiType type = variable.getType(); - if (!isObsoleteCollectionType(type)) { - return; - } - if (LibraryUtil.isOverrideOfLibraryMethodParameter(variable)) { - return; - } - final PsiTypeElement typeElement = variable.getTypeElement(); - if (typeElement == null) { - return; - } - if (ignoreRequiredObsoleteCollectionTypes && - isUsedAsParameterForLibraryMethod(variable)) { - return; - } - registerError(typeElement); + @Nonnull + public String getID() { + return "UseOfObsoleteCollectionType"; } + @Nonnull @Override - public void visitMethod(PsiMethod method) { - super.visitMethod(method); - final PsiType returnType = method.getReturnType(); - if (!isObsoleteCollectionType(returnType)) { - return; - } - if (LibraryUtil.isOverrideOfLibraryMethod(method)) { - return; - } - final PsiTypeElement typeElement = method.getReturnTypeElement(); - if (typeElement == null) { - return; - } - if (ignoreRequiredObsoleteCollectionTypes && - isUsedAsParameterForLibraryMethod(method)) { - return; - } - registerError(typeElement); + @Deprecated(forRemoval = true) + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.useObsoleteCollectionTypeDisplayName(); } @Override - public void visitNewExpression( - @Nonnull PsiNewExpression newExpression) { - super.visitNewExpression(newExpression); - final PsiType type = newExpression.getType(); - if (!isObsoleteCollectionType(type)) { - return; - } - if (ignoreRequiredObsoleteCollectionTypes && - isRequiredObsoleteCollectionElement(newExpression)) { - return; - } - registerNewExpressionError(newExpression); + @Nonnull + public String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.useObsoleteCollectionTypeProblemDescriptor().get(); } - private boolean isObsoleteCollectionType(PsiType type) { - if (type == null) { - return false; - } - final PsiType deepComponentType = type.getDeepComponentType(); - if (!(deepComponentType instanceof PsiClassType)) { - return false; - } - final PsiClassType classType = (PsiClassType)deepComponentType; - @NonNls final String className = classType.getClassName(); - if (!"Vector".equals(className) && !"Hashtable".equals(className)) { - return false; - } - final PsiClass aClass = classType.resolve(); - if (aClass == null) { - return false; - } - final String name = aClass.getQualifiedName(); - return "java.util.Vector".equals(name) || - "java.util.Hashtable".equals(name); + @Override + @Nullable + public JComponent createOptionsPanel() { + LocalizeValue message = InspectionGadgetsLocalize.useObsoleteCollectionTypeIgnoreLibraryArgumentsOption(); + return new SingleCheckboxOptionsPanel(message.get(), this, "ignoreRequiredObsoleteCollectionTypes"); } - private boolean isUsedAsParameterForLibraryMethod( - PsiNamedElement namedElement) { - final PsiFile containingFile = namedElement.getContainingFile(); - final Query query = - ReferencesSearch.search(namedElement, - GlobalSearchScope.fileScope(containingFile)); - for (PsiReference reference : query) { - final PsiElement element = reference.getElement(); - if (isRequiredObsoleteCollectionElement(element)) { - return true; - } - } - return false; + @Override + public BaseInspectionVisitor buildVisitor() { + return new ObsoleteCollectionVisitor(); } - private boolean isRequiredObsoleteCollectionElement( - PsiElement element) { - final PsiElement parent = element.getParent(); - if (parent instanceof PsiVariable) { - final PsiVariable variable = (PsiVariable)parent; - final PsiType variableType = variable.getType(); - if (isObsoleteCollectionType(variableType)) { - return true; + private class ObsoleteCollectionVisitor + extends BaseInspectionVisitor { + + @Override + public void visitVariable(@Nonnull PsiVariable variable) { + super.visitVariable(variable); + final PsiType type = variable.getType(); + if (!isObsoleteCollectionType(type)) { + return; + } + if (LibraryUtil.isOverrideOfLibraryMethodParameter(variable)) { + return; + } + final PsiTypeElement typeElement = variable.getTypeElement(); + if (typeElement == null) { + return; + } + if (ignoreRequiredObsoleteCollectionTypes && + isUsedAsParameterForLibraryMethod(variable)) { + return; + } + registerError(typeElement); } - } - else if (parent instanceof PsiReturnStatement) { - final PsiMethod method = PsiTreeUtil.getParentOfType(parent, - PsiMethod.class); - if (method != null) { - final PsiType returnType = method.getReturnType(); - if (isObsoleteCollectionType(returnType)) { - return true; - } + + @Override + public void visitMethod(PsiMethod method) { + super.visitMethod(method); + final PsiType returnType = method.getReturnType(); + if (!isObsoleteCollectionType(returnType)) { + return; + } + if (LibraryUtil.isOverrideOfLibraryMethod(method)) { + return; + } + final PsiTypeElement typeElement = method.getReturnTypeElement(); + if (typeElement == null) { + return; + } + if (ignoreRequiredObsoleteCollectionTypes && + isUsedAsParameterForLibraryMethod(method)) { + return; + } + registerError(typeElement); } - } - else if (parent instanceof PsiAssignmentExpression) { - final PsiAssignmentExpression assignmentExpression = - (PsiAssignmentExpression)parent; - final PsiExpression lhs = assignmentExpression.getLExpression(); - final PsiType lhsType = lhs.getType(); - if (isObsoleteCollectionType(lhsType)) { - return true; + + @Override + public void visitNewExpression( + @Nonnull PsiNewExpression newExpression + ) { + super.visitNewExpression(newExpression); + final PsiType type = newExpression.getType(); + if (!isObsoleteCollectionType(type)) { + return; + } + if (ignoreRequiredObsoleteCollectionTypes && + isRequiredObsoleteCollectionElement(newExpression)) { + return; + } + registerNewExpressionError(newExpression); } - } - if (!(parent instanceof PsiExpressionList)) { - return false; - } - final PsiExpressionList argumentList = (PsiExpressionList)parent; - final PsiElement grandParent = parent.getParent(); - if (!(grandParent instanceof PsiCallExpression)) { - return false; - } - final PsiCallExpression callExpression = - (PsiCallExpression)grandParent; - final int index = getIndexOfArgument(argumentList, element); - final PsiMethod method = callExpression.resolveMethod(); - if (method == null) { - return false; - } - final PsiParameterList parameterList = - method.getParameterList(); - final PsiParameter[] parameters = parameterList.getParameters(); - if (index >= parameters.length) { - final PsiParameter lastParameter = - parameters[parameters.length - 1]; - if (!lastParameter.isVarArgs()) { - return false; + + private boolean isObsoleteCollectionType(PsiType type) { + if (type == null) { + return false; + } + final PsiType deepComponentType = type.getDeepComponentType(); + if (!(deepComponentType instanceof PsiClassType)) { + return false; + } + final PsiClassType classType = (PsiClassType) deepComponentType; + @NonNls final String className = classType.getClassName(); + if (!"Vector".equals(className) && !"Hashtable".equals(className)) { + return false; + } + final PsiClass aClass = classType.resolve(); + if (aClass == null) { + return false; + } + final String name = aClass.getQualifiedName(); + return "java.util.Vector".equals(name) || + "java.util.Hashtable".equals(name); } - final PsiType type = lastParameter.getType(); - if (!(type instanceof PsiEllipsisType)) { - return false; + + private boolean isUsedAsParameterForLibraryMethod( + PsiNamedElement namedElement + ) { + final PsiFile containingFile = namedElement.getContainingFile(); + final Query query = + ReferencesSearch.search( + namedElement, + GlobalSearchScope.fileScope(containingFile) + ); + for (PsiReference reference : query) { + final PsiElement element = reference.getElement(); + if (isRequiredObsoleteCollectionElement(element)) { + return true; + } + } + return false; + } + + private boolean isRequiredObsoleteCollectionElement( + PsiElement element + ) { + final PsiElement parent = element.getParent(); + if (parent instanceof PsiVariable) { + final PsiVariable variable = (PsiVariable) parent; + final PsiType variableType = variable.getType(); + if (isObsoleteCollectionType(variableType)) { + return true; + } + } + else if (parent instanceof PsiReturnStatement) { + final PsiMethod method = PsiTreeUtil.getParentOfType( + parent, + PsiMethod.class + ); + if (method != null) { + final PsiType returnType = method.getReturnType(); + if (isObsoleteCollectionType(returnType)) { + return true; + } + } + } + else if (parent instanceof PsiAssignmentExpression) { + final PsiAssignmentExpression assignmentExpression = + (PsiAssignmentExpression) parent; + final PsiExpression lhs = assignmentExpression.getLExpression(); + final PsiType lhsType = lhs.getType(); + if (isObsoleteCollectionType(lhsType)) { + return true; + } + } + if (!(parent instanceof PsiExpressionList)) { + return false; + } + final PsiExpressionList argumentList = (PsiExpressionList) parent; + final PsiElement grandParent = parent.getParent(); + if (!(grandParent instanceof PsiCallExpression)) { + return false; + } + final PsiCallExpression callExpression = + (PsiCallExpression) grandParent; + final int index = getIndexOfArgument(argumentList, element); + final PsiMethod method = callExpression.resolveMethod(); + if (method == null) { + return false; + } + final PsiParameterList parameterList = + method.getParameterList(); + final PsiParameter[] parameters = parameterList.getParameters(); + if (index >= parameters.length) { + final PsiParameter lastParameter = + parameters[parameters.length - 1]; + if (!lastParameter.isVarArgs()) { + return false; + } + final PsiType type = lastParameter.getType(); + if (!(type instanceof PsiEllipsisType)) { + return false; + } + final PsiEllipsisType ellipsisType = (PsiEllipsisType) type; + final PsiType componentType = ellipsisType.getComponentType(); + return isObsoleteCollectionType(componentType); + } + final PsiParameter parameter = parameters[index]; + final PsiType type = parameter.getType(); + return isObsoleteCollectionType(type); } - final PsiEllipsisType ellipsisType = (PsiEllipsisType)type; - final PsiType componentType = ellipsisType.getComponentType(); - return isObsoleteCollectionType(componentType); - } - final PsiParameter parameter = parameters[index]; - final PsiType type = parameter.getType(); - return isObsoleteCollectionType(type); - } - private int getIndexOfArgument(PsiExpressionList argumentList, - PsiElement argument) { - final PsiExpression[] expressions = - argumentList.getExpressions(); - int index = -1; - for (PsiExpression expression : expressions) { - index++; - if (expression.equals(argument)) { - break; + private int getIndexOfArgument( + PsiExpressionList argumentList, + PsiElement argument + ) { + final PsiExpression[] expressions = + argumentList.getExpressions(); + int index = -1; + for (PsiExpression expression : expressions) { + index++; + if (expression.equals(argument)) { + break; + } + } + return index; } - } - return index; } - } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/maturity/SuppressionAnnotationInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/maturity/SuppressionAnnotationInspection.java index af3e00368f..e255089019 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/maturity/SuppressionAnnotationInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/maturity/SuppressionAnnotationInspection.java @@ -26,56 +26,58 @@ import consulo.language.ast.IElementType; import consulo.language.editor.inspection.SuppressionUtil; import consulo.language.psi.PsiComment; +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; import org.jetbrains.annotations.NonNls; @ExtensionImpl public class SuppressionAnnotationInspection extends BaseInspection { - - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.inspectionSuppressionAnnotationDisplayName().get(); - } - - @Nonnull - public String buildErrorString(Object... infos) { - return InspectionGadgetsLocalize.inspectionSuppressionAnnotationProblemDescriptor().get(); - } - - public BaseInspectionVisitor buildVisitor() { - return new SuppressionAnnotationVisitor(); - } - - private static class SuppressionAnnotationVisitor - extends BaseInspectionVisitor { + @Nonnull @Override - public void visitComment(PsiComment comment) { - super.visitComment(comment); - final String commentText = comment.getText(); - final IElementType tokenType = comment.getTokenType(); - if (!tokenType.equals(JavaTokenType.END_OF_LINE_COMMENT) - && !tokenType.equals(JavaTokenType.C_STYLE_COMMENT)) { - return; - } - @NonNls final String strippedComment = commentText.substring(2).trim(); - if (strippedComment.startsWith(SuppressionUtil.SUPPRESS_INSPECTIONS_TAG_NAME)) { - registerError(comment); - } + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.inspectionSuppressionAnnotationDisplayName(); } + @Nonnull @Override - public void visitAnnotation(PsiAnnotation annotation) { - super.visitAnnotation(annotation); - final PsiJavaCodeReferenceElement reference = - annotation.getNameReferenceElement(); - if (reference == null) { - return; - } - @NonNls final String text = reference.getText(); - if ("SuppressWarnings".equals(text) || - BatchSuppressManager.SUPPRESS_INSPECTIONS_ANNOTATION_NAME.equals(text)) { - registerError(annotation); - } + public String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.inspectionSuppressionAnnotationProblemDescriptor().get(); + } + + public BaseInspectionVisitor buildVisitor() { + return new SuppressionAnnotationVisitor(); + } + + private static class SuppressionAnnotationVisitor + extends BaseInspectionVisitor { + @Override + public void visitComment(PsiComment comment) { + super.visitComment(comment); + final String commentText = comment.getText(); + final IElementType tokenType = comment.getTokenType(); + if (!tokenType.equals(JavaTokenType.END_OF_LINE_COMMENT) + && !tokenType.equals(JavaTokenType.C_STYLE_COMMENT)) { + return; + } + @NonNls final String strippedComment = commentText.substring(2).trim(); + if (strippedComment.startsWith(SuppressionUtil.SUPPRESS_INSPECTIONS_TAG_NAME)) { + registerError(comment); + } + } + + @Override + public void visitAnnotation(PsiAnnotation annotation) { + super.visitAnnotation(annotation); + final PsiJavaCodeReferenceElement reference = + annotation.getNameReferenceElement(); + if (reference == null) { + return; + } + @NonNls final String text = reference.getText(); + if ("SuppressWarnings".equals(text) || + BatchSuppressManager.SUPPRESS_INSPECTIONS_ANNOTATION_NAME.equals(text)) { + registerError(annotation); + } + } } - } } diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/maturity/SystemOutErrInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/maturity/SystemOutErrInspection.java index 4a643efe43..dea6eeccfc 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/maturity/SystemOutErrInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/maturity/SystemOutErrInspection.java @@ -24,55 +24,58 @@ import com.siyeh.localize.InspectionGadgetsLocalize; import consulo.annotation.component.ExtensionImpl; import consulo.language.psi.PsiElement; +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; @ExtensionImpl public class SystemOutErrInspection extends BaseInspection { - @Nonnull - public String getID() { - return "UseOfSystemOutOrSystemErr"; - } + @Nonnull + public String getID() { + return "UseOfSystemOutOrSystemErr"; + } - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.useSystemOutErrDisplayName().get(); - } + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.useSystemOutErrDisplayName(); + } - @Nonnull - public String buildErrorString(Object... infos) { - return InspectionGadgetsLocalize.useSystemOutErrProblemDescriptor().get(); - } + @Nonnull + public String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.useSystemOutErrProblemDescriptor().get(); + } - public BaseInspectionVisitor buildVisitor() { - return new SystemOutErrVisitor(); - } + public BaseInspectionVisitor buildVisitor() { + return new SystemOutErrVisitor(); + } - private static class SystemOutErrVisitor extends BaseInspectionVisitor { + private static class SystemOutErrVisitor extends BaseInspectionVisitor { - @Override - public void visitReferenceExpression( - @Nonnull PsiReferenceExpression expression) { - super.visitReferenceExpression(expression); - final String name = expression.getReferenceName(); - if (!HardcodedMethodConstants.OUT.equals(name) && - !HardcodedMethodConstants.ERR.equals(name)) { - return; - } - final PsiElement referent = expression.resolve(); - if (!(referent instanceof PsiField)) { - return; - } - final PsiField field = (PsiField)referent; - final PsiClass containingClass = field.getContainingClass(); - if (containingClass == null) { - return; - } - final String className = containingClass.getQualifiedName(); - if (!"java.lang.System".equals(className)) { - return; - } - registerError(expression); + @Override + public void visitReferenceExpression( + @Nonnull PsiReferenceExpression expression + ) { + super.visitReferenceExpression(expression); + final String name = expression.getReferenceName(); + if (!HardcodedMethodConstants.OUT.equals(name) && + !HardcodedMethodConstants.ERR.equals(name)) { + return; + } + final PsiElement referent = expression.resolve(); + if (!(referent instanceof PsiField)) { + return; + } + final PsiField field = (PsiField) referent; + final PsiClass containingClass = field.getContainingClass(); + if (containingClass == null) { + return; + } + final String className = containingClass.getQualifiedName(); + if (!"java.lang.System".equals(className)) { + return; + } + registerError(expression); + } } - } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/maturity/ThreadDumpStackInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/maturity/ThreadDumpStackInspection.java index a2b4b97b57..96fbdc64d5 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/maturity/ThreadDumpStackInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/maturity/ThreadDumpStackInspection.java @@ -23,60 +23,58 @@ import com.siyeh.localize.InspectionGadgetsLocalize; import consulo.annotation.component.ExtensionImpl; import consulo.language.psi.PsiElement; +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; @ExtensionImpl public class ThreadDumpStackInspection extends BaseInspection { + @Nonnull + public String getID() { + return "CallToThreadDumpStack"; + } - @Nonnull - public String getID() { - return "CallToThreadDumpStack"; - } - - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.dumpstackCallDisplayName().get(); - } - - @Nonnull - public String buildErrorString(Object... infos) { - return InspectionGadgetsLocalize.dumpstackCallProblemDescriptor().get(); - } + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.dumpstackCallDisplayName(); + } - public BaseInspectionVisitor buildVisitor() { - return new ThreadDumpStackVisitor(); - } + @Nonnull + public String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.dumpstackCallProblemDescriptor().get(); + } - private static class ThreadDumpStackVisitor extends BaseInspectionVisitor { + public BaseInspectionVisitor buildVisitor() { + return new ThreadDumpStackVisitor(); + } - @Override - public void visitMethodCallExpression( - @Nonnull PsiMethodCallExpression expression) { - super.visitMethodCallExpression(expression); - final String methodName = MethodCallUtils.getMethodName(expression); - if (!HardcodedMethodConstants.DUMP_STACKTRACE.equals(methodName)) { - return; - } - final PsiExpressionList argumentList = expression.getArgumentList(); - if (argumentList.getExpressions().length != 0) { - return; - } - final PsiReferenceExpression methodExpression = - expression.getMethodExpression(); - final PsiElement element = methodExpression.resolve(); - if (!(element instanceof PsiMethod)) { - return; - } - final PsiMethod method = (PsiMethod)element; - final PsiClass aClass = method.getContainingClass(); - if (aClass == null) { - return; - } - final String qualifiedName = aClass.getQualifiedName(); - if (!"java.lang.Thread".equals(qualifiedName)) { - return; - } - registerMethodCallError(expression); + private static class ThreadDumpStackVisitor extends BaseInspectionVisitor { + @Override + public void visitMethodCallExpression(@Nonnull PsiMethodCallExpression expression) { + super.visitMethodCallExpression(expression); + final String methodName = MethodCallUtils.getMethodName(expression); + if (!HardcodedMethodConstants.DUMP_STACKTRACE.equals(methodName)) { + return; + } + final PsiExpressionList argumentList = expression.getArgumentList(); + if (argumentList.getExpressions().length != 0) { + return; + } + final PsiReferenceExpression methodExpression = expression.getMethodExpression(); + final PsiElement element = methodExpression.resolve(); + if (!(element instanceof PsiMethod)) { + return; + } + final PsiMethod method = (PsiMethod) element; + final PsiClass aClass = method.getContainingClass(); + if (aClass == null) { + return; + } + final String qualifiedName = aClass.getQualifiedName(); + if (!"java.lang.Thread".equals(qualifiedName)) { + return; + } + registerMethodCallError(expression); + } } - } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/maturity/ThrowablePrintStackTraceInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/maturity/ThrowablePrintStackTraceInspection.java index 06066b8cca..91b13794e5 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/maturity/ThrowablePrintStackTraceInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/maturity/ThrowablePrintStackTraceInspection.java @@ -23,47 +23,44 @@ import com.siyeh.ig.psiutils.MethodCallUtils; import com.siyeh.localize.InspectionGadgetsLocalize; import consulo.annotation.component.ExtensionImpl; +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; @ExtensionImpl public class ThrowablePrintStackTraceInspection extends BaseInspection { + @Nonnull + public String getID() { + return "CallToPrintStackTrace"; + } - @Nonnull - public String getID() { - return "CallToPrintStackTrace"; - } - - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.printstacktraceCallDisplayName().get(); - } - - @Nonnull - public String buildErrorString(Object... infos) { - return InspectionGadgetsLocalize.printstacktraceCallProblemDescriptor().get(); - } + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.printstacktraceCallDisplayName(); + } - public BaseInspectionVisitor buildVisitor() { - return new ThrowablePrintStackTraceVisitor(); - } + @Nonnull + public String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.printstacktraceCallProblemDescriptor().get(); + } - private static class ThrowablePrintStackTraceVisitor - extends BaseInspectionVisitor { + public BaseInspectionVisitor buildVisitor() { + return new ThrowablePrintStackTraceVisitor(); + } - @Override - public void visitMethodCallExpression( - @Nonnull PsiMethodCallExpression expression) { - super.visitMethodCallExpression(expression); - final String methodName = MethodCallUtils.getMethodName(expression); - if (!HardcodedMethodConstants.PRINT_STACK_TRACE.equals( - methodName)) { - return; - } - final PsiExpressionList argumentList = expression.getArgumentList(); - if (argumentList.getExpressions().length != 0) { - return; - } - registerMethodCallError(expression); + private static class ThrowablePrintStackTraceVisitor extends BaseInspectionVisitor { + @Override + public void visitMethodCallExpression(@Nonnull PsiMethodCallExpression expression) { + super.visitMethodCallExpression(expression); + final String methodName = MethodCallUtils.getMethodName(expression); + if (!HardcodedMethodConstants.PRINT_STACK_TRACE.equals(methodName)) { + return; + } + final PsiExpressionList argumentList = expression.getArgumentList(); + if (argumentList.getExpressions().length != 0) { + return; + } + registerMethodCallError(expression); + } } - } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/memory/StaticCollectionInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/memory/StaticCollectionInspection.java index f8d36ab771..ab3526f818 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/memory/StaticCollectionInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/memory/StaticCollectionInspection.java @@ -31,47 +31,45 @@ @ExtensionImpl public class StaticCollectionInspection extends BaseInspection { + /** + * @noinspection PublicField + */ + public boolean m_ignoreWeakCollections = false; - /** - * @noinspection PublicField - */ - public boolean m_ignoreWeakCollections = false; - - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.staticCollectionDisplayName().get(); - } - - @Nonnull - public String buildErrorString(Object... infos) { - return InspectionGadgetsLocalize.staticCollectionProblemDescriptor().get(); - } + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.staticCollectionDisplayName(); + } - public JComponent createOptionsPanel() { - LocalizeValue message = InspectionGadgetsLocalize.staticCollectionIgnoreOption(); - return new SingleCheckboxOptionsPanel(message.get(), this, "m_ignoreWeakCollections"); - } + @Nonnull + public String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.staticCollectionProblemDescriptor().get(); + } - public BaseInspectionVisitor buildVisitor() { - return new StaticCollectionVisitor(); - } + public JComponent createOptionsPanel() { + LocalizeValue message = InspectionGadgetsLocalize.staticCollectionIgnoreOption(); + return new SingleCheckboxOptionsPanel(message.get(), this, "m_ignoreWeakCollections"); + } - private class StaticCollectionVisitor extends BaseInspectionVisitor { + public BaseInspectionVisitor buildVisitor() { + return new StaticCollectionVisitor(); + } - @Override - public void visitField(@Nonnull PsiField field) { - if (!field.hasModifierProperty(PsiModifier.STATIC)) { - return; - } - final PsiType type = field.getType(); - if (!CollectionUtils.isCollectionClassOrInterface(type)) { - return; - } - if (!m_ignoreWeakCollections || - CollectionUtils.isWeakCollectionClass(type)) { - return; - } - registerFieldError(field); + private class StaticCollectionVisitor extends BaseInspectionVisitor { + @Override + public void visitField(@Nonnull PsiField field) { + if (!field.hasModifierProperty(PsiModifier.STATIC)) { + return; + } + final PsiType type = field.getType(); + if (!CollectionUtils.isCollectionClassOrInterface(type)) { + return; + } + if (!m_ignoreWeakCollections || CollectionUtils.isWeakCollectionClass(type)) { + return; + } + registerFieldError(field); + } } - } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/memory/StringBufferFieldInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/memory/StringBufferFieldInspection.java index ea379c021b..ea08d4106c 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/memory/StringBufferFieldInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/memory/StringBufferFieldInspection.java @@ -22,42 +22,40 @@ import com.siyeh.ig.BaseInspectionVisitor; import com.siyeh.localize.InspectionGadgetsLocalize; import consulo.annotation.component.ExtensionImpl; +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; @ExtensionImpl public class StringBufferFieldInspection extends BaseInspection { + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.stringbufferFieldDisplayName(); + } - @Override - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.stringbufferFieldDisplayName().get(); - } - - @Override - @Nonnull - public String buildErrorString(Object... infos) { - final PsiType type = (PsiType)infos[0]; - final String typeName = type.getPresentableText(); - return InspectionGadgetsLocalize.stringbufferFieldProblemDescriptor(typeName).get(); - } - - @Override - public BaseInspectionVisitor buildVisitor() { - return new StringBufferFieldVisitor(); - } - - private static class StringBufferFieldVisitor - extends BaseInspectionVisitor { + @Override + @Nonnull + public String buildErrorString(Object... infos) { + final PsiType type = (PsiType) infos[0]; + final String typeName = type.getPresentableText(); + return InspectionGadgetsLocalize.stringbufferFieldProblemDescriptor(typeName).get(); + } @Override - public void visitField(@Nonnull PsiField field) { - super.visitField(field); - final PsiType type = field.getType(); - if (!type.equalsToText(CommonClassNames.JAVA_LANG_STRING_BUFFER) && - !type.equalsToText(CommonClassNames.JAVA_LANG_STRING_BUILDER)) { - return; - } - registerFieldError(field, type); + public BaseInspectionVisitor buildVisitor() { + return new StringBufferFieldVisitor(); + } + + private static class StringBufferFieldVisitor extends BaseInspectionVisitor { + @Override + public void visitField(@Nonnull PsiField field) { + super.visitField(field); + final PsiType type = field.getType(); + if (!type.equalsToText(CommonClassNames.JAVA_LANG_STRING_BUFFER) && + !type.equalsToText(CommonClassNames.JAVA_LANG_STRING_BUILDER)) { + return; + } + registerFieldError(field, type); + } } - } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/memory/SystemGCInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/memory/SystemGCInspection.java index edd5bf9702..6bd7d62e4e 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/memory/SystemGCInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/memory/SystemGCInspection.java @@ -21,60 +21,58 @@ import com.siyeh.ig.BaseInspectionVisitor; import com.siyeh.localize.InspectionGadgetsLocalize; import consulo.annotation.component.ExtensionImpl; +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; @ExtensionImpl public class SystemGCInspection extends BaseInspection { + @Nonnull + public String getID() { + return "CallToSystemGC"; + } - @Nonnull - public String getID() { - return "CallToSystemGC"; - } - - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.gcCallDisplayName().get(); - } - - @Nonnull - public String buildErrorString(Object... infos) { - return InspectionGadgetsLocalize.gcCallProblemDescriptor().get(); - } + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.gcCallDisplayName(); + } - public BaseInspectionVisitor buildVisitor() { - return new SystemGCVisitor(); - } + @Nonnull + public String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.gcCallProblemDescriptor().get(); + } - private static class SystemGCVisitor extends BaseInspectionVisitor { + public BaseInspectionVisitor buildVisitor() { + return new SystemGCVisitor(); + } - @Override - public void visitMethodCallExpression( - @Nonnull PsiMethodCallExpression expression) { - super.visitMethodCallExpression(expression); - final PsiReferenceExpression methodExpression = - expression.getMethodExpression(); - final String methodName = methodExpression.getReferenceName(); - if (!HardcodedMethodConstants.GC.equals(methodName)) { - return; - } - final PsiMethod method = expression.resolveMethod(); - if (method == null) { - return; - } - final PsiParameterList parameterList = method.getParameterList(); - if (parameterList.getParametersCount() != 0) { - return; - } - final PsiClass aClass = method.getContainingClass(); - if (aClass == null) { - return; - } - final String className = aClass.getQualifiedName(); - if (!"java.lang.System".equals(className) && - !"java.lang.Runtime".equals(className)) { - return; - } - registerError(expression); + private static class SystemGCVisitor extends BaseInspectionVisitor { + @Override + public void visitMethodCallExpression(@Nonnull PsiMethodCallExpression expression) { + super.visitMethodCallExpression(expression); + final PsiReferenceExpression methodExpression = expression.getMethodExpression(); + final String methodName = methodExpression.getReferenceName(); + if (!HardcodedMethodConstants.GC.equals(methodName)) { + return; + } + final PsiMethod method = expression.resolveMethod(); + if (method == null) { + return; + } + final PsiParameterList parameterList = method.getParameterList(); + if (parameterList.getParametersCount() != 0) { + return; + } + final PsiClass aClass = method.getContainingClass(); + if (aClass == null) { + return; + } + final String className = aClass.getQualifiedName(); + if (!"java.lang.System".equals(className) && + !"java.lang.Runtime".equals(className)) { + return; + } + registerError(expression); + } } - } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/methodmetrics/ParametersPerConstructorInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/methodmetrics/ParametersPerConstructorInspection.java index f6550ce96b..41e2a39cdf 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/methodmetrics/ParametersPerConstructorInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/methodmetrics/ParametersPerConstructorInspection.java @@ -21,6 +21,7 @@ import com.siyeh.ig.BaseInspectionVisitor; import com.siyeh.localize.InspectionGadgetsLocalize; import consulo.annotation.component.ExtensionImpl; +import consulo.localize.LocalizeValue; import consulo.ui.ex.awt.ListCellRendererWrapper; import jakarta.annotation.Nonnull; @@ -30,144 +31,155 @@ @ExtensionImpl public class ParametersPerConstructorInspection extends MethodMetricInspection { + private enum Scope { + NONE { + @Override + String getText() { + return InspectionGadgetsLocalize.none().get(); + } + }, + PRIVATE { + @Override + String getText() { + return InspectionGadgetsLocalize.privateModifier().get(); + } + }, + PACKAGE_LOCAL { + @Override + String getText() { + return InspectionGadgetsLocalize.packageLocalPrivate().get(); + } + }, + PROTECTED { + @Override + String getText() { + return InspectionGadgetsLocalize.protectedPackageLocalPrivate().get(); + } + }; + + abstract String getText(); + } + + @SuppressWarnings("PublicField") + public Scope ignoreScope = Scope.NONE; - private enum Scope { - NONE { - @Override - String getText() { - return InspectionGadgetsLocalize.none().get(); - } - }, - PRIVATE { - @Override - String getText() { - return InspectionGadgetsLocalize.privateModifier().get(); - } - }, - PACKAGE_LOCAL { - @Override - String getText() { - return InspectionGadgetsLocalize.packageLocalPrivate().get(); - } - }, - PROTECTED { - @Override - String getText() { - return InspectionGadgetsLocalize.protectedPackageLocalPrivate().get(); - } - }; - - abstract String getText(); - } - - @SuppressWarnings("PublicField") public Scope ignoreScope = Scope.NONE; - - @Override - @Nonnull - public String getID() { - return "ConstructorWithTooManyParameters"; - } - - @Override - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.parametersPerConstructorDisplayName().get(); - } - - @Override - @Nonnull - public String buildErrorString(Object... infos) { - final Integer parameterCount = (Integer)infos[0]; - return InspectionGadgetsLocalize.parametersPerConstructorProblemDescriptor(parameterCount).get(); - } - - @Override - protected int getDefaultLimit() { - return 5; - } - - @Override - protected String getConfigurationLabel() { - return InspectionGadgetsLocalize.parameterLimitOption().get(); - } - - @Override - public JComponent createOptionsPanel() { - final JPanel panel = new JPanel(); - final JLabel textFieldLabel = new JLabel(getConfigurationLabel()); - final JFormattedTextField valueField = prepareNumberEditor(() -> m_limit, i -> m_limit = i); - final JLabel comboBoxLabel = new JLabel(InspectionGadgetsLocalize.constructorVisibilityOption().get()); - final JComboBox comboBox = new JComboBox(); - comboBox.addItem(Scope.NONE); - comboBox.addItem(Scope.PRIVATE); - comboBox.addItem(Scope.PACKAGE_LOCAL); - comboBox.addItem(Scope.PROTECTED); - comboBox.setRenderer(new ListCellRendererWrapper() { - @Override - public void customize(JList list, Object value, int index, boolean selected, boolean hasFocus) { - if (value instanceof Scope) setText(((Scope)value).getText()); - } - }); - comboBox.setSelectedItem(ignoreScope); - comboBox.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - ignoreScope = (Scope)comboBox.getSelectedItem(); - } - }); - comboBox.setPrototypeDisplayValue(Scope.PROTECTED); - - final GroupLayout layout = new GroupLayout(panel); - layout.setAutoCreateGaps(true); - panel.setLayout(layout); - final GroupLayout.ParallelGroup horizontal = layout.createParallelGroup(); - horizontal.addGroup(layout.createSequentialGroup() - .addComponent(textFieldLabel) - .addComponent(valueField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)); - horizontal.addGroup(layout.createSequentialGroup() - .addComponent(comboBoxLabel).addComponent(comboBox, 100, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)); - layout.setHorizontalGroup(horizontal); - final GroupLayout.SequentialGroup vertical = layout.createSequentialGroup(); - vertical.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE) - .addComponent(textFieldLabel) - .addComponent(valueField)); - vertical.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE) - .addComponent(comboBoxLabel) - .addComponent(comboBox)); - layout.setVerticalGroup(vertical); - - return panel; - } - - @Override - public BaseInspectionVisitor buildVisitor() { - return new ParametersPerConstructorVisitor(); - } - - private class ParametersPerConstructorVisitor extends BaseInspectionVisitor { + @Override + @Nonnull + public String getID() { + return "ConstructorWithTooManyParameters"; + } + @Nonnull @Override - public void visitMethod(@Nonnull PsiMethod method) { - // note: no call to super - if (method.getNameIdentifier() == null) { - return; - } - if (!method.isConstructor()) { - return; - } - if (ignoreScope != Scope.NONE) { - switch (ignoreScope.ordinal()) { - case 3: if (method.hasModifierProperty(PsiModifier.PROTECTED)) return; - case 2: if (method.hasModifierProperty(PsiModifier.PACKAGE_LOCAL)) return; - case 1: if (method.hasModifierProperty(PsiModifier.PRIVATE)) return; + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.parametersPerConstructorDisplayName(); + } + + @Override + @Nonnull + public String buildErrorString(Object... infos) { + final Integer parameterCount = (Integer) infos[0]; + return InspectionGadgetsLocalize.parametersPerConstructorProblemDescriptor(parameterCount).get(); + } + + @Override + protected int getDefaultLimit() { + return 5; + } + + @Override + protected String getConfigurationLabel() { + return InspectionGadgetsLocalize.parameterLimitOption().get(); + } + + @Override + public JComponent createOptionsPanel() { + final JPanel panel = new JPanel(); + final JLabel textFieldLabel = new JLabel(getConfigurationLabel()); + final JFormattedTextField valueField = prepareNumberEditor(() -> m_limit, i -> m_limit = i); + final JLabel comboBoxLabel = new JLabel(InspectionGadgetsLocalize.constructorVisibilityOption().get()); + final JComboBox comboBox = new JComboBox(); + comboBox.addItem(Scope.NONE); + comboBox.addItem(Scope.PRIVATE); + comboBox.addItem(Scope.PACKAGE_LOCAL); + comboBox.addItem(Scope.PROTECTED); + comboBox.setRenderer(new ListCellRendererWrapper() { + @Override + public void customize(JList list, Object value, int index, boolean selected, boolean hasFocus) { + if (value instanceof Scope) { + setText(((Scope) value).getText()); + } + } + }); + comboBox.setSelectedItem(ignoreScope); + comboBox.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + ignoreScope = (Scope) comboBox.getSelectedItem(); + } + }); + comboBox.setPrototypeDisplayValue(Scope.PROTECTED); + + final GroupLayout layout = new GroupLayout(panel); + layout.setAutoCreateGaps(true); + panel.setLayout(layout); + final GroupLayout.ParallelGroup horizontal = layout.createParallelGroup(); + horizontal.addGroup(layout.createSequentialGroup() + .addComponent(textFieldLabel) + .addComponent(valueField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)); + horizontal.addGroup(layout.createSequentialGroup() + .addComponent(comboBoxLabel).addComponent(comboBox, 100, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)); + layout.setHorizontalGroup(horizontal); + final GroupLayout.SequentialGroup vertical = layout.createSequentialGroup(); + vertical.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE) + .addComponent(textFieldLabel) + .addComponent(valueField)); + vertical.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE) + .addComponent(comboBoxLabel) + .addComponent(comboBox)); + layout.setVerticalGroup(vertical); + + return panel; + } + + @Override + public BaseInspectionVisitor buildVisitor() { + return new ParametersPerConstructorVisitor(); + } + + private class ParametersPerConstructorVisitor extends BaseInspectionVisitor { + + @Override + public void visitMethod(@Nonnull PsiMethod method) { + // note: no call to super + if (method.getNameIdentifier() == null) { + return; + } + if (!method.isConstructor()) { + return; + } + if (ignoreScope != Scope.NONE) { + switch (ignoreScope.ordinal()) { + case 3: + if (method.hasModifierProperty(PsiModifier.PROTECTED)) { + return; + } + case 2: + if (method.hasModifierProperty(PsiModifier.PACKAGE_LOCAL)) { + return; + } + case 1: + if (method.hasModifierProperty(PsiModifier.PRIVATE)) { + return; + } + } + } + final PsiParameterList parameterList = method.getParameterList(); + final int parametersCount = parameterList.getParametersCount(); + if (parametersCount <= getLimit()) { + return; + } + registerMethodError(method, Integer.valueOf(parametersCount)); } - } - final PsiParameterList parameterList = method.getParameterList(); - final int parametersCount = parameterList.getParametersCount(); - if (parametersCount <= getLimit()) { - return; - } - registerMethodError(method, Integer.valueOf(parametersCount)); } - } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/methodmetrics/ParametersPerMethodInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/methodmetrics/ParametersPerMethodInspection.java index f78623e05f..39dd6b11c7 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/methodmetrics/ParametersPerMethodInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/methodmetrics/ParametersPerMethodInspection.java @@ -21,59 +21,60 @@ import com.siyeh.ig.BaseInspectionVisitor; import com.siyeh.localize.InspectionGadgetsLocalize; import consulo.annotation.component.ExtensionImpl; +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; @ExtensionImpl public class ParametersPerMethodInspection extends MethodMetricInspection { + @Nonnull + public String getID() { + return "MethodWithTooManyParameters"; + } - @Nonnull - public String getID() { - return "MethodWithTooManyParameters"; - } - - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.parametersPerMethodDisplayName().get(); - } + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.parametersPerMethodDisplayName(); + } - @Nonnull - public String buildErrorString(Object... infos) { - final Integer parameterCount = (Integer)infos[0]; - return InspectionGadgetsLocalize.parametersPerMethodProblemDescriptor(parameterCount).get(); - } + @Nonnull + public String buildErrorString(Object... infos) { + final Integer parameterCount = (Integer) infos[0]; + return InspectionGadgetsLocalize.parametersPerMethodProblemDescriptor(parameterCount).get(); + } - protected int getDefaultLimit() { - return 5; - } + protected int getDefaultLimit() { + return 5; + } - protected String getConfigurationLabel() { - return InspectionGadgetsLocalize.parameterLimitOption().get(); - } + protected String getConfigurationLabel() { + return InspectionGadgetsLocalize.parameterLimitOption().get(); + } - public BaseInspectionVisitor buildVisitor() { - return new ParametersPerMethodVisitor(); - } + public BaseInspectionVisitor buildVisitor() { + return new ParametersPerMethodVisitor(); + } - private class ParametersPerMethodVisitor extends BaseInspectionVisitor { + private class ParametersPerMethodVisitor extends BaseInspectionVisitor { - @Override - public void visitMethod(@Nonnull PsiMethod method) { - // note: no call to super - if (method.getNameIdentifier() == null) { - return; - } - if (method.isConstructor()) { - return; - } - final PsiParameterList parameterList = method.getParameterList(); - final int parametersCount = parameterList.getParametersCount(); - if (parametersCount <= getLimit()) { - return; - } - if (LibraryUtil.isOverrideOfLibraryMethod(method)) { - return; - } - registerMethodError(method, Integer.valueOf(parametersCount)); + @Override + public void visitMethod(@Nonnull PsiMethod method) { + // note: no call to super + if (method.getNameIdentifier() == null) { + return; + } + if (method.isConstructor()) { + return; + } + final PsiParameterList parameterList = method.getParameterList(); + final int parametersCount = parameterList.getParametersCount(); + if (parametersCount <= getLimit()) { + return; + } + if (LibraryUtil.isOverrideOfLibraryMethod(method)) { + return; + } + registerMethodError(method, Integer.valueOf(parametersCount)); + } } - } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/methodmetrics/ThreeNegationsPerMethodInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/methodmetrics/ThreeNegationsPerMethodInspection.java index c67abfb298..1ef4a64a00 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/methodmetrics/ThreeNegationsPerMethodInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/methodmetrics/ThreeNegationsPerMethodInspection.java @@ -22,71 +22,71 @@ import com.siyeh.localize.InspectionGadgetsLocalize; import consulo.annotation.component.ExtensionImpl; import consulo.deadCodeNotWorking.impl.MultipleCheckboxOptionsPanel; +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; import javax.swing.*; @ExtensionImpl public class ThreeNegationsPerMethodInspection extends BaseInspection { + /** + * @noinspection PublicField + */ + public boolean m_ignoreInEquals = true; - /** - * @noinspection PublicField - */ - public boolean m_ignoreInEquals = true; + @SuppressWarnings("UnusedDeclaration") + public boolean ignoreInAssert = false; - @SuppressWarnings("UnusedDeclaration") - public boolean ignoreInAssert = false; - - @Override - @Nonnull - public String getID() { - return "MethodWithMoreThanThreeNegations"; - } + @Override + @Nonnull + public String getID() { + return "MethodWithMoreThanThreeNegations"; + } - @Override - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.threeNegationsPerMethodDisplayName().get(); - } + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.threeNegationsPerMethodDisplayName(); + } - @Override - public JComponent createOptionsPanel() { - final MultipleCheckboxOptionsPanel panel = new MultipleCheckboxOptionsPanel(this); - panel.addCheckbox(InspectionGadgetsLocalize.threeNegationsPerMethodIgnoreOption().get(), "m_ignoreInEquals"); - panel.addCheckbox(InspectionGadgetsLocalize.threeNegationsPerMethodIgnoreAssertOption().get(), "ignoreInAssert"); - return panel; - } + @Override + public JComponent createOptionsPanel() { + final MultipleCheckboxOptionsPanel panel = new MultipleCheckboxOptionsPanel(this); + panel.addCheckbox(InspectionGadgetsLocalize.threeNegationsPerMethodIgnoreOption().get(), "m_ignoreInEquals"); + panel.addCheckbox(InspectionGadgetsLocalize.threeNegationsPerMethodIgnoreAssertOption().get(), "ignoreInAssert"); + return panel; + } - @Override - @Nonnull - public String buildErrorString(Object... infos) { - final Integer negationCount = (Integer)infos[0]; - return InspectionGadgetsLocalize.threeNegationsPerMethodProblemDescriptor(negationCount).get(); - } + @Override + @Nonnull + public String buildErrorString(Object... infos) { + final Integer negationCount = (Integer) infos[0]; + return InspectionGadgetsLocalize.threeNegationsPerMethodProblemDescriptor(negationCount).get(); + } - @Override - public BaseInspectionVisitor buildVisitor() { - return new ThreeNegationsPerMethodVisitor(); - } + @Override + public BaseInspectionVisitor buildVisitor() { + return new ThreeNegationsPerMethodVisitor(); + } - private class ThreeNegationsPerMethodVisitor extends BaseInspectionVisitor { + private class ThreeNegationsPerMethodVisitor extends BaseInspectionVisitor { - @Override - public void visitMethod(@Nonnull PsiMethod method) { - // note: no call to super - if (method.getNameIdentifier() == null) { - return; - } - final NegationCountVisitor visitor = new NegationCountVisitor(ignoreInAssert); - method.accept(visitor); - final int negationCount = visitor.getCount(); - if (negationCount <= 3) { - return; - } - if (m_ignoreInEquals && MethodUtils.isEquals(method)) { - return; - } - registerMethodError(method, Integer.valueOf(negationCount)); + @Override + public void visitMethod(@Nonnull PsiMethod method) { + // note: no call to super + if (method.getNameIdentifier() == null) { + return; + } + final NegationCountVisitor visitor = new NegationCountVisitor(ignoreInAssert); + method.accept(visitor); + final int negationCount = visitor.getCount(); + if (negationCount <= 3) { + return; + } + if (m_ignoreInEquals && MethodUtils.isEquals(method)) { + return; + } + registerMethodError(method, Integer.valueOf(negationCount)); + } } - } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/methodmetrics/ThrownExceptionsPerMethodInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/methodmetrics/ThrownExceptionsPerMethodInspection.java index 0bd0681eb5..965f4e2207 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/methodmetrics/ThrownExceptionsPerMethodInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/methodmetrics/ThrownExceptionsPerMethodInspection.java @@ -21,57 +21,54 @@ import com.siyeh.ig.BaseInspectionVisitor; import com.siyeh.localize.InspectionGadgetsLocalize; import consulo.annotation.component.ExtensionImpl; +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; @ExtensionImpl -public class ThrownExceptionsPerMethodInspection - extends MethodMetricInspection { - - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.thrownExceptionsPerMethodDisplayName().get(); - } - - @Nonnull - public String getID() { - return "MethodWithTooExceptionsDeclared"; - } +public class ThrownExceptionsPerMethodInspection extends MethodMetricInspection { + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.thrownExceptionsPerMethodDisplayName(); + } - @Nonnull - public String buildErrorString(Object... infos) { - final Integer exceptionCount = (Integer)infos[0]; - return InspectionGadgetsLocalize.thrownExceptionsPerMethodProblemDescriptor(exceptionCount).get(); - } + @Nonnull + public String getID() { + return "MethodWithTooExceptionsDeclared"; + } - protected int getDefaultLimit() { - return 3; - } + @Nonnull + public String buildErrorString(Object... infos) { + final Integer exceptionCount = (Integer) infos[0]; + return InspectionGadgetsLocalize.thrownExceptionsPerMethodProblemDescriptor(exceptionCount).get(); + } - protected String getConfigurationLabel() { - return InspectionGadgetsLocalize.thrownExceptionsPerMethodLimitOption().get(); - } + protected int getDefaultLimit() { + return 3; + } - public BaseInspectionVisitor buildVisitor() { - return new ThrownExceptionsPerMethodVisitor(); - } + protected String getConfigurationLabel() { + return InspectionGadgetsLocalize.thrownExceptionsPerMethodLimitOption().get(); + } - private class ThrownExceptionsPerMethodVisitor - extends BaseInspectionVisitor { + public BaseInspectionVisitor buildVisitor() { + return new ThrownExceptionsPerMethodVisitor(); + } - @Override - public void visitMethod(@Nonnull PsiMethod method) { - // note: no call to super - if (method.getNameIdentifier() == null) { - return; - } - final PsiReferenceList throwList = method.getThrowsList(); - final PsiJavaCodeReferenceElement[] thrownExceptions = - throwList.getReferenceElements(); - final int exceptionCount = thrownExceptions.length; - if (exceptionCount <= getLimit()) { - return; - } - registerMethodError(method, Integer.valueOf(exceptionCount)); + private class ThrownExceptionsPerMethodVisitor extends BaseInspectionVisitor { + @Override + public void visitMethod(@Nonnull PsiMethod method) { + // note: no call to super + if (method.getNameIdentifier() == null) { + return; + } + final PsiReferenceList throwList = method.getThrowsList(); + final PsiJavaCodeReferenceElement[] thrownExceptions = throwList.getReferenceElements(); + final int exceptionCount = thrownExceptions.length; + if (exceptionCount <= getLimit()) { + return; + } + registerMethodError(method, Integer.valueOf(exceptionCount)); + } } - } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/migration/RawUseOfParameterizedTypeInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/migration/RawUseOfParameterizedTypeInspection.java index c1f672b6c8..f262f05917 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/migration/RawUseOfParameterizedTypeInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/migration/RawUseOfParameterizedTypeInspection.java @@ -26,6 +26,7 @@ import consulo.language.psi.PsiComment; import consulo.language.psi.PsiElement; import consulo.language.psi.util.PsiTreeUtil; +import consulo.localize.LocalizeValue; import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; @@ -34,151 +35,154 @@ @ExtensionImpl public class RawUseOfParameterizedTypeInspection extends BaseInspection { - @SuppressWarnings("PublicField") public boolean ignoreObjectConstruction = true; - - @SuppressWarnings("PublicField") public boolean ignoreTypeCasts = false; - - @SuppressWarnings("PublicField") public boolean ignoreUncompilable = false; - - @Override - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.rawUseOfParameterizedTypeDisplayName().get(); - } - - @Override - @Nonnull - protected String buildErrorString(Object... infos) { - return InspectionGadgetsLocalize.rawUseOfParameterizedTypeProblemDescriptor().get(); - } - - @Override - @Nullable - public JComponent createOptionsPanel() { - final MultipleCheckboxOptionsPanel optionsPanel = new MultipleCheckboxOptionsPanel(this); - optionsPanel.addCheckbox( - InspectionGadgetsLocalize.rawUseOfParameterizedTypeIgnoreNewObjectsOption().get(), - "ignoreObjectConstruction" - ); - optionsPanel.addCheckbox( - InspectionGadgetsLocalize.rawUseOfParameterizedTypeIgnoreTypeCastsOption().get(), - "ignoreTypeCasts" - ); - optionsPanel.addCheckbox( - InspectionGadgetsLocalize.rawUseOfParameterizedTypeIgnoreUncompilableOption().get(), - "ignoreUncompilable" - ); - return optionsPanel; - } - - @Override - public String getAlternativeID() { - return "rawtypes"; - } - - @Override - public BaseInspectionVisitor buildVisitor() { - return new RawUseOfParameterizedTypeVisitor(); - } - - private class RawUseOfParameterizedTypeVisitor extends BaseInspectionVisitor { + @SuppressWarnings("PublicField") + public boolean ignoreObjectConstruction = true; + @SuppressWarnings("PublicField") + public boolean ignoreTypeCasts = false; + + @SuppressWarnings("PublicField") + public boolean ignoreUncompilable = false; + + @Nonnull @Override - public void visitNewExpression(@Nonnull PsiNewExpression expression) { - if (!hasNeededLanguageLevel(expression)) { - return; - } - super.visitNewExpression(expression); - if (ignoreObjectConstruction) { - return; - } - final PsiJavaCodeReferenceElement classReference = expression.getClassOrAnonymousClassReference(); - checkReferenceElement(classReference); + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.rawUseOfParameterizedTypeDisplayName(); } @Override - public void visitTypeElement(@Nonnull PsiTypeElement typeElement) { - if (!hasNeededLanguageLevel(typeElement)) { - return; - } - final PsiType type = typeElement.getType(); - if (type instanceof PsiArrayType) { - return; - } - super.visitTypeElement(typeElement); - final PsiElement parent = typeElement.getParent(); - if (parent instanceof PsiInstanceOfExpression || parent instanceof PsiClassObjectAccessExpression) { - return; - } - if (ignoreTypeCasts && parent instanceof PsiTypeCastExpression) { - return; - } - if (PsiTreeUtil.getParentOfType(typeElement, PsiComment.class) != null) { - return; - } - final PsiAnnotationMethod annotationMethod = - PsiTreeUtil.getParentOfType(typeElement, PsiAnnotationMethod.class, true, PsiClass.class); - if (ignoreUncompilable && annotationMethod != null) { - // type of class type parameter cannot be parameterized if annotation method has default value - final PsiAnnotationMemberValue defaultValue = annotationMethod.getDefaultValue(); - if (defaultValue != null && parent != annotationMethod) { - return; - } - } - final PsiJavaCodeReferenceElement referenceElement = typeElement.getInnermostComponentReferenceElement(); - checkReferenceElement(referenceElement); + @Nonnull + protected String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.rawUseOfParameterizedTypeProblemDescriptor().get(); } @Override - public void visitReferenceElement(PsiJavaCodeReferenceElement reference) { - if (!hasNeededLanguageLevel(reference)) { - return; - } - super.visitReferenceElement(reference); - final PsiElement referenceParent = reference.getParent(); - if (!(referenceParent instanceof PsiReferenceList)) { - return; - } - final PsiReferenceList referenceList = (PsiReferenceList)referenceParent; - final PsiElement listParent = referenceList.getParent(); - if (!(listParent instanceof PsiClass)) { - return; - } - checkReferenceElement(reference); + @Nullable + public JComponent createOptionsPanel() { + final MultipleCheckboxOptionsPanel optionsPanel = new MultipleCheckboxOptionsPanel(this); + optionsPanel.addCheckbox( + InspectionGadgetsLocalize.rawUseOfParameterizedTypeIgnoreNewObjectsOption().get(), + "ignoreObjectConstruction" + ); + optionsPanel.addCheckbox( + InspectionGadgetsLocalize.rawUseOfParameterizedTypeIgnoreTypeCastsOption().get(), + "ignoreTypeCasts" + ); + optionsPanel.addCheckbox( + InspectionGadgetsLocalize.rawUseOfParameterizedTypeIgnoreUncompilableOption().get(), + "ignoreUncompilable" + ); + return optionsPanel; } - private void checkReferenceElement(PsiJavaCodeReferenceElement reference) { - if (reference == null) { - return; - } - final PsiType[] typeParameters = reference.getTypeParameters(); - if (typeParameters.length > 0) { - return; - } - final PsiElement element = reference.resolve(); - if (!(element instanceof PsiClass)) { - return; - } - final PsiClass aClass = (PsiClass)element; - final PsiElement qualifier = reference.getQualifier(); - if (qualifier instanceof PsiJavaCodeReferenceElement) { - final PsiJavaCodeReferenceElement qualifierReference = (PsiJavaCodeReferenceElement)qualifier; - if (!aClass.hasModifierProperty(PsiModifier.STATIC) && !aClass.isInterface() && !aClass.isEnum()) { - checkReferenceElement(qualifierReference); - } - } - if (!aClass.hasTypeParameters()) { - return; - } - registerError(reference); + @Override + public String getAlternativeID() { + return "rawtypes"; } - private boolean hasNeededLanguageLevel(PsiElement element) { - if (element.getLanguage() != JavaLanguage.INSTANCE) { - return false; - } - return PsiUtil.isLanguageLevel5OrHigher(element); + @Override + public BaseInspectionVisitor buildVisitor() { + return new RawUseOfParameterizedTypeVisitor(); + } + + private class RawUseOfParameterizedTypeVisitor extends BaseInspectionVisitor { + + @Override + public void visitNewExpression(@Nonnull PsiNewExpression expression) { + if (!hasNeededLanguageLevel(expression)) { + return; + } + super.visitNewExpression(expression); + if (ignoreObjectConstruction) { + return; + } + final PsiJavaCodeReferenceElement classReference = expression.getClassOrAnonymousClassReference(); + checkReferenceElement(classReference); + } + + @Override + public void visitTypeElement(@Nonnull PsiTypeElement typeElement) { + if (!hasNeededLanguageLevel(typeElement)) { + return; + } + final PsiType type = typeElement.getType(); + if (type instanceof PsiArrayType) { + return; + } + super.visitTypeElement(typeElement); + final PsiElement parent = typeElement.getParent(); + if (parent instanceof PsiInstanceOfExpression || parent instanceof PsiClassObjectAccessExpression) { + return; + } + if (ignoreTypeCasts && parent instanceof PsiTypeCastExpression) { + return; + } + if (PsiTreeUtil.getParentOfType(typeElement, PsiComment.class) != null) { + return; + } + final PsiAnnotationMethod annotationMethod = + PsiTreeUtil.getParentOfType(typeElement, PsiAnnotationMethod.class, true, PsiClass.class); + if (ignoreUncompilable && annotationMethod != null) { + // type of class type parameter cannot be parameterized if annotation method has default value + final PsiAnnotationMemberValue defaultValue = annotationMethod.getDefaultValue(); + if (defaultValue != null && parent != annotationMethod) { + return; + } + } + final PsiJavaCodeReferenceElement referenceElement = typeElement.getInnermostComponentReferenceElement(); + checkReferenceElement(referenceElement); + } + + @Override + public void visitReferenceElement(PsiJavaCodeReferenceElement reference) { + if (!hasNeededLanguageLevel(reference)) { + return; + } + super.visitReferenceElement(reference); + final PsiElement referenceParent = reference.getParent(); + if (!(referenceParent instanceof PsiReferenceList)) { + return; + } + final PsiReferenceList referenceList = (PsiReferenceList) referenceParent; + final PsiElement listParent = referenceList.getParent(); + if (!(listParent instanceof PsiClass)) { + return; + } + checkReferenceElement(reference); + } + + private void checkReferenceElement(PsiJavaCodeReferenceElement reference) { + if (reference == null) { + return; + } + final PsiType[] typeParameters = reference.getTypeParameters(); + if (typeParameters.length > 0) { + return; + } + final PsiElement element = reference.resolve(); + if (!(element instanceof PsiClass)) { + return; + } + final PsiClass aClass = (PsiClass) element; + final PsiElement qualifier = reference.getQualifier(); + if (qualifier instanceof PsiJavaCodeReferenceElement) { + final PsiJavaCodeReferenceElement qualifierReference = (PsiJavaCodeReferenceElement) qualifier; + if (!aClass.hasModifierProperty(PsiModifier.STATIC) && !aClass.isInterface() && !aClass.isEnum()) { + checkReferenceElement(qualifierReference); + } + } + if (!aClass.hasTypeParameters()) { + return; + } + registerError(reference); + } + + private boolean hasNeededLanguageLevel(PsiElement element) { + if (element.getLanguage() != JavaLanguage.INSTANCE) { + return false; + } + return PsiUtil.isLanguageLevel5OrHigher(element); + } } - } } diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/migration/StringBufferReplaceableByStringBuilderInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/migration/StringBufferReplaceableByStringBuilderInspection.java index fb14af08c2..b5e28fde7d 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/migration/StringBufferReplaceableByStringBuilderInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/migration/StringBufferReplaceableByStringBuilderInspection.java @@ -28,6 +28,7 @@ import consulo.language.psi.PsiElement; import consulo.language.psi.util.PsiTreeUtil; import consulo.language.util.IncorrectOperationException; +import consulo.localize.LocalizeValue; import consulo.project.Project; import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; @@ -40,171 +41,174 @@ @ExtensionImpl public class StringBufferReplaceableByStringBuilderInspection extends BaseInspection { - @Override - public boolean isEnabledByDefault() { - return true; - } - - @Override - @Nonnull - public String getID() { - return "StringBufferMayBeStringBuilder"; - } - - @Override - @Nonnull - public String getDisplayName() { - return InspectionGadgetsLocalize.stringBufferReplaceableByStringBuilderDisplayName().get(); - } - - @Override - @Nonnull - protected String buildErrorString(Object... infos) { - return InspectionGadgetsLocalize.stringBufferReplaceableByStringBuilderProblemDescriptor().get(); - } - - @Override - public InspectionGadgetsFix buildFix(Object... infos) { - return new StringBufferMayBeStringBuilderFix(); - } - - @Nullable - private static PsiNewExpression getNewStringBuffer(PsiExpression expression) { - if (expression == null) { - return null; - } - else if (expression instanceof PsiNewExpression) { - return (PsiNewExpression)expression; + @Override + public boolean isEnabledByDefault() { + return true; } - else if (expression instanceof PsiMethodCallExpression) { - final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression)expression; - final PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression(); - @NonNls final String methodName = methodExpression.getReferenceName(); - if (!"append".equals(methodName)) { - return null; - } - final PsiExpression qualifier = methodExpression.getQualifierExpression(); - return getNewStringBuffer(qualifier); + + @Override + @Nonnull + public String getID() { + return "StringBufferMayBeStringBuilder"; } - return null; - } - private static class StringBufferMayBeStringBuilderFix extends InspectionGadgetsFix { + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.stringBufferReplaceableByStringBuilderDisplayName(); + } + @Override @Nonnull - public String getName() { - return InspectionGadgetsLocalize.stringBufferReplaceableByStringBuilderReplaceQuickfix().get(); + protected String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.stringBufferReplaceableByStringBuilderProblemDescriptor().get(); } @Override - public void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { - final PsiElement element = descriptor.getPsiElement(); - final PsiElement parent = element.getParent(); - final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); - final PsiClass stringBuilderClass = psiFacade.findClass(CommonClassNames.JAVA_LANG_STRING_BUILDER, element.getResolveScope()); - if (stringBuilderClass == null) { - return; - } - final PsiElementFactory factory = psiFacade.getElementFactory(); - final PsiJavaCodeReferenceElement stringBuilderClassReference = factory.createClassReferenceElement(stringBuilderClass); - final PsiClassType stringBuilderType = factory.createType(stringBuilderClass); - final PsiTypeElement stringBuilderTypeElement = factory.createTypeElement(stringBuilderType); - final PsiElement grandParent = parent.getParent(); - final PsiDeclarationStatement declarationStatement = (PsiDeclarationStatement)grandParent; - final PsiElement[] declaredElements = declarationStatement.getDeclaredElements(); - for (PsiElement declaredElement : declaredElements) { - if (!(declaredElement instanceof PsiVariable)) { - continue; - } - replaceWithStringBuilder(stringBuilderClassReference, stringBuilderTypeElement, (PsiVariable)declaredElement); - } + public InspectionGadgetsFix buildFix(Object... infos) { + return new StringBufferMayBeStringBuilderFix(); } - private static void replaceWithStringBuilder(PsiJavaCodeReferenceElement newClassReference, - PsiTypeElement newTypeElement, - PsiVariable variable) { - final PsiExpression initializer = getNewStringBuffer(variable.getInitializer()); - if (initializer == null) { - return; - } - final PsiNewExpression newExpression = (PsiNewExpression)initializer; - final PsiJavaCodeReferenceElement classReference = newExpression.getClassReference(); // no anonymous classes because StringBuffer is final - if (classReference == null) { - return; - } - final PsiTypeElement typeElement = variable.getTypeElement(); - if (typeElement != null && typeElement.getParent() == variable) { - typeElement.replace(newTypeElement); - } - classReference.replace(newClassReference); + @Nullable + private static PsiNewExpression getNewStringBuffer(PsiExpression expression) { + if (expression == null) { + return null; + } + else if (expression instanceof PsiNewExpression) { + return (PsiNewExpression) expression; + } + else if (expression instanceof PsiMethodCallExpression) { + final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression) expression; + final PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression(); + @NonNls final String methodName = methodExpression.getReferenceName(); + if (!"append".equals(methodName)) { + return null; + } + final PsiExpression qualifier = methodExpression.getQualifierExpression(); + return getNewStringBuffer(qualifier); + } + return null; } - } - @Override - public BaseInspectionVisitor buildVisitor() { - return new StringBufferReplaceableByStringBuilderVisitor(); - } + private static class StringBufferMayBeStringBuilderFix extends InspectionGadgetsFix { + @Nonnull + @Override + public LocalizeValue getName() { + return InspectionGadgetsLocalize.stringBufferReplaceableByStringBuilderReplaceQuickfix(); + } - private static class StringBufferReplaceableByStringBuilderVisitor extends BaseInspectionVisitor { + @Override + public void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { + final PsiElement element = descriptor.getPsiElement(); + final PsiElement parent = element.getParent(); + final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); + final PsiClass stringBuilderClass = psiFacade.findClass(CommonClassNames.JAVA_LANG_STRING_BUILDER, element.getResolveScope()); + if (stringBuilderClass == null) { + return; + } + final PsiElementFactory factory = psiFacade.getElementFactory(); + final PsiJavaCodeReferenceElement stringBuilderClassReference = factory.createClassReferenceElement(stringBuilderClass); + final PsiClassType stringBuilderType = factory.createType(stringBuilderClass); + final PsiTypeElement stringBuilderTypeElement = factory.createTypeElement(stringBuilderType); + final PsiElement grandParent = parent.getParent(); + final PsiDeclarationStatement declarationStatement = (PsiDeclarationStatement) grandParent; + final PsiElement[] declaredElements = declarationStatement.getDeclaredElements(); + for (PsiElement declaredElement : declaredElements) { + if (!(declaredElement instanceof PsiVariable)) { + continue; + } + replaceWithStringBuilder(stringBuilderClassReference, stringBuilderTypeElement, (PsiVariable) declaredElement); + } + } - private static final Set excludes = - new HashSet(Arrays.asList(CommonClassNames.JAVA_LANG_STRING_BUILDER, CommonClassNames.JAVA_LANG_STRING_BUFFER)); + private static void replaceWithStringBuilder( + PsiJavaCodeReferenceElement newClassReference, + PsiTypeElement newTypeElement, + PsiVariable variable + ) { + final PsiExpression initializer = getNewStringBuffer(variable.getInitializer()); + if (initializer == null) { + return; + } + final PsiNewExpression newExpression = (PsiNewExpression) initializer; + final PsiJavaCodeReferenceElement classReference = + newExpression.getClassReference(); // no anonymous classes because StringBuffer is final + if (classReference == null) { + return; + } + final PsiTypeElement typeElement = variable.getTypeElement(); + if (typeElement != null && typeElement.getParent() == variable) { + typeElement.replace(newTypeElement); + } + classReference.replace(newClassReference); + } + } @Override - public void visitDeclarationStatement(PsiDeclarationStatement statement) { - if (!PsiUtil.isLanguageLevel5OrHigher(statement)) { - return; - } - super.visitDeclarationStatement(statement); - final PsiElement[] declaredElements = statement.getDeclaredElements(); - if (declaredElements.length == 0) { - return; - } - for (PsiElement declaredElement : declaredElements) { - if (!(declaredElement instanceof PsiLocalVariable)) { - return; - } - final PsiLocalVariable variable = (PsiLocalVariable)declaredElement; - final PsiElement context = PsiTreeUtil.getParentOfType(variable, PsiCodeBlock.class, true, PsiClass.class); - if (!isReplaceableStringBuffer(variable, context)) { - return; - } - } - final PsiLocalVariable firstVariable = (PsiLocalVariable)declaredElements[0]; - registerVariableError(firstVariable); + public BaseInspectionVisitor buildVisitor() { + return new StringBufferReplaceableByStringBuilderVisitor(); } - private static boolean isReplaceableStringBuffer(PsiVariable variable, PsiElement context) { - if (context == null) { - return false; - } - final PsiType type = variable.getType(); - if (!TypeUtils.typeEquals(CommonClassNames.JAVA_LANG_STRING_BUFFER, type)) { - return false; - } - final PsiExpression initializer = variable.getInitializer(); - if (initializer == null) { - return false; - } - if (getNewStringBuffer(initializer) == null) { - return false; - } - if (VariableAccessUtils.variableIsAssigned(variable, context)) { - return false; - } - if (VariableAccessUtils.variableIsAssignedFrom(variable, context)) { - return false; - } - if (VariableAccessUtils.variableIsReturned(variable, context, true)) { - return false; - } - if (VariableAccessUtils.variableIsPassedAsMethodArgument(variable, excludes, context, true)) { - return false; - } - if (VariableAccessUtils.variableIsUsedInInnerClass(variable, context)) { - return false; - } - return true; + private static class StringBufferReplaceableByStringBuilderVisitor extends BaseInspectionVisitor { + + private static final Set excludes = + new HashSet(Arrays.asList(CommonClassNames.JAVA_LANG_STRING_BUILDER, CommonClassNames.JAVA_LANG_STRING_BUFFER)); + + @Override + public void visitDeclarationStatement(PsiDeclarationStatement statement) { + if (!PsiUtil.isLanguageLevel5OrHigher(statement)) { + return; + } + super.visitDeclarationStatement(statement); + final PsiElement[] declaredElements = statement.getDeclaredElements(); + if (declaredElements.length == 0) { + return; + } + for (PsiElement declaredElement : declaredElements) { + if (!(declaredElement instanceof PsiLocalVariable)) { + return; + } + final PsiLocalVariable variable = (PsiLocalVariable) declaredElement; + final PsiElement context = PsiTreeUtil.getParentOfType(variable, PsiCodeBlock.class, true, PsiClass.class); + if (!isReplaceableStringBuffer(variable, context)) { + return; + } + } + final PsiLocalVariable firstVariable = (PsiLocalVariable) declaredElements[0]; + registerVariableError(firstVariable); + } + + private static boolean isReplaceableStringBuffer(PsiVariable variable, PsiElement context) { + if (context == null) { + return false; + } + final PsiType type = variable.getType(); + if (!TypeUtils.typeEquals(CommonClassNames.JAVA_LANG_STRING_BUFFER, type)) { + return false; + } + final PsiExpression initializer = variable.getInitializer(); + if (initializer == null) { + return false; + } + if (getNewStringBuffer(initializer) == null) { + return false; + } + if (VariableAccessUtils.variableIsAssigned(variable, context)) { + return false; + } + if (VariableAccessUtils.variableIsAssignedFrom(variable, context)) { + return false; + } + if (VariableAccessUtils.variableIsReturned(variable, context, true)) { + return false; + } + if (VariableAccessUtils.variableIsPassedAsMethodArgument(variable, excludes, context, true)) { + return false; + } + if (VariableAccessUtils.variableIsUsedInInnerClass(variable, context)) { + return false; + } + return true; + } } - } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/migration/TryFinallyCanBeTryWithResourcesInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/migration/TryFinallyCanBeTryWithResourcesInspection.java index 1989e2f917..15cdb5950e 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/migration/TryFinallyCanBeTryWithResourcesInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/migration/TryFinallyCanBeTryWithResourcesInspection.java @@ -31,10 +31,10 @@ import consulo.language.psi.PsiWhiteSpace; import consulo.language.psi.util.PsiTreeUtil; import consulo.language.util.IncorrectOperationException; +import consulo.localize.LocalizeValue; import consulo.project.Project; import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; -import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NonNls; import java.util.*; @@ -44,525 +44,518 @@ */ @ExtensionImpl public class TryFinallyCanBeTryWithResourcesInspection extends BaseInspection { - - @Override - public boolean isEnabledByDefault() { - return true; - } - - @Nls - @Nonnull - @Override - public String getDisplayName() { - return InspectionGadgetsLocalize.tryFinallyCanBeTryWithResourcesDisplayName().get(); - } - - @Nonnull - @Override - protected String buildErrorString(Object... infos) { - return InspectionGadgetsLocalize.tryFinallyCanBeTryWithResourcesProblemDescriptor().get(); - } - - @Override - protected InspectionGadgetsFix buildFix(Object... infos) { - return new TryFinallyCanBeTryWithResourcesFix(); - } - - private static class TryFinallyCanBeTryWithResourcesFix extends InspectionGadgetsFix { - - public TryFinallyCanBeTryWithResourcesFix() {} + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.tryFinallyCanBeTryWithResourcesDisplayName(); + } @Nonnull - public String getName() { - return InspectionGadgetsLocalize.tryFinallyCanBeTryWithResourcesQuickfix().get(); + @Override + protected String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.tryFinallyCanBeTryWithResourcesProblemDescriptor().get(); } @Override - protected void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { - final PsiElement element = descriptor.getPsiElement(); - final PsiElement parent = element.getParent(); - if (!(parent instanceof PsiTryStatement)) { - return; - } - final PsiTryStatement tryStatement = (PsiTryStatement)parent; - final PsiCodeBlock tryBlock = tryStatement.getTryBlock(); - if (tryBlock == null) { - return; - } - final PsiCodeBlock finallyBlock = tryStatement.getFinallyBlock(); - if (finallyBlock == null) { - return; - } - final PsiElement[] tryBlockChildren = tryBlock.getChildren(); - final Set variables = new HashSet(); - for (PsiLocalVariable variable : collectVariables(tryStatement)) { - if (!isVariableUsedOutsideContext(variable, tryBlock)) { - variables.add(variable); - } - } - final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project); - @NonNls final StringBuilder newTryStatementText = new StringBuilder("try ("); - final Set unwantedChildren = new HashSet(2); - boolean separator = false; - for (PsiLocalVariable variable : variables) { - final boolean hasInitializer; - final PsiExpression initializer = variable.getInitializer(); - if (initializer == null) { - hasInitializer = false; - } - else { - final PsiType type = initializer.getType(); - hasInitializer = !PsiType.NULL.equals(type); - } - if (separator) { - newTryStatementText.append(';'); - } - newTryStatementText.append(variable.getTypeElement().getText()).append(' ').append(variable.getName()).append('='); - if (hasInitializer) { - newTryStatementText.append(initializer.getText()); - } - else { - final int index = findInitialization(tryBlockChildren, variable, hasInitializer); - if (index < 0) { - return; - } - unwantedChildren.add(Integer.valueOf(index)); - final PsiExpressionStatement expressionStatement = (PsiExpressionStatement)tryBlockChildren[index]; - if (expressionStatement.getNextSibling() instanceof PsiWhiteSpace) { - unwantedChildren.add(Integer.valueOf(index + 1)); - } - final PsiAssignmentExpression assignmentExpression = (PsiAssignmentExpression)expressionStatement.getExpression(); - final PsiExpression rhs = assignmentExpression.getRExpression(); - if (rhs == null) { - return; - } - newTryStatementText.append(rhs.getText()); - } - separator = true; - } - newTryStatementText.append(") {"); - final int tryBlockStatementsLength = tryBlockChildren.length - 1; - for (int i = 1; i < tryBlockStatementsLength; i++) { - final PsiElement child = tryBlockChildren[i]; - if (unwantedChildren.contains(Integer.valueOf(i))) { - continue; - } - newTryStatementText.append(child.getText()); - } - newTryStatementText.append('}'); - final PsiCatchSection[] catchSections = tryStatement.getCatchSections(); - for (PsiCatchSection catchSection : catchSections) { - newTryStatementText.append(catchSection.getText()); - } - final PsiElement[] finallyChildren = finallyBlock.getChildren(); - boolean appended = false; - final int finallyChildrenLength = finallyChildren.length - 1; - final List savedComments = new ArrayList(); - for (int i = 1; i < finallyChildrenLength; i++) { - final PsiElement child = finallyChildren[i]; - if (isCloseStatement(child, variables)) { - continue; - } - if (!appended) { - if (child instanceof PsiComment) { - final PsiElement prevSibling = child.getPrevSibling(); - if (prevSibling instanceof PsiWhiteSpace) { - savedComments.add(prevSibling); - } - savedComments.add(child); - } - else if (!(child instanceof PsiWhiteSpace)) { - newTryStatementText.append(" finally {"); - for (PsiElement savedComment : savedComments) { - newTryStatementText.append(savedComment.getText()); - } - newTryStatementText.append(child.getText()); - appended = true; - } - } - else { - newTryStatementText.append(child.getText()); - } - } - if (appended) { - newTryStatementText.append('}'); - } - for (PsiLocalVariable variable : variables) { - variable.delete(); - } - if (!appended) { - final int savedCommentsSize = savedComments.size(); - final PsiElement parent1 = tryStatement.getParent(); - for (int i = savedCommentsSize - 1; i >= 0; i--) { - final PsiElement savedComment = savedComments.get(i); - parent1.addAfter(savedComment, tryStatement); - } - } - final PsiStatement newTryStatement = factory.createStatementFromText(newTryStatementText.toString(), element); - tryStatement.replace(newTryStatement); + protected InspectionGadgetsFix buildFix(Object... infos) { + return new TryFinallyCanBeTryWithResourcesFix(); } - private static boolean isCloseStatement(PsiElement element, Set variables) { - if (element instanceof PsiExpressionStatement) { - final PsiExpressionStatement expressionStatement = (PsiExpressionStatement)element; - final PsiExpression expression = expressionStatement.getExpression(); - if (!(expression instanceof PsiMethodCallExpression)) { - return false; - } - final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression)expression; - final PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression(); - final String methodName = methodExpression.getReferenceName(); - if (!HardcodedMethodConstants.CLOSE.equals(methodName)) { - return false; - } - final PsiExpression qualifier = methodExpression.getQualifierExpression(); - if (!(qualifier instanceof PsiReferenceExpression)) { - return false; - } - final PsiReferenceExpression referenceExpression = (PsiReferenceExpression)qualifier; - final PsiElement target = referenceExpression.resolve(); - if (!(target instanceof PsiLocalVariable)) { - return false; - } - final PsiLocalVariable variable = (PsiLocalVariable)target; - return variables.contains(variable); - } - else if (element instanceof PsiIfStatement) { - final PsiIfStatement ifStatement = (PsiIfStatement)element; - if (ifStatement.getElseBranch() != null) { - return false; - } - final PsiExpression condition = ifStatement.getCondition(); - if (!(condition instanceof PsiBinaryExpression)) { - return false; - } - final PsiBinaryExpression binaryExpression = (PsiBinaryExpression)condition; - final IElementType tokenType = binaryExpression.getOperationTokenType(); - if (!JavaTokenType.NE.equals(tokenType)) { - return false; - } - final PsiExpression lhs = binaryExpression.getLOperand(); - final PsiExpression rhs = binaryExpression.getROperand(); - if (rhs == null) { - return false; - } - final PsiElement variable; - if (PsiType.NULL.equals(rhs.getType())) { - if (!(lhs instanceof PsiReferenceExpression)) { - return false; - } - final PsiReferenceExpression referenceExpression = (PsiReferenceExpression)lhs; - variable = referenceExpression.resolve(); - if (!(variable instanceof PsiLocalVariable)) { - return false; - } + private static class TryFinallyCanBeTryWithResourcesFix extends InspectionGadgetsFix { + @Nonnull + @Override + public LocalizeValue getName() { + return InspectionGadgetsLocalize.tryFinallyCanBeTryWithResourcesQuickfix(); } - else if (PsiType.NULL.equals(lhs.getType())) { - if (!(rhs instanceof PsiReferenceExpression)) { - return false; - } - final PsiReferenceExpression referenceExpression = (PsiReferenceExpression)rhs; - variable = referenceExpression.resolve(); - if (!(variable instanceof PsiLocalVariable)) { - return false; - } - } - else { - return false; - } - final PsiStatement thenBranch = ifStatement.getThenBranch(); - if (thenBranch instanceof PsiExpressionStatement) { - return isCloseStatement(thenBranch, variables); - } - else if (thenBranch instanceof PsiBlockStatement) { - final PsiBlockStatement blockStatement = (PsiBlockStatement)thenBranch; - final PsiCodeBlock codeBlock = blockStatement.getCodeBlock(); - final PsiStatement[] statements = codeBlock.getStatements(); - return statements.length == 1 && isCloseStatement(statements[0], variables); + + @Override + protected void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { + final PsiElement element = descriptor.getPsiElement(); + final PsiElement parent = element.getParent(); + if (!(parent instanceof PsiTryStatement)) { + return; + } + final PsiTryStatement tryStatement = (PsiTryStatement) parent; + final PsiCodeBlock tryBlock = tryStatement.getTryBlock(); + if (tryBlock == null) { + return; + } + final PsiCodeBlock finallyBlock = tryStatement.getFinallyBlock(); + if (finallyBlock == null) { + return; + } + final PsiElement[] tryBlockChildren = tryBlock.getChildren(); + final Set variables = new HashSet(); + for (PsiLocalVariable variable : collectVariables(tryStatement)) { + if (!isVariableUsedOutsideContext(variable, tryBlock)) { + variables.add(variable); + } + } + final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project); + @NonNls final StringBuilder newTryStatementText = new StringBuilder("try ("); + final Set unwantedChildren = new HashSet(2); + boolean separator = false; + for (PsiLocalVariable variable : variables) { + final boolean hasInitializer; + final PsiExpression initializer = variable.getInitializer(); + if (initializer == null) { + hasInitializer = false; + } + else { + final PsiType type = initializer.getType(); + hasInitializer = !PsiType.NULL.equals(type); + } + if (separator) { + newTryStatementText.append(';'); + } + newTryStatementText.append(variable.getTypeElement().getText()).append(' ').append(variable.getName()).append('='); + if (hasInitializer) { + newTryStatementText.append(initializer.getText()); + } + else { + final int index = findInitialization(tryBlockChildren, variable, hasInitializer); + if (index < 0) { + return; + } + unwantedChildren.add(Integer.valueOf(index)); + final PsiExpressionStatement expressionStatement = (PsiExpressionStatement) tryBlockChildren[index]; + if (expressionStatement.getNextSibling() instanceof PsiWhiteSpace) { + unwantedChildren.add(Integer.valueOf(index + 1)); + } + final PsiAssignmentExpression assignmentExpression = (PsiAssignmentExpression) expressionStatement.getExpression(); + final PsiExpression rhs = assignmentExpression.getRExpression(); + if (rhs == null) { + return; + } + newTryStatementText.append(rhs.getText()); + } + separator = true; + } + newTryStatementText.append(") {"); + final int tryBlockStatementsLength = tryBlockChildren.length - 1; + for (int i = 1; i < tryBlockStatementsLength; i++) { + final PsiElement child = tryBlockChildren[i]; + if (unwantedChildren.contains(Integer.valueOf(i))) { + continue; + } + newTryStatementText.append(child.getText()); + } + newTryStatementText.append('}'); + final PsiCatchSection[] catchSections = tryStatement.getCatchSections(); + for (PsiCatchSection catchSection : catchSections) { + newTryStatementText.append(catchSection.getText()); + } + final PsiElement[] finallyChildren = finallyBlock.getChildren(); + boolean appended = false; + final int finallyChildrenLength = finallyChildren.length - 1; + final List savedComments = new ArrayList(); + for (int i = 1; i < finallyChildrenLength; i++) { + final PsiElement child = finallyChildren[i]; + if (isCloseStatement(child, variables)) { + continue; + } + if (!appended) { + if (child instanceof PsiComment) { + final PsiElement prevSibling = child.getPrevSibling(); + if (prevSibling instanceof PsiWhiteSpace) { + savedComments.add(prevSibling); + } + savedComments.add(child); + } + else if (!(child instanceof PsiWhiteSpace)) { + newTryStatementText.append(" finally {"); + for (PsiElement savedComment : savedComments) { + newTryStatementText.append(savedComment.getText()); + } + newTryStatementText.append(child.getText()); + appended = true; + } + } + else { + newTryStatementText.append(child.getText()); + } + } + if (appended) { + newTryStatementText.append('}'); + } + for (PsiLocalVariable variable : variables) { + variable.delete(); + } + if (!appended) { + final int savedCommentsSize = savedComments.size(); + final PsiElement parent1 = tryStatement.getParent(); + for (int i = savedCommentsSize - 1; i >= 0; i--) { + final PsiElement savedComment = savedComments.get(i); + parent1.addAfter(savedComment, tryStatement); + } + } + final PsiStatement newTryStatement = factory.createStatementFromText(newTryStatementText.toString(), element); + tryStatement.replace(newTryStatement); } - else { - return false; + + private static boolean isCloseStatement(PsiElement element, Set variables) { + if (element instanceof PsiExpressionStatement) { + final PsiExpressionStatement expressionStatement = (PsiExpressionStatement) element; + final PsiExpression expression = expressionStatement.getExpression(); + if (!(expression instanceof PsiMethodCallExpression)) { + return false; + } + final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression) expression; + final PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression(); + final String methodName = methodExpression.getReferenceName(); + if (!HardcodedMethodConstants.CLOSE.equals(methodName)) { + return false; + } + final PsiExpression qualifier = methodExpression.getQualifierExpression(); + if (!(qualifier instanceof PsiReferenceExpression)) { + return false; + } + final PsiReferenceExpression referenceExpression = (PsiReferenceExpression) qualifier; + final PsiElement target = referenceExpression.resolve(); + if (!(target instanceof PsiLocalVariable)) { + return false; + } + final PsiLocalVariable variable = (PsiLocalVariable) target; + return variables.contains(variable); + } + else if (element instanceof PsiIfStatement) { + final PsiIfStatement ifStatement = (PsiIfStatement) element; + if (ifStatement.getElseBranch() != null) { + return false; + } + final PsiExpression condition = ifStatement.getCondition(); + if (!(condition instanceof PsiBinaryExpression)) { + return false; + } + final PsiBinaryExpression binaryExpression = (PsiBinaryExpression) condition; + final IElementType tokenType = binaryExpression.getOperationTokenType(); + if (!JavaTokenType.NE.equals(tokenType)) { + return false; + } + final PsiExpression lhs = binaryExpression.getLOperand(); + final PsiExpression rhs = binaryExpression.getROperand(); + if (rhs == null) { + return false; + } + final PsiElement variable; + if (PsiType.NULL.equals(rhs.getType())) { + if (!(lhs instanceof PsiReferenceExpression)) { + return false; + } + final PsiReferenceExpression referenceExpression = (PsiReferenceExpression) lhs; + variable = referenceExpression.resolve(); + if (!(variable instanceof PsiLocalVariable)) { + return false; + } + } + else if (PsiType.NULL.equals(lhs.getType())) { + if (!(rhs instanceof PsiReferenceExpression)) { + return false; + } + final PsiReferenceExpression referenceExpression = (PsiReferenceExpression) rhs; + variable = referenceExpression.resolve(); + if (!(variable instanceof PsiLocalVariable)) { + return false; + } + } + else { + return false; + } + final PsiStatement thenBranch = ifStatement.getThenBranch(); + if (thenBranch instanceof PsiExpressionStatement) { + return isCloseStatement(thenBranch, variables); + } + else if (thenBranch instanceof PsiBlockStatement) { + final PsiBlockStatement blockStatement = (PsiBlockStatement) thenBranch; + final PsiCodeBlock codeBlock = blockStatement.getCodeBlock(); + final PsiStatement[] statements = codeBlock.getStatements(); + return statements.length == 1 && isCloseStatement(statements[0], variables); + } + else { + return false; + } + } + else { + return false; + } } - } - else { - return false; - } } - } - - @Override - public BaseInspectionVisitor buildVisitor() { - return new TryFinallyCanBeTryWithResourcesVisitor(); - } - - private static class TryFinallyCanBeTryWithResourcesVisitor extends BaseInspectionVisitor { @Override - public void visitTryStatement(PsiTryStatement tryStatement) { - super.visitTryStatement(tryStatement); - if (!PsiUtil.isLanguageLevel7OrHigher(tryStatement)) { - return; - } - final PsiResourceList resourceList = tryStatement.getResourceList(); - if (resourceList != null) { - return; - } - final PsiCodeBlock tryBlock = tryStatement.getTryBlock(); - if (tryBlock == null) { - return; - } - final List variables = collectVariables(tryStatement); - if (variables.isEmpty()) { - return; - } - final PsiStatement[] tryBlockStatements = tryBlock.getStatements(); - boolean found = false; - for (PsiVariable variable : variables) { - final boolean hasInitializer; - final PsiExpression initializer = variable.getInitializer(); - if (initializer == null) { - hasInitializer = false; - } - else { - final PsiType type = initializer.getType(); - hasInitializer = !PsiType.NULL.equals(type); - } - final int index = findInitialization(tryBlockStatements, variable, hasInitializer); - if (index >= 0 ^ hasInitializer) { - if (isVariableUsedOutsideContext(variable, tryBlock)) { - continue; - } - found = true; - break; - } - } - if (!found) { - return; - } - registerStatementError(tryStatement); + public BaseInspectionVisitor buildVisitor() { + return new TryFinallyCanBeTryWithResourcesVisitor(); } - } - static boolean isVariableUsedOutsideContext(PsiVariable variable, PsiElement context) { - final VariableUsedOutsideContextVisitor visitor = new VariableUsedOutsideContextVisitor(variable, context); - final PsiElement declarationScope = PsiTreeUtil.getParentOfType(variable, PsiCodeBlock.class); - if (declarationScope == null) { - return true; + private static class TryFinallyCanBeTryWithResourcesVisitor extends BaseInspectionVisitor { + @Override + public void visitTryStatement(PsiTryStatement tryStatement) { + super.visitTryStatement(tryStatement); + if (!PsiUtil.isLanguageLevel7OrHigher(tryStatement)) { + return; + } + final PsiResourceList resourceList = tryStatement.getResourceList(); + if (resourceList != null) { + return; + } + final PsiCodeBlock tryBlock = tryStatement.getTryBlock(); + if (tryBlock == null) { + return; + } + final List variables = collectVariables(tryStatement); + if (variables.isEmpty()) { + return; + } + final PsiStatement[] tryBlockStatements = tryBlock.getStatements(); + boolean found = false; + for (PsiVariable variable : variables) { + final boolean hasInitializer; + final PsiExpression initializer = variable.getInitializer(); + if (initializer == null) { + hasInitializer = false; + } + else { + final PsiType type = initializer.getType(); + hasInitializer = !PsiType.NULL.equals(type); + } + final int index = findInitialization(tryBlockStatements, variable, hasInitializer); + if (index >= 0 ^ hasInitializer) { + if (isVariableUsedOutsideContext(variable, tryBlock)) { + continue; + } + found = true; + break; + } + } + if (!found) { + return; + } + registerStatementError(tryStatement); + } } - declarationScope.accept(visitor); - return visitor.variableIsUsed(); - } - static List collectVariables(PsiTryStatement tryStatement) { - final PsiCodeBlock finallyBlock = tryStatement.getFinallyBlock(); - if (finallyBlock == null) { - return Collections.EMPTY_LIST; - } - final PsiStatement[] statements = finallyBlock.getStatements(); - if (statements.length == 0) { - return Collections.EMPTY_LIST; - } - final List variables = new ArrayList(); - for (PsiStatement statement : statements) { - final PsiLocalVariable variable = findAutoCloseableVariable(statement); - if (variable != null) { - variables.add(variable); - } + static boolean isVariableUsedOutsideContext(PsiVariable variable, PsiElement context) { + final VariableUsedOutsideContextVisitor visitor = new VariableUsedOutsideContextVisitor(variable, context); + final PsiElement declarationScope = PsiTreeUtil.getParentOfType(variable, PsiCodeBlock.class); + if (declarationScope == null) { + return true; + } + declarationScope.accept(visitor); + return visitor.variableIsUsed(); } - return variables; - } - @Nullable - static PsiLocalVariable findAutoCloseableVariable(PsiStatement statement) { - if (statement instanceof PsiIfStatement) { - final PsiIfStatement ifStatement = (PsiIfStatement)statement; - if (ifStatement.getElseBranch() != null) { - return null; - } - final PsiExpression condition = ifStatement.getCondition(); - if (!(condition instanceof PsiBinaryExpression)) { - return null; - } - final PsiBinaryExpression binaryExpression = (PsiBinaryExpression)condition; - final IElementType tokenType = binaryExpression.getOperationTokenType(); - if (!JavaTokenType.NE.equals(tokenType)) { - return null; - } - final PsiExpression lhs = binaryExpression.getLOperand(); - final PsiExpression rhs = binaryExpression.getROperand(); - if (rhs == null) { - return null; - } - final PsiElement variable; - if (PsiType.NULL.equals(rhs.getType())) { - if (!(lhs instanceof PsiReferenceExpression)) { - return null; - } - final PsiReferenceExpression referenceExpression = (PsiReferenceExpression)lhs; - variable = referenceExpression.resolve(); - if (!(variable instanceof PsiLocalVariable)) { - return null; - } - } - else if (PsiType.NULL.equals(lhs.getType())) { - if (!(rhs instanceof PsiReferenceExpression)) { - return null; + static List collectVariables(PsiTryStatement tryStatement) { + final PsiCodeBlock finallyBlock = tryStatement.getFinallyBlock(); + if (finallyBlock == null) { + return Collections.EMPTY_LIST; + } + final PsiStatement[] statements = finallyBlock.getStatements(); + if (statements.length == 0) { + return Collections.EMPTY_LIST; + } + final List variables = new ArrayList(); + for (PsiStatement statement : statements) { + final PsiLocalVariable variable = findAutoCloseableVariable(statement); + if (variable != null) { + variables.add(variable); + } } - final PsiReferenceExpression referenceExpression = (PsiReferenceExpression)rhs; - variable = referenceExpression.resolve(); - if (!(variable instanceof PsiLocalVariable)) { - return null; + return variables; + } + + @Nullable + static PsiLocalVariable findAutoCloseableVariable(PsiStatement statement) { + if (statement instanceof PsiIfStatement) { + final PsiIfStatement ifStatement = (PsiIfStatement) statement; + if (ifStatement.getElseBranch() != null) { + return null; + } + final PsiExpression condition = ifStatement.getCondition(); + if (!(condition instanceof PsiBinaryExpression)) { + return null; + } + final PsiBinaryExpression binaryExpression = (PsiBinaryExpression) condition; + final IElementType tokenType = binaryExpression.getOperationTokenType(); + if (!JavaTokenType.NE.equals(tokenType)) { + return null; + } + final PsiExpression lhs = binaryExpression.getLOperand(); + final PsiExpression rhs = binaryExpression.getROperand(); + if (rhs == null) { + return null; + } + final PsiElement variable; + if (PsiType.NULL.equals(rhs.getType())) { + if (!(lhs instanceof PsiReferenceExpression)) { + return null; + } + final PsiReferenceExpression referenceExpression = (PsiReferenceExpression) lhs; + variable = referenceExpression.resolve(); + if (!(variable instanceof PsiLocalVariable)) { + return null; + } + } + else if (PsiType.NULL.equals(lhs.getType())) { + if (!(rhs instanceof PsiReferenceExpression)) { + return null; + } + final PsiReferenceExpression referenceExpression = (PsiReferenceExpression) rhs; + variable = referenceExpression.resolve(); + if (!(variable instanceof PsiLocalVariable)) { + return null; + } + } + else { + return null; + } + final PsiStatement thenBranch = ifStatement.getThenBranch(); + final PsiLocalVariable resourceVariable; + if (thenBranch instanceof PsiExpressionStatement) { + resourceVariable = findAutoCloseableVariable(thenBranch); + } + else if (thenBranch instanceof PsiBlockStatement) { + final PsiBlockStatement blockStatement = (PsiBlockStatement) thenBranch; + final PsiCodeBlock codeBlock = blockStatement.getCodeBlock(); + final PsiStatement[] statements = codeBlock.getStatements(); + if (statements.length != 1) { + return null; + } + resourceVariable = findAutoCloseableVariable(statements[0]); + } + else { + return null; + } + if (variable.equals(resourceVariable)) { + return resourceVariable; + } } - } - else { - return null; - } - final PsiStatement thenBranch = ifStatement.getThenBranch(); - final PsiLocalVariable resourceVariable; - if (thenBranch instanceof PsiExpressionStatement) { - resourceVariable = findAutoCloseableVariable(thenBranch); - } - else if (thenBranch instanceof PsiBlockStatement) { - final PsiBlockStatement blockStatement = (PsiBlockStatement)thenBranch; - final PsiCodeBlock codeBlock = blockStatement.getCodeBlock(); - final PsiStatement[] statements = codeBlock.getStatements(); - if (statements.length != 1) { - return null; + else if (statement instanceof PsiExpressionStatement) { + final PsiExpressionStatement expressionStatement = (PsiExpressionStatement) statement; + final PsiExpression expression = expressionStatement.getExpression(); + if (!(expression instanceof PsiMethodCallExpression)) { + return null; + } + final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression) expression; + final PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression(); + final String methodName = methodExpression.getReferenceName(); + if (!HardcodedMethodConstants.CLOSE.equals(methodName)) { + return null; + } + final PsiExpression qualifier = methodExpression.getQualifierExpression(); + if (!(qualifier instanceof PsiReferenceExpression)) { + return null; + } + final PsiReferenceExpression referenceExpression = (PsiReferenceExpression) qualifier; + final PsiElement target = referenceExpression.resolve(); + if (!(target instanceof PsiLocalVariable) || target instanceof PsiResourceVariable) { + return null; + } + final PsiLocalVariable variable = (PsiLocalVariable) target; + if (!isAutoCloseable(variable)) { + return null; + } + return variable; } - resourceVariable = findAutoCloseableVariable(statements[0]); - } - else { return null; - } - if (variable.equals(resourceVariable)) { - return resourceVariable; - } } - else if (statement instanceof PsiExpressionStatement) { - final PsiExpressionStatement expressionStatement = (PsiExpressionStatement)statement; - final PsiExpression expression = expressionStatement.getExpression(); - if (!(expression instanceof PsiMethodCallExpression)) { - return null; - } - final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression)expression; - final PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression(); - final String methodName = methodExpression.getReferenceName(); - if (!HardcodedMethodConstants.CLOSE.equals(methodName)) { - return null; - } - final PsiExpression qualifier = methodExpression.getQualifierExpression(); - if (!(qualifier instanceof PsiReferenceExpression)) { - return null; - } - final PsiReferenceExpression referenceExpression = (PsiReferenceExpression)qualifier; - final PsiElement target = referenceExpression.resolve(); - if (!(target instanceof PsiLocalVariable) || target instanceof PsiResourceVariable) { - return null; - } - final PsiLocalVariable variable = (PsiLocalVariable)target; - if (!isAutoCloseable(variable)) { - return null; - } - return variable; - } - return null; - } - private static boolean isAutoCloseable(PsiVariable variable) { - final PsiType type = variable.getType(); - if (!(type instanceof PsiClassType)) { - return false; + private static boolean isAutoCloseable(PsiVariable variable) { + final PsiType type = variable.getType(); + if (!(type instanceof PsiClassType)) { + return false; + } + final PsiClassType classType = (PsiClassType) type; + final PsiClass aClass = classType.resolve(); + return aClass != null && InheritanceUtil.isInheritor(aClass, CommonClassNames.JAVA_LANG_AUTO_CLOSEABLE); } - final PsiClassType classType = (PsiClassType)type; - final PsiClass aClass = classType.resolve(); - return aClass != null && InheritanceUtil.isInheritor(aClass, CommonClassNames.JAVA_LANG_AUTO_CLOSEABLE); - } - static int findInitialization(PsiElement[] elements, PsiVariable variable, - boolean hasInitializer) { - int result = -1; - final int statementsLength = elements.length; - for (int i = 0; i < statementsLength; i++) { - final PsiElement element = elements[i]; - if (!(element instanceof PsiExpressionStatement)) { - continue; - } - final PsiExpressionStatement expressionStatement = (PsiExpressionStatement)element; - final PsiExpression expression = expressionStatement.getExpression(); - if (!(expression instanceof PsiAssignmentExpression)) { - continue; - } - final PsiAssignmentExpression assignmentExpression = (PsiAssignmentExpression)expression; - final PsiExpression lhs = assignmentExpression.getLExpression(); - if (!(lhs instanceof PsiReferenceExpression)) { - continue; - } - final PsiReferenceExpression referenceExpression = (PsiReferenceExpression)lhs; - final PsiElement target = referenceExpression.resolve(); - if (variable.equals(target)) { - if (result >= 0 && !hasInitializer) { - return -1; + static int findInitialization( + PsiElement[] elements, PsiVariable variable, + boolean hasInitializer + ) { + int result = -1; + final int statementsLength = elements.length; + for (int i = 0; i < statementsLength; i++) { + final PsiElement element = elements[i]; + if (!(element instanceof PsiExpressionStatement)) { + continue; + } + final PsiExpressionStatement expressionStatement = (PsiExpressionStatement) element; + final PsiExpression expression = expressionStatement.getExpression(); + if (!(expression instanceof PsiAssignmentExpression)) { + continue; + } + final PsiAssignmentExpression assignmentExpression = (PsiAssignmentExpression) expression; + final PsiExpression lhs = assignmentExpression.getLExpression(); + if (!(lhs instanceof PsiReferenceExpression)) { + continue; + } + final PsiReferenceExpression referenceExpression = (PsiReferenceExpression) lhs; + final PsiElement target = referenceExpression.resolve(); + if (variable.equals(target)) { + if (result >= 0 && !hasInitializer) { + return -1; + } + result = i; + } } - result = i; - } + return result; } - return result; - } - static class VariableUsedOutsideContextVisitor extends JavaRecursiveElementVisitor { + static class VariableUsedOutsideContextVisitor extends JavaRecursiveElementVisitor { - private boolean used = false; - @Nonnull - private final PsiVariable variable; - private final PsiElement skipContext; + private boolean used = false; + @Nonnull + private final PsiVariable variable; + private final PsiElement skipContext; - public VariableUsedOutsideContextVisitor(@Nonnull PsiVariable variable, PsiElement skipContext) { - this.variable = variable; - this.skipContext = skipContext; - } + public VariableUsedOutsideContextVisitor(@Nonnull PsiVariable variable, PsiElement skipContext) { + this.variable = variable; + this.skipContext = skipContext; + } - @Override - public void visitElement(@Nonnull PsiElement element) { - if (element.equals(skipContext)) { - return; - } - if (used) { - return; - } - super.visitElement(element); - } + @Override + public void visitElement(@Nonnull PsiElement element) { + if (element.equals(skipContext)) { + return; + } + if (used) { + return; + } + super.visitElement(element); + } - @Override - public void visitReferenceExpression(@Nonnull PsiReferenceExpression referenceExpression) { - if (used) { - return; - } - super.visitReferenceExpression(referenceExpression); - final PsiElement target = referenceExpression.resolve(); - if (target == null) { - return; - } - if (target.equals(variable) && !isCloseMethodCalled(referenceExpression)) { - used = true; - } - } + @Override + public void visitReferenceExpression(@Nonnull PsiReferenceExpression referenceExpression) { + if (used) { + return; + } + super.visitReferenceExpression(referenceExpression); + final PsiElement target = referenceExpression.resolve(); + if (target == null) { + return; + } + if (target.equals(variable) && !isCloseMethodCalled(referenceExpression)) { + used = true; + } + } - private static boolean isCloseMethodCalled(PsiReferenceExpression referenceExpression) { - final PsiMethodCallExpression methodCallExpression = PsiTreeUtil.getParentOfType(referenceExpression, PsiMethodCallExpression.class); - if (methodCallExpression == null) { - return false; - } - final PsiExpressionList argumentList = methodCallExpression.getArgumentList(); - if (argumentList.getExpressions().length != 0) { - return false; - } - final PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression(); - final String name = methodExpression.getReferenceName(); - return HardcodedMethodConstants.CLOSE.equals(name); - } + private static boolean isCloseMethodCalled(PsiReferenceExpression referenceExpression) { + final PsiMethodCallExpression methodCallExpression = + PsiTreeUtil.getParentOfType(referenceExpression, PsiMethodCallExpression.class); + if (methodCallExpression == null) { + return false; + } + final PsiExpressionList argumentList = methodCallExpression.getArgumentList(); + if (argumentList.getExpressions().length != 0) { + return false; + } + final PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression(); + final String name = methodExpression.getReferenceName(); + return HardcodedMethodConstants.CLOSE.equals(name); + } - public boolean variableIsUsed() { - return used; + public boolean variableIsUsed() { + return used; + } } - } } diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/migration/UnnecessaryBoxingInspection.java b/plugin/src/main/java/com/intellij/java/impl/ig/migration/UnnecessaryBoxingInspection.java index 384cf11018..c11e4f51e0 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/migration/UnnecessaryBoxingInspection.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/migration/UnnecessaryBoxingInspection.java @@ -41,350 +41,292 @@ import javax.swing.*; @ExtensionImpl -public class UnnecessaryBoxingInspection extends BaseInspection -{ +public class UnnecessaryBoxingInspection extends BaseInspection { + @SuppressWarnings("PublicField") + public boolean onlyReportSuperfluouslyBoxed = false; - @SuppressWarnings("PublicField") - public boolean onlyReportSuperfluouslyBoxed = false; + @Nonnull + @Override + public LocalizeValue getDisplayName() { + return InspectionGadgetsLocalize.unnecessaryBoxingDisplayName(); + } - @Override - @Nonnull - public String getDisplayName() - { - return InspectionGadgetsLocalize.unnecessaryBoxingDisplayName().get(); - } + @Override + public boolean isEnabledByDefault() { + return true; + } - @Override - public boolean isEnabledByDefault() - { - return true; - } + @Nullable + @Override + public JComponent createOptionsPanel() { + LocalizeValue message = InspectionGadgetsLocalize.unnecessaryBoxingSuperfluousOption(); + return new SingleCheckboxOptionsPanel(message.get(), this, "onlyReportSuperfluouslyBoxed"); + } - @Nullable - @Override - public JComponent createOptionsPanel() - { - LocalizeValue message = InspectionGadgetsLocalize.unnecessaryBoxingSuperfluousOption(); - return new SingleCheckboxOptionsPanel(message.get(), this, "onlyReportSuperfluouslyBoxed"); - } + @Override + @Nonnull + protected String buildErrorString(Object... infos) { + return InspectionGadgetsLocalize.unnecessaryBoxingProblemDescriptor().get(); + } - @Override - @Nonnull - protected String buildErrorString(Object... infos) - { - return InspectionGadgetsLocalize.unnecessaryBoxingProblemDescriptor().get(); - } + @Override + public InspectionGadgetsFix buildFix(Object... infos) { + return new UnnecessaryBoxingFix(); + } - @Override - public InspectionGadgetsFix buildFix(Object... infos) - { - return new UnnecessaryBoxingFix(); - } + private static class UnnecessaryBoxingFix extends InspectionGadgetsFix { + @Nonnull + @Override + public LocalizeValue getName() { + return InspectionGadgetsLocalize.unnecessaryBoxingRemoveQuickfix(); + } - private static class UnnecessaryBoxingFix extends InspectionGadgetsFix - { + @Override + public void doFix(@Nonnull Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { + final PsiCallExpression expression = (PsiCallExpression) descriptor.getPsiElement(); + final PsiExpressionList argumentList = expression.getArgumentList(); + if (argumentList == null) { + return; + } + final PsiExpression[] arguments = argumentList.getExpressions(); + if (arguments.length != 1) { + return; + } + final PsiExpression unboxedExpression = arguments[0]; + final Object value = ExpressionUtils.computeConstantExpression(unboxedExpression); + if (value != null) { + if (value == Boolean.TRUE) { + PsiReplacementUtil.replaceExpression(expression, "java.lang.Boolean.TRUE"); + return; + } + else if (value == Boolean.FALSE) { + PsiReplacementUtil.replaceExpression(expression, "java.lang.Boolean.FALSE"); + return; + } + } + final String replacementText = getUnboxedExpressionText(unboxedExpression, expression); + if (replacementText == null) { + return; + } + PsiReplacementUtil.replaceExpression(expression, replacementText); + } - @Override - @Nonnull - public String getFamilyName() - { - return InspectionGadgetsLocalize.unnecessaryBoxingRemoveQuickfix().get(); - } + @Nullable + private static String getUnboxedExpressionText(@Nonnull PsiExpression unboxedExpression, @Nonnull PsiExpression boxedExpression) { + final PsiType boxedType = boxedExpression.getType(); + if (boxedType == null) { + return null; + } + final PsiType expressionType = unboxedExpression.getType(); + if (expressionType == null) { + return null; + } + final PsiType unboxedType = PsiPrimitiveType.getUnboxedType(boxedType); + if (unboxedType == null) { + return null; + } + final String text = unboxedExpression.getText(); + if (expressionType.equals(unboxedType)) { + final PsiElement parent = boxedExpression.getParent(); + if (parent instanceof PsiExpression && ParenthesesUtils.areParenthesesNeeded( + unboxedExpression, + (PsiExpression) parent, + false + )) { + return '(' + text + ')'; + } + else { + return text; + } + } + if (unboxedExpression instanceof PsiLiteralExpression) { + if (unboxedType.equals(PsiType.LONG) && expressionType.equals(PsiType.INT)) { + return text + 'L'; + } + else if (unboxedType.equals(PsiType.FLOAT) && (expressionType.equals(PsiType.INT) || (expressionType.equals(PsiType.DOUBLE)) && !StringUtil.endsWithIgnoreCase( + text, + "d" + ))) { + return text + 'f'; + } + else if (unboxedType.equals(PsiType.DOUBLE) && expressionType.equals(PsiType.INT)) { + return text + 'd'; + } + } + if (ParenthesesUtils.getPrecedence(unboxedExpression) > ParenthesesUtils.TYPE_CAST_PRECEDENCE) { + return '(' + unboxedType.getCanonicalText() + ")(" + text + ')'; + } + else { + return '(' + unboxedType.getCanonicalText() + ')' + text; + } + } + } - @Override - public void doFix(@Nonnull Project project, ProblemDescriptor descriptor) throws IncorrectOperationException - { - final PsiCallExpression expression = (PsiCallExpression) descriptor.getPsiElement(); - final PsiExpressionList argumentList = expression.getArgumentList(); - if(argumentList == null) - { - return; - } - final PsiExpression[] arguments = argumentList.getExpressions(); - if(arguments.length != 1) - { - return; - } - final PsiExpression unboxedExpression = arguments[0]; - final Object value = ExpressionUtils.computeConstantExpression(unboxedExpression); - if(value != null) - { - if(value == Boolean.TRUE) - { - PsiReplacementUtil.replaceExpression(expression, "java.lang.Boolean.TRUE"); - return; - } - else if(value == Boolean.FALSE) - { - PsiReplacementUtil.replaceExpression(expression, "java.lang.Boolean.FALSE"); - return; - } - } - final String replacementText = getUnboxedExpressionText(unboxedExpression, expression); - if(replacementText == null) - { - return; - } - PsiReplacementUtil.replaceExpression(expression, replacementText); - } + @Override + public boolean shouldInspect(PsiFile file) { + return PsiUtil.isLanguageLevel5OrHigher(file); + } - @Nullable - private static String getUnboxedExpressionText(@Nonnull PsiExpression unboxedExpression, @Nonnull PsiExpression boxedExpression) - { - final PsiType boxedType = boxedExpression.getType(); - if(boxedType == null) - { - return null; - } - final PsiType expressionType = unboxedExpression.getType(); - if(expressionType == null) - { - return null; - } - final PsiType unboxedType = PsiPrimitiveType.getUnboxedType(boxedType); - if(unboxedType == null) - { - return null; - } - final String text = unboxedExpression.getText(); - if(expressionType.equals(unboxedType)) - { - final PsiElement parent = boxedExpression.getParent(); - if(parent instanceof PsiExpression && ParenthesesUtils.areParenthesesNeeded(unboxedExpression, (PsiExpression) parent, false)) - { - return '(' + text + ')'; - } - else - { - return text; - } - } - if(unboxedExpression instanceof PsiLiteralExpression) - { - if(unboxedType.equals(PsiType.LONG) && expressionType.equals(PsiType.INT)) - { - return text + 'L'; - } - else if(unboxedType.equals(PsiType.FLOAT) && (expressionType.equals(PsiType.INT) || (expressionType.equals(PsiType.DOUBLE)) && !StringUtil.endsWithIgnoreCase(text, "d"))) - { - return text + 'f'; - } - else if(unboxedType.equals(PsiType.DOUBLE) && expressionType.equals(PsiType.INT)) - { - return text + 'd'; - } - } - if(ParenthesesUtils.getPrecedence(unboxedExpression) > ParenthesesUtils.TYPE_CAST_PRECEDENCE) - { - return '(' + unboxedType.getCanonicalText() + ")(" + text + ')'; - } - else - { - return '(' + unboxedType.getCanonicalText() + ')' + text; - } - } - } + @Override + public BaseInspectionVisitor buildVisitor() { + return new UnnecessaryBoxingVisitor(); + } - @Override - public boolean shouldInspect(PsiFile file) - { - return PsiUtil.isLanguageLevel5OrHigher(file); - } + private class UnnecessaryBoxingVisitor extends BaseInspectionVisitor { - @Override - public BaseInspectionVisitor buildVisitor() - { - return new UnnecessaryBoxingVisitor(); - } + @Override + public void visitNewExpression(@Nonnull PsiNewExpression expression) { + super.visitNewExpression(expression); + final PsiExpressionList argumentList = expression.getArgumentList(); + if (argumentList == null) { + return; + } + final PsiType constructorType = expression.getType(); + final PsiPrimitiveType unboxedType = PsiPrimitiveType.getUnboxedType(constructorType); + if (unboxedType == null) { + return; + } + final PsiMethod constructor = expression.resolveConstructor(); + if (constructor == null) { + return; + } + final PsiExpression[] arguments = argumentList.getExpressions(); + if (arguments.length != 1) { + return; + } + final PsiExpression boxedExpression = arguments[0]; + final PsiType argumentType = boxedExpression.getType(); + if (!(argumentType instanceof PsiPrimitiveType) || !canRemainUnboxed(expression, boxedExpression)) { + return; + } + if (onlyReportSuperfluouslyBoxed) { + final PsiType expectedType = ExpectedTypeUtils.findExpectedType(expression, false, true); + if (!(expectedType instanceof PsiPrimitiveType)) { + return; + } + } + registerError(expression); + } - private class UnnecessaryBoxingVisitor extends BaseInspectionVisitor - { + @Override + public void visitMethodCallExpression(PsiMethodCallExpression expression) { + super.visitMethodCallExpression(expression); + final PsiExpressionList argumentList = expression.getArgumentList(); + final PsiExpression[] arguments = argumentList.getExpressions(); + if (arguments.length != 1) { + return; + } + final PsiExpression boxedExpression = arguments[0]; + if (!(boxedExpression.getType() instanceof PsiPrimitiveType)) { + return; + } + final PsiReferenceExpression methodExpression = expression.getMethodExpression(); + @NonNls final String referenceName = methodExpression.getReferenceName(); + if (!"valueOf".equals(referenceName)) { + return; + } + final PsiExpression qualifierExpression = methodExpression.getQualifierExpression(); + if (!(qualifierExpression instanceof PsiReferenceExpression)) { + return; + } + final PsiReferenceExpression referenceExpression = (PsiReferenceExpression) qualifierExpression; + final String canonicalText = referenceExpression.getCanonicalText(); + if (PsiTypesUtil.unboxIfPossible(canonicalText) == canonicalText || !canRemainUnboxed(expression, boxedExpression)) { + return; + } + registerError(expression); + } - @Override - public void visitNewExpression(@Nonnull PsiNewExpression expression) - { - super.visitNewExpression(expression); - final PsiExpressionList argumentList = expression.getArgumentList(); - if(argumentList == null) - { - return; - } - final PsiType constructorType = expression.getType(); - final PsiPrimitiveType unboxedType = PsiPrimitiveType.getUnboxedType(constructorType); - if(unboxedType == null) - { - return; - } - final PsiMethod constructor = expression.resolveConstructor(); - if(constructor == null) - { - return; - } - final PsiExpression[] arguments = argumentList.getExpressions(); - if(arguments.length != 1) - { - return; - } - final PsiExpression boxedExpression = arguments[0]; - final PsiType argumentType = boxedExpression.getType(); - if(!(argumentType instanceof PsiPrimitiveType) || !canRemainUnboxed(expression, boxedExpression)) - { - return; - } - if(onlyReportSuperfluouslyBoxed) - { - final PsiType expectedType = ExpectedTypeUtils.findExpectedType(expression, false, true); - if(!(expectedType instanceof PsiPrimitiveType)) - { - return; - } - } - registerError(expression); - } + private boolean canRemainUnboxed(PsiExpression expression, PsiExpression boxedExpression) { + PsiElement parent = expression.getParent(); + while (parent instanceof PsiParenthesizedExpression) { + expression = (PsiExpression) parent; + parent = parent.getParent(); + } + if (parent instanceof PsiExpressionStatement || parent instanceof PsiReferenceExpression) { + return false; + } + else if (parent instanceof PsiTypeCastExpression) { + final PsiTypeCastExpression castExpression = (PsiTypeCastExpression) parent; + return !TypeUtils.isTypeParameter(castExpression.getType()); + } + else if (parent instanceof PsiConditionalExpression) { + final PsiConditionalExpression conditionalExpression = (PsiConditionalExpression) parent; + final PsiExpression thenExpression = conditionalExpression.getThenExpression(); + final PsiExpression elseExpression = conditionalExpression.getElseExpression(); + if (elseExpression == null || thenExpression == null) { + return false; + } + if (PsiTreeUtil.isAncestor(thenExpression, expression, false)) { + final PsiType type = elseExpression.getType(); + return type instanceof PsiPrimitiveType; + } + else if (PsiTreeUtil.isAncestor(elseExpression, expression, false)) { + final PsiType type = thenExpression.getType(); + return type instanceof PsiPrimitiveType; + } + else { + return true; + } + } + else if (parent instanceof PsiPolyadicExpression) { + final PsiPolyadicExpression polyadicExpression = (PsiPolyadicExpression) parent; + return !isPossibleObjectComparison(expression, polyadicExpression); + } + final PsiElement grandParent = parent.getParent(); + if (!(grandParent instanceof PsiCallExpression)) { // method call or new expression + return true; + } + final PsiCallExpression containingCallExpression = (PsiCallExpression) grandParent; + return isSameMethodCalledWithoutBoxing(containingCallExpression, expression, boxedExpression); + } - @Override - public void visitMethodCallExpression(PsiMethodCallExpression expression) - { - super.visitMethodCallExpression(expression); - final PsiExpressionList argumentList = expression.getArgumentList(); - final PsiExpression[] arguments = argumentList.getExpressions(); - if(arguments.length != 1) - { - return; - } - final PsiExpression boxedExpression = arguments[0]; - if(!(boxedExpression.getType() instanceof PsiPrimitiveType)) - { - return; - } - final PsiReferenceExpression methodExpression = expression.getMethodExpression(); - @NonNls - final String referenceName = methodExpression.getReferenceName(); - if(!"valueOf".equals(referenceName)) - { - return; - } - final PsiExpression qualifierExpression = methodExpression.getQualifierExpression(); - if(!(qualifierExpression instanceof PsiReferenceExpression)) - { - return; - } - final PsiReferenceExpression referenceExpression = (PsiReferenceExpression) qualifierExpression; - final String canonicalText = referenceExpression.getCanonicalText(); - if(PsiTypesUtil.unboxIfPossible(canonicalText) == canonicalText || !canRemainUnboxed(expression, boxedExpression)) - { - return; - } - registerError(expression); - } + private boolean isPossibleObjectComparison(PsiExpression expression, PsiPolyadicExpression polyadicExpression) { + if (!ComparisonUtils.isEqualityComparison(polyadicExpression)) { + return false; + } + for (PsiExpression operand : polyadicExpression.getOperands()) { + if (operand == expression) { + continue; + } + if (!(operand.getType() instanceof PsiPrimitiveType)) { + return true; + } + //else if (isUnboxingExpression(operand)) { + // return true; + //} + } + return false; + } - private boolean canRemainUnboxed(PsiExpression expression, PsiExpression boxedExpression) - { - PsiElement parent = expression.getParent(); - while(parent instanceof PsiParenthesizedExpression) - { - expression = (PsiExpression) parent; - parent = parent.getParent(); - } - if(parent instanceof PsiExpressionStatement || parent instanceof PsiReferenceExpression) - { - return false; - } - else if(parent instanceof PsiTypeCastExpression) - { - final PsiTypeCastExpression castExpression = (PsiTypeCastExpression) parent; - return !TypeUtils.isTypeParameter(castExpression.getType()); - } - else if(parent instanceof PsiConditionalExpression) - { - final PsiConditionalExpression conditionalExpression = (PsiConditionalExpression) parent; - final PsiExpression thenExpression = conditionalExpression.getThenExpression(); - final PsiExpression elseExpression = conditionalExpression.getElseExpression(); - if(elseExpression == null || thenExpression == null) - { - return false; - } - if(PsiTreeUtil.isAncestor(thenExpression, expression, false)) - { - final PsiType type = elseExpression.getType(); - return type instanceof PsiPrimitiveType; - } - else if(PsiTreeUtil.isAncestor(elseExpression, expression, false)) - { - final PsiType type = thenExpression.getType(); - return type instanceof PsiPrimitiveType; - } - else - { - return true; - } - } - else if(parent instanceof PsiPolyadicExpression) - { - final PsiPolyadicExpression polyadicExpression = (PsiPolyadicExpression) parent; - return !isPossibleObjectComparison(expression, polyadicExpression); - } - final PsiElement grandParent = parent.getParent(); - if(!(grandParent instanceof PsiCallExpression)) - { // method call or new expression - return true; - } - final PsiCallExpression containingCallExpression = (PsiCallExpression) grandParent; - return isSameMethodCalledWithoutBoxing(containingCallExpression, expression, boxedExpression); - } + private boolean canBinaryExpressionBeUnboxed(PsiExpression lhs, PsiExpression rhs) { + final PsiType rhsType = rhs.getType(); + if (rhsType == null) { + return false; + } + final PsiType lhsType = lhs.getType(); + if (lhsType == null) { + return false; + } + if (!(lhsType instanceof PsiPrimitiveType) && !ExpressionUtils.isAnnotatedNotNull(lhs)) { + return false; + } + final PsiPrimitiveType unboxedType = PsiPrimitiveType.getUnboxedType(rhsType); + return unboxedType != null && unboxedType.isAssignableFrom(lhsType); + } - private boolean isPossibleObjectComparison(PsiExpression expression, PsiPolyadicExpression polyadicExpression) - { - if(!ComparisonUtils.isEqualityComparison(polyadicExpression)) - { - return false; - } - for(PsiExpression operand : polyadicExpression.getOperands()) - { - if(operand == expression) - { - continue; - } - if(!(operand.getType() instanceof PsiPrimitiveType)) - { - return true; - } - //else if (isUnboxingExpression(operand)) { - // return true; - //} - } - return false; - } - - private boolean canBinaryExpressionBeUnboxed(PsiExpression lhs, PsiExpression rhs) - { - final PsiType rhsType = rhs.getType(); - if(rhsType == null) - { - return false; - } - final PsiType lhsType = lhs.getType(); - if(lhsType == null) - { - return false; - } - if(!(lhsType instanceof PsiPrimitiveType) && !ExpressionUtils.isAnnotatedNotNull(lhs)) - { - return false; - } - final PsiPrimitiveType unboxedType = PsiPrimitiveType.getUnboxedType(rhsType); - return unboxedType != null && unboxedType.isAssignableFrom(lhsType); - } - - private boolean isSameMethodCalledWithoutBoxing(@Nonnull PsiCallExpression methodCallExpression, @Nonnull PsiExpression boxingExpression, @Nonnull PsiExpression boxedExpression) - { - final PsiMethod originalMethod = methodCallExpression.resolveMethod(); - if(originalMethod == null) - { - return false; - } - final PsiMethod otherMethod = MethodCallUtils.findMethodWithReplacedArgument(methodCallExpression, boxingExpression, boxedExpression); - return originalMethod == otherMethod; - } - } + private boolean isSameMethodCalledWithoutBoxing( + @Nonnull PsiCallExpression methodCallExpression, + @Nonnull PsiExpression boxingExpression, + @Nonnull PsiExpression boxedExpression + ) { + final PsiMethod originalMethod = methodCallExpression.resolveMethod(); + if (originalMethod == null) { + return false; + } + final PsiMethod otherMethod = + MethodCallUtils.findMethodWithReplacedArgument(methodCallExpression, boxingExpression, boxedExpression); + return originalMethod == otherMethod; + } + } } \ No newline at end of file