From 632e8c3c6840bd6d15df4f872f26111c3a60ca04 Mon Sep 17 00:00:00 2001 From: UNV Date: Tue, 6 May 2025 19:05:31 +0300 Subject: [PATCH 1/3] Reformatting ClsRepositoryPsiElement. --- .../compiled/ClsRepositoryPsiElement.java | 168 +++++++++--------- 1 file changed, 87 insertions(+), 81 deletions(-) diff --git a/java-language-impl/src/main/java/com/intellij/java/language/impl/psi/impl/compiled/ClsRepositoryPsiElement.java b/java-language-impl/src/main/java/com/intellij/java/language/impl/psi/impl/compiled/ClsRepositoryPsiElement.java index 9d398a6fb7..5519e51467 100644 --- a/java-language-impl/src/main/java/com/intellij/java/language/impl/psi/impl/compiled/ClsRepositoryPsiElement.java +++ b/java-language-impl/src/main/java/com/intellij/java/language/impl/psi/impl/compiled/ClsRepositoryPsiElement.java @@ -25,91 +25,97 @@ import java.util.List; public abstract class ClsRepositoryPsiElement extends ClsElementImpl implements StubBasedPsiElement { - private final T myStub; - - protected ClsRepositoryPsiElement(final T stub) { - myStub = stub; - } - - @Override - public IStubElementType getElementType() { - return myStub.getStubType(); - } - - @Override - public PsiElement getParent() { - return myStub.getParentStub().getPsi(); - } - - @Override - public PsiManager getManager() { - final PsiFile file = getContainingFile(); - if (file == null) throw new PsiInvalidElementAccessException(this); - return file.getManager(); - } - - @Override - public PsiFile getContainingFile() { - StubElement p = myStub; - while (!(p instanceof PsiFileStub)) { - p = p.getParentStub(); + private final T myStub; + + protected ClsRepositoryPsiElement(final T stub) { + myStub = stub; + } + + @Override + public IStubElementType getElementType() { + return myStub.getStubType(); + } + + @Override + public PsiElement getParent() { + return myStub.getParentStub().getPsi(); } - return (PsiFile)p.getPsi(); - } - - @Override - public T getStub() { - return myStub; - } - - @Override - public boolean isPhysical() { - return getContainingFile().isPhysical(); - } - - @Override - @Nonnull - public PsiElement[] getChildren() { - final List stubs = getStub().getChildrenStubs(); - PsiElement[] children = new PsiElement[stubs.size()]; - for (int i = 0; i < stubs.size(); i++) { - children[i] = ((StubElement)stubs.get(i)).getPsi(); + + @Override + public PsiManager getManager() { + final PsiFile file = getContainingFile(); + if (file == null) { + throw new PsiInvalidElementAccessException(this); + } + return file.getManager(); + } + + @Override + public PsiFile getContainingFile() { + StubElement p = myStub; + while (!(p instanceof PsiFileStub)) { + p = p.getParentStub(); + } + return (PsiFile)p.getPsi(); + } + + @Override + public T getStub() { + return myStub; } - return children; - } - - @Override - public PsiElement getFirstChild() { - final List children = getStub().getChildrenStubs(); - if (children.isEmpty()) return null; - return children.get(0).getPsi(); - } - - @Override - public PsiElement getLastChild() { - final List children = getStub().getChildrenStubs(); - if (children.isEmpty()) return null; - return children.get(children.size() - 1).getPsi(); - } - - @Override - public PsiElement getNextSibling() { - final PsiElement[] psiElements = getParent().getChildren(); - final int i = ArrayUtil.indexOf(psiElements, this); - if (i < 0 || i >= psiElements.length - 1) { - return null; + + @Override + public boolean isPhysical() { + return getContainingFile().isPhysical(); + } + + @Override + @Nonnull + public PsiElement[] getChildren() { + final List stubs = getStub().getChildrenStubs(); + PsiElement[] children = new PsiElement[stubs.size()]; + for (int i = 0; i < stubs.size(); i++) { + children[i] = ((StubElement)stubs.get(i)).getPsi(); + } + return children; + } + + @Override + public PsiElement getFirstChild() { + final List children = getStub().getChildrenStubs(); + if (children.isEmpty()) { + return null; + } + return children.get(0).getPsi(); + } + + @Override + public PsiElement getLastChild() { + final List children = getStub().getChildrenStubs(); + if (children.isEmpty()) { + return null; + } + return children.get(children.size() - 1).getPsi(); + } + + @Override + public PsiElement getNextSibling() { + final PsiElement[] psiElements = getParent().getChildren(); + final int i = ArrayUtil.indexOf(psiElements, this); + if (i < 0 || i >= psiElements.length - 1) { + return null; + } + return psiElements[i + 1]; } - return psiElements[i + 1]; - } - @Override - public PsiElement getPrevSibling() { - final PsiElement[] psiElements = getParent().getChildren(); - final int i = ArrayUtil.indexOf(psiElements, this); - if (i < 1) { - return null; + @Override + public PsiElement getPrevSibling() { + final PsiElement[] psiElements = getParent().getChildren(); + final int i = ArrayUtil.indexOf(psiElements, this); + if (i < 1) { + return null; + } + return psiElements[i - 1]; } - return psiElements[i - 1]; - } } From a563c611b204a7af97fc901a10e8c74f932565dc Mon Sep 17 00:00:00 2001 From: UNV Date: Tue, 6 May 2025 19:37:05 +0300 Subject: [PATCH 2/3] Refactoring and localizing users of EP_NAME (part 13). --- .../impl/settings/NodeRendererSettings.java | 152 ++++---- .../impl/JavaTestFrameworkRunnableState.java | 95 ++--- .../impl/RunConfigurationExtension.java | 18 +- .../BaseJavaApplicationCommandLineState.java | 2 +- .../search/CustomPropertyScopeProvider.java | 2 +- .../runner/JavaMainMethodProvider.java | 6 +- .../psi/augment/PsiAugmentProvider.java | 103 +++--- .../java/language/psi/util/PsiMethodUtil.java | 40 +- .../impl/codeInsight/ExceptionUtil.java | 341 +++++++++--------- .../impl/psi/impl/compiled/ClsClassImpl.java | 77 ++-- .../impl/psi/impl/compiled/ClsFieldImpl.java | 20 +- .../impl/psi/impl/compiled/ClsFileImpl.java | 60 +-- .../impl/psi/impl/compiled/ClsMethodImpl.java | 30 +- .../compiled/ClsRepositoryPsiElement.java | 28 +- .../SmartTypePointerManagerImpl.java | 60 ++- .../impl/source/PsiClassReferenceType.java | 66 ++-- .../graphInference/InferenceVariable.java | 36 +- .../properties/impl/i18n/I18nizeAction.java | 44 +-- .../impl/i18n/I18nizeHandlerProvider.java | 2 +- 19 files changed, 583 insertions(+), 599 deletions(-) diff --git a/java-debugger-impl/src/main/java/com/intellij/java/debugger/impl/settings/NodeRendererSettings.java b/java-debugger-impl/src/main/java/com/intellij/java/debugger/impl/settings/NodeRendererSettings.java index 5800f11fdb..bd4e57964f 100644 --- a/java-debugger-impl/src/main/java/com/intellij/java/debugger/impl/settings/NodeRendererSettings.java +++ b/java-debugger-impl/src/main/java/com/intellij/java/debugger/impl/settings/NodeRendererSettings.java @@ -15,7 +15,6 @@ */ package com.intellij.java.debugger.impl.settings; -import com.intellij.java.debugger.DebuggerBundle; import com.intellij.java.debugger.DebuggerContext; import com.intellij.java.debugger.engine.DebugProcess; import com.intellij.java.debugger.engine.evaluation.CodeFragmentKind; @@ -32,11 +31,11 @@ import com.intellij.java.debugger.impl.ui.tree.DebuggerTreeNode; import com.intellij.java.debugger.impl.ui.tree.ValueDescriptor; import com.intellij.java.debugger.impl.ui.tree.render.*; +import com.intellij.java.debugger.localize.JavaDebuggerLocalize; import com.intellij.java.language.impl.JavaFileType; import consulo.annotation.component.ComponentScope; import consulo.annotation.component.ServiceAPI; import consulo.annotation.component.ServiceImpl; -import consulo.application.util.function.Computable; import consulo.component.persist.PersistentStateComponent; import consulo.component.persist.State; import consulo.component.persist.Storage; @@ -46,6 +45,7 @@ import consulo.java.language.module.util.JavaClassNames; import consulo.language.psi.PsiElement; import consulo.language.util.IncorrectOperationException; +import consulo.localize.LocalizeValue; import consulo.project.Project; import consulo.proxy.EventDispatcher; import consulo.ui.image.Image; @@ -55,26 +55,22 @@ import consulo.util.xml.serializer.JDOMExternalizerUtil; import consulo.util.xml.serializer.WriteExternalException; import jakarta.annotation.Nonnull; +import jakarta.annotation.Nullable; import jakarta.inject.Singleton; import org.jdom.Element; -import org.jetbrains.annotations.NonNls; - -import jakarta.annotation.Nullable; import java.util.ArrayList; import java.util.Collections; import java.util.List; +import java.util.function.Supplier; @Singleton @State(name = "NodeRendererSettings", storages = @Storage("debugger.renderers.xml")) @ServiceAPI(ComponentScope.APPLICATION) @ServiceImpl public class NodeRendererSettings implements PersistentStateComponent { - @NonNls private static final String REFERENCE_RENDERER = "Reference renderer"; - @NonNls public static final String RENDERER_TAG = "Renderer"; - @NonNls private static final String RENDERER_ID = "ID"; private final EventDispatcher myDispatcher = EventDispatcher.create(NodeRendererSettingsListener.class); @@ -120,11 +116,8 @@ public class NodeRendererSettings implements PersistentStateComponent { createExpressionChildrenRenderer("toArray()", "!isEmpty()") ) }; - @NonNls private static final String HEX_VIEW_ENABLED = "HEX_VIEW_ENABLED"; - @NonNls private static final String ALTERNATIVE_COLLECTION_VIEW_ENABLED = "ALTERNATIVE_COLLECTION_VIEW_ENABLED"; - @NonNls private static final String CUSTOM_RENDERERS_TAG_NAME = "CustomRenderers"; public NodeRendererSettings() { @@ -148,12 +141,12 @@ public boolean areAlternateCollectionViewsEnabled() { return myAlternateCollectionRenderers[0].isEnabled(); } + @Override public boolean equals(Object o) { - if (!(o instanceof NodeRendererSettings)) { - return false; - } + return o == this + || o instanceof NodeRendererSettings that + && DebuggerUtilsEx.elementsEqual(getState(), that.getState()); - return DebuggerUtilsEx.elementsEqual(getState(), ((NodeRendererSettings)o).getState()); } public void addListener(NodeRendererSettingsListener listener, Disposable disposable) { @@ -163,7 +156,7 @@ public void addListener(NodeRendererSettingsListener listener, Disposable dispos @Override @SuppressWarnings({"HardCodedStringLiteral"}) public Element getState() { - final Element element = new Element("NodeRendererSettings"); + Element element = new Element("NodeRendererSettings"); if (myHexRenderer.isEnabled()) { JDOMExternalizerUtil.writeField(element, HEX_VIEW_ENABLED, "true"); } @@ -177,7 +170,7 @@ public Element getState() { element.addContent(writeRenderer(myClassRenderer)); element.addContent(writeRenderer(myPrimitiveRenderer)); if (myCustomRenderers.getRendererCount() > 0) { - final Element custom = new Element(CUSTOM_RENDERERS_TAG_NAME); + Element custom = new Element(CUSTOM_RENDERERS_TAG_NAME); element.addContent(custom); myCustomRenderers.writeExternal(custom); } @@ -190,19 +183,19 @@ public Element getState() { @Override @SuppressWarnings({"HardCodedStringLiteral"}) - public void loadState(final Element root) { - final String hexEnabled = JDOMExternalizerUtil.readField(root, HEX_VIEW_ENABLED); + public void loadState(Element root) { + String hexEnabled = JDOMExternalizerUtil.readField(root, HEX_VIEW_ENABLED); if (hexEnabled != null) { myHexRenderer.setEnabled("true".equalsIgnoreCase(hexEnabled)); } - final String alternativeEnabled = JDOMExternalizerUtil.readField(root, ALTERNATIVE_COLLECTION_VIEW_ENABLED); + String alternativeEnabled = JDOMExternalizerUtil.readField(root, ALTERNATIVE_COLLECTION_VIEW_ENABLED); if (alternativeEnabled != null) { setAlternateCollectionViewsEnabled("true".equalsIgnoreCase(alternativeEnabled)); } - for (final Element elem : root.getChildren(RENDERER_TAG)) { - final String id = elem.getAttributeValue(RENDERER_ID); + for (Element elem : root.getChildren(RENDERER_TAG)) { + String id = elem.getAttributeValue(RENDERER_ID); if (id == null) { continue; } @@ -224,7 +217,7 @@ else if (PrimitiveRenderer.UNIQUE_ID.equals(id)) { // ignore } } - final Element custom = root.getChild(CUSTOM_RENDERERS_TAG_NAME); + Element custom = root.getChild(CUSTOM_RENDERERS_TAG_NAME); if (custom != null) { myCustomRenderers.readExternal(custom); } @@ -236,7 +229,7 @@ public RendererConfiguration getCustomRenderers() { return myCustomRenderers; } - public void setCustomRenderers(@Nonnull final RendererConfiguration customRenderers) { + public void setCustomRenderers(@Nonnull RendererConfiguration customRenderers) { RendererConfiguration oldConfig = myCustomRenderers; myCustomRenderers = customRenderers; if (oldConfig == null || !oldConfig.equals(customRenderers)) { @@ -274,11 +267,10 @@ public void fireRenderersChanged() { public List getAllRenderers() { // the order is important as the renderers are applied according to it - final List allRenderers = new ArrayList<>(); + List allRenderers = new ArrayList<>(); // user defined renderers must come first - myCustomRenderers.iterateRenderers(renderer -> - { + myCustomRenderers.iterateRenderers(renderer -> { allRenderers.add(renderer); return true; }); @@ -305,14 +297,14 @@ public Renderer readRenderer(Element root) throws InvalidDataException { throw new InvalidDataException("Cannot read renderer - tag name is not '" + RENDERER_TAG + "'"); } - final String rendererId = root.getAttributeValue(RENDERER_ID); + String rendererId = root.getAttributeValue(RENDERER_ID); if (rendererId == null) { - throw new InvalidDataException("unknown renderer ID: " + rendererId); + throw new InvalidDataException("unknown renderer ID: null"); } - final Renderer renderer = createRenderer(rendererId); + Renderer renderer = createRenderer(rendererId); if (renderer == null) { - throw new InvalidDataException("unknown renderer ID: " + rendererId); + throw new InvalidDataException("unknown renderer ID: null"); } renderer.readExternal(root); @@ -329,7 +321,7 @@ public Element writeRenderer(Renderer renderer) throws WriteExternalException { return root; } - public Renderer createRenderer(final String rendererId) { + public Renderer createRenderer(String rendererId) { if (ClassRenderer.UNIQUE_ID.equals(rendererId)) { return myClassRenderer; } @@ -364,10 +356,10 @@ else if (rendererId.equals(CompoundTypeRenderer.UNIQUE_ID)) { } public CompoundTypeRenderer createCompoundTypeRenderer( - @NonNls final String rendererName, - @NonNls final String className, - final ValueLabelRenderer labelRenderer, - final ChildrenRenderer childrenRenderer + String rendererName, + String className, + ValueLabelRenderer labelRenderer, + ChildrenRenderer childrenRenderer ) { CompoundTypeRenderer renderer = new CompoundTypeRenderer(this, rendererName, labelRenderer, childrenRenderer); renderer.setClassName(className); @@ -375,21 +367,18 @@ public CompoundTypeRenderer createCompoundTypeRenderer( } public CompoundReferenceRenderer createCompoundReferenceRenderer( - @NonNls final String rendererName, - @NonNls final String className, - final ValueLabelRenderer labelRenderer, - final ChildrenRenderer childrenRenderer + String rendererName, + String className, + ValueLabelRenderer labelRenderer, + ChildrenRenderer childrenRenderer ) { CompoundReferenceRenderer renderer = new CompoundReferenceRenderer(this, rendererName, labelRenderer, childrenRenderer); renderer.setClassName(className); return renderer; } - public static ExpressionChildrenRenderer createExpressionChildrenRenderer( - @NonNls String expressionText, - @NonNls String childrenExpandableText - ) { - final ExpressionChildrenRenderer childrenRenderer = new ExpressionChildrenRenderer(); + public static ExpressionChildrenRenderer createExpressionChildrenRenderer(String expressionText, String childrenExpandableText) { + ExpressionChildrenRenderer childrenRenderer = new ExpressionChildrenRenderer(); childrenRenderer.setChildrenExpression(new TextWithImportsImpl( CodeFragmentKind.EXPRESSION, expressionText, @@ -407,7 +396,7 @@ public static ExpressionChildrenRenderer createExpressionChildrenRenderer( return childrenRenderer; } - public static EnumerationChildrenRenderer createEnumerationChildrenRenderer(@NonNls String[][] expressions) { + public static EnumerationChildrenRenderer createEnumerationChildrenRenderer(String[][] expressions) { EnumerationChildrenRenderer childrenRenderer = new EnumerationChildrenRenderer(); if (expressions != null && expressions.length > 0) { ArrayList childrenList = new ArrayList<>(expressions.length); @@ -428,16 +417,12 @@ public static EnumerationChildrenRenderer createEnumerationChildrenRenderer(@Non return childrenRenderer; } - private static LabelRenderer createLabelRenderer( - @NonNls final String prefix, - @NonNls final String expressionText, - @NonNls final String postfix - ) { - final LabelRenderer labelRenderer = new LabelRenderer() { + private static LabelRenderer createLabelRenderer(final String prefix, String expressionText, final String postfix) { + LabelRenderer labelRenderer = new LabelRenderer() { @Override public String calcLabel(ValueDescriptor descriptor, EvaluationContext evaluationContext, DescriptorLabelListener labelListener) throws EvaluateException { - final String evaluated = super.calcLabel(descriptor, evaluationContext, labelListener); + String evaluated = super.calcLabel(descriptor, evaluationContext, labelListener); if (prefix == null && postfix == null) { return evaluated; } @@ -455,7 +440,7 @@ public String calcLabel(ValueDescriptor descriptor, EvaluationContext evaluation } private static class MapEntryLabelRenderer extends ReferenceRenderer implements ValueLabelRenderer { - private static final Computable NULL_LABEL_COMPUTABLE = () -> "null"; + private static final Supplier NULL_LABEL_COMPUTABLE = () -> "null"; private final MyCachedEvaluator myKeyExpression = new MyCachedEvaluator(); private final MyCachedEvaluator myValueExpression = new MyCachedEvaluator(); @@ -483,41 +468,40 @@ public Image calcValueIcon(ValueDescriptor descriptor, EvaluationContext evaluat } @Override - public String calcLabel( - ValueDescriptor descriptor, - EvaluationContext evaluationContext, - DescriptorLabelListener listener - ) throws EvaluateException { - final DescriptorUpdater descriptorUpdater = new DescriptorUpdater(descriptor, listener); + public String calcLabel(ValueDescriptor descriptor, EvaluationContext evaluationContext, DescriptorLabelListener listener) + throws EvaluateException { + DescriptorUpdater descriptorUpdater = new DescriptorUpdater(descriptor, listener); - final Value originalValue = descriptor.getValue(); - final Pair, ValueDescriptorImpl> keyPair = + Value originalValue = descriptor.getValue(); + Pair, ValueDescriptorImpl> keyPair = createValueComputable(evaluationContext, originalValue, myKeyExpression, descriptorUpdater); - final Pair, ValueDescriptorImpl> valuePair = + Pair, ValueDescriptorImpl> valuePair = createValueComputable(evaluationContext, originalValue, myValueExpression, descriptorUpdater); descriptorUpdater.setKeyDescriptor(keyPair.second); descriptorUpdater.setValueDescriptor(valuePair.second); - return DescriptorUpdater.constructLabelText(keyPair.first.compute(), valuePair.first.compute()); + return DescriptorUpdater.constructLabelText(keyPair.first.get(), valuePair.first.get()); } - private Pair, ValueDescriptorImpl> createValueComputable( - final EvaluationContext evaluationContext, + private Pair, ValueDescriptorImpl> createValueComputable( + EvaluationContext evaluationContext, Value originalValue, - final MyCachedEvaluator evaluator, - final DescriptorLabelListener listener + MyCachedEvaluator evaluator, + DescriptorLabelListener listener ) throws EvaluateException { - final Value eval = doEval(evaluationContext, originalValue, evaluator); + Value eval = doEval(evaluationContext, originalValue, evaluator); if (eval != null) { - final WatchItemDescriptor evalDescriptor = + WatchItemDescriptor evalDescriptor = new WatchItemDescriptor(evaluationContext.getProject(), evaluator.getReferenceExpression(), eval); evalDescriptor.setShowIdLabel(false); - return new Pair<>(() -> - { - evalDescriptor.updateRepresentation((EvaluationContextImpl)evaluationContext, listener); - return evalDescriptor.getValueLabel(); - }, evalDescriptor); + return new Pair<>( + () -> { + evalDescriptor.updateRepresentation((EvaluationContextImpl)evaluationContext, listener); + return evalDescriptor.getValueLabel(); + }, + evalDescriptor + ); } return new Pair<>(NULL_LABEL_COMPUTABLE, null); } @@ -532,20 +516,24 @@ private Value doEval( Value originalValue, MyCachedEvaluator cachedEvaluator ) throws EvaluateException { - final DebugProcess debugProcess = evaluationContext.getDebugProcess(); + DebugProcess debugProcess = evaluationContext.getDebugProcess(); if (originalValue == null) { return null; } try { - final ExpressionEvaluator evaluator = cachedEvaluator.getEvaluator(debugProcess.getProject()); + ExpressionEvaluator evaluator = cachedEvaluator.getEvaluator(debugProcess.getProject()); if (!debugProcess.isAttached()) { throw EvaluateExceptionUtil.PROCESS_EXITED; } - final EvaluationContext thisEvaluationContext = evaluationContext.createEvaluationContext(originalValue); + EvaluationContext thisEvaluationContext = evaluationContext.createEvaluationContext(originalValue); return evaluator.evaluate(thisEvaluationContext); } - catch (final EvaluateException ex) { - throw new EvaluateException(DebuggerBundle.message("error.unable.to.evaluate.expression") + " " + ex.getMessage(), ex); + catch (EvaluateException ex) { + LocalizeValue message = LocalizeValue.join( + JavaDebuggerLocalize.errorUnableToEvaluateExpression(), + LocalizeValue.ofNullable(ex.getMessage()) + ); + throw new EvaluateException(message.get(), ex); } } @@ -620,7 +608,7 @@ public void labelChanged() { myDelegate.labelChanged(); } - static String constructLabelText(final String keylabel, final String valueLabel) { + static String constructLabelText(String keylabel, String valueLabel) { StringBuilder sb = new StringBuilder(); sb.append('\"').append(keylabel).append("\" -> "); if (!StringUtil.isEmpty(valueLabel)) { @@ -629,7 +617,7 @@ static String constructLabelText(final String keylabel, final String valueLabel) return sb.toString(); } - private static String getDescriptorLabel(final ValueDescriptorImpl keyDescriptor) { + private static String getDescriptorLabel(ValueDescriptorImpl keyDescriptor) { return keyDescriptor == null ? "null" : keyDescriptor.getValueLabel(); } } diff --git a/java-execution-impl/src/main/java/com/intellij/java/execution/impl/JavaTestFrameworkRunnableState.java b/java-execution-impl/src/main/java/com/intellij/java/execution/impl/JavaTestFrameworkRunnableState.java index 2c97aab0a0..60cdbd45bb 100644 --- a/java-execution-impl/src/main/java/com/intellij/java/execution/impl/JavaTestFrameworkRunnableState.java +++ b/java-execution-impl/src/main/java/com/intellij/java/execution/impl/JavaTestFrameworkRunnableState.java @@ -30,7 +30,6 @@ import com.intellij.java.language.psi.JavaPsiFacade; import com.intellij.java.language.psi.PsiJavaPackage; import consulo.application.Application; -import consulo.component.extension.Extensions; import consulo.component.macro.PathMacroUtil; import consulo.content.bundle.Sdk; import consulo.disposer.Disposer; @@ -162,14 +161,14 @@ protected GeneralCommandLine createCommandLine() throws ExecutionException { @Nonnull @Override public ExecutionResult execute(@Nonnull Executor executor, @Nonnull ProgramRunner runner) throws ExecutionException { - final RunnerSettings runnerSettings = getRunnerSettings(); + RunnerSettings runnerSettings = getRunnerSettings(); - final SMTRunnerConsoleProperties testConsoleProperties = getConfiguration().createTestConsoleProperties(executor); + SMTRunnerConsoleProperties testConsoleProperties = getConfiguration().createTestConsoleProperties(executor); testConsoleProperties.setIdBasedTestTree(isIdBasedTestTree()); testConsoleProperties.setIfUndefined(TestConsoleProperties.HIDE_PASSED_TESTS, false); - final BaseTestsOutputConsoleView consoleView = SMTestRunnerConnectionUtil.createConsole(getFrameworkName(), testConsoleProperties); - final SMTestRunnerResultsForm viewer = ((SMTRunnerConsoleView)consoleView).getResultsViewer(); + BaseTestsOutputConsoleView consoleView = SMTestRunnerConnectionUtil.createConsole(getFrameworkName(), testConsoleProperties); + SMTestRunnerResultsForm viewer = ((SMTRunnerConsoleView)consoleView).getResultsViewer(); Disposer.register(getConfiguration().getProject(), consoleView); final ProcessHandler handler = createHandler(executor); @@ -187,7 +186,7 @@ public ExecutionResult execute(@Nonnull Executor executor, @Nonnull ProgramRunne @Override public void startNotified(@Nonnull ProcessEvent event) { if (getConfiguration().isSaveOutputToFile()) { - final File file = OutputFileUtil.getOutputFile(getConfiguration()); + File file = OutputFileUtil.getOutputFile(getConfiguration()); root.setOutputFilePath(file != null ? file.getAbsolutePath() : null); } } @@ -209,7 +208,7 @@ public void processTerminated(@Nonnull ProcessEvent event) { LOG.assertTrue(rerunFailedTestsAction != null); rerunFailedTestsAction.setModelProvider(() -> viewer); - final DefaultExecutionResult result = new DefaultExecutionResult(consoleView, handler); + DefaultExecutionResult result = new DefaultExecutionResult(consoleView, handler); result.setRestartActions(rerunFailedTestsAction, new ToggleAutoTestAction() { @Override public boolean isDelayApplicable() { @@ -230,14 +229,14 @@ public AbstractAutoTestManager getAutoTestManager(Project project) { @Override protected OwnJavaParameters createJavaParameters() throws ExecutionException { - final OwnJavaParameters javaParameters = new OwnJavaParameters(); + OwnJavaParameters javaParameters = new OwnJavaParameters(); Project project = getConfiguration().getProject(); - final Module module = getConfiguration().getConfigurationModule().getModule(); + Module module = getConfiguration().getConfigurationModule().getModule(); Sdk jdk = module == null ? null : ModuleUtilCore.getSdk(module, JavaModuleExtension.class); javaParameters.setJdk(jdk); - final String parameters = getConfiguration().getProgramParameters(); + String parameters = getConfiguration().getProgramParameters(); getConfiguration().setProgramParameters(null); try { JavaParametersUtil.configureConfiguration(javaParameters, getConfiguration()); @@ -248,7 +247,7 @@ protected OwnJavaParameters createJavaParameters() throws ExecutionException { javaParameters.getClassPath().addFirst(JavaSdkUtil.getJavaRtJarPath()); configureClasspath(javaParameters); - final JavaTestPatcher[] patchers = JavaTestPatcher.EP_NAME.getExtensions(); + JavaTestPatcher[] patchers = JavaTestPatcher.EP_NAME.getExtensions(); for (JavaTestPatcher patcher : patchers) { patcher.patchJavaParameters(module, javaParameters); } @@ -291,18 +290,20 @@ public ServerSocket getForkSocket() { } private boolean isExecutorDisabledInForkedMode() { - final RunnerSettings settings = getRunnerSettings(); + RunnerSettings settings = getRunnerSettings(); return settings != null && !(settings instanceof GenericDebuggerRunnerSettings); } protected void appendForkInfo(Executor executor) throws ExecutionException { - final String forkMode = getForkMode(); + String forkMode = getForkMode(); if (Comparing.strEqual(forkMode, "none")) { if (forkPerModule()) { if (isExecutorDisabledInForkedMode()) { - final String actionName = executor.getStartActionText().map(Presentation.NO_MNEMONIC).get(); - throw new CantRunException("'" + actionName + "' is disabled when per-module working directory is configured.
" + "Please specify single working directory, or change test " + - "scope to single module."); + String actionName = executor.getStartActionText().map(Presentation.NO_MNEMONIC).get(); + throw new CantRunException( + "'" + actionName + "' is disabled when per-module working directory is configured.
" + + "Please specify single working directory, or change test scope to single module." + ); } } else { @@ -310,18 +311,20 @@ protected void appendForkInfo(Executor executor) throws ExecutionException { } } else if (isExecutorDisabledInForkedMode()) { - final String actionName = executor.getStartActionText().toLowerCase().map(Presentation.NO_MNEMONIC).get(); - throw new CantRunException(actionName + " is disabled in fork mode.
Please change fork mode to <none> to " + actionName + "."); + String actionName = executor.getStartActionText().toLowerCase().map(Presentation.NO_MNEMONIC).get(); + throw new CantRunException( + actionName + " is disabled in fork mode.
Please change fork mode to <none> to " + actionName + "." + ); } - final OwnJavaParameters javaParameters = getJavaParameters(); - final Sdk jdk = javaParameters.getJdk(); + OwnJavaParameters javaParameters = getJavaParameters(); + Sdk jdk = javaParameters.getJdk(); if (jdk == null) { throw new ExecutionException(ExecutionLocalize.runConfigurationErrorNoJdkSpecified().get()); } try { - final File tempFile = FileUtil.createTempFile("command.line", "", true); + File tempFile = FileUtil.createTempFile("command.line", "", true); try (PrintWriter writer = new PrintWriter(tempFile, CharsetToolkit.UTF8)) { if (forkPerModule()) { writer.println("use classpath jar"); @@ -354,11 +357,11 @@ else if (isExecutorDisabledInForkedMode()) { protected abstract void passForkMode(String forkMode, File tempFile, OwnJavaParameters parameters) throws ExecutionException; protected void collectListeners(OwnJavaParameters javaParameters, StringBuilder buf, Class epName, String delimiter) { - final T configuration = getConfiguration(); - final Object[] listeners = Application.get().getExtensionPoint(epName).getExtensions(); - for (final Object listener : listeners) { + T configuration = getConfiguration(); + Object[] listeners = Application.get().getExtensionPoint(epName).getExtensions(); + for (Object listener : listeners) { boolean enabled = true; - for (RunConfigurationExtension ext : Extensions.getExtensions(RunConfigurationExtension.EP_NAME)) { + for (RunConfigurationExtension ext : RunConfigurationExtension.EP_NAME.getExtensions()) { if (ext.isListenerDisabled(configuration, listener, getRunnerSettings())) { enabled = false; break; @@ -368,19 +371,19 @@ protected void collectListeners(OwnJavaParameters javaParameters, StringBuilder if (buf.length() > 0) { buf.append(delimiter); } - final Class classListener = listener.getClass(); + Class classListener = listener.getClass(); buf.append(classListener.getName()); javaParameters.getClassPath().add(ClassPathUtil.getJarPathForClass(classListener)); } } } - protected void configureClasspath(final OwnJavaParameters javaParameters) throws CantRunException { + protected void configureClasspath(OwnJavaParameters javaParameters) throws CantRunException { configureRTClasspath(javaParameters); RunConfigurationModule module = getConfiguration().getConfigurationModule(); - final String alternativeJreName = + String alternativeJreName = getConfiguration().isAlternativeJrePathEnabled() ? getConfiguration().getAlternativeJrePath() : null; - final int pathType = OwnJavaParameters.JDK_AND_CLASSES_AND_TESTS; + int pathType = OwnJavaParameters.JDK_AND_CLASSES_AND_TESTS; if (configureByModule(module.getModule())) { JavaParametersUtil.configureModule(module, javaParameters, pathType, alternativeJreName); } @@ -399,18 +402,18 @@ protected void createServerSocket(OwnJavaParameters javaParameters) { } } - protected boolean spansMultipleModules(final String qualifiedName) { + protected boolean spansMultipleModules(String qualifiedName) { if (qualifiedName != null) { - final Project project = getConfiguration().getProject(); - final PsiJavaPackage aPackage = JavaPsiFacade.getInstance(project).findPackage(qualifiedName); + Project project = getConfiguration().getProject(); + PsiJavaPackage aPackage = JavaPsiFacade.getInstance(project).findPackage(qualifiedName); if (aPackage != null) { - final TestSearchScope scope = getScope(); + TestSearchScope scope = getScope(); if (scope != null) { - final SourceScope sourceScope = scope.getSourceScope(getConfiguration()); + SourceScope sourceScope = scope.getSourceScope(getConfiguration()); if (sourceScope != null) { - final GlobalSearchScope configurationSearchScope = + GlobalSearchScope configurationSearchScope = GlobalSearchScopesCore.projectTestScope(project).intersectWith(sourceScope.getGlobalSearchScope()); - final PsiDirectory[] directories = aPackage.getDirectories(configurationSearchScope); + PsiDirectory[] directories = aPackage.getDirectories(configurationSearchScope); return Arrays.stream(directories) .map(dir -> ModuleUtilCore.findModuleForFile(dir.getVirtualFile(), project)) .filter(Objects::nonNull) @@ -427,9 +430,10 @@ protected boolean spansMultipleModules(final String qualifiedName) { * Configuration based on package which spans multiple modules */ protected boolean forkPerModule() { - final String workingDirectory = getConfiguration().getWorkingDirectory(); - return getScope() != TestSearchScope.SINGLE_MODULE && ("$" + PathMacroUtil.MODULE_DIR_MACRO_NAME + "$").equals(workingDirectory) && spansMultipleModules( - getConfiguration().getPackage()); + String workingDirectory = getConfiguration().getWorkingDirectory(); + return getScope() != TestSearchScope.SINGLE_MODULE + && ("$" + PathMacroUtil.MODULE_DIR_MACRO_NAME + "$").equals(workingDirectory) + && spansMultipleModules(getConfiguration().getPackage()); } protected void createTempFiles(OwnJavaParameters javaParameters) { @@ -445,13 +449,10 @@ protected void createTempFiles(OwnJavaParameters javaParameters) { } } - protected void writeClassesPerModule( - String packageName, - OwnJavaParameters javaParameters, - Map> perModule - ) throws FileNotFoundException, UnsupportedEncodingException, CantRunException { + protected void writeClassesPerModule(String packageName, OwnJavaParameters javaParameters, Map> perModule) + throws FileNotFoundException, UnsupportedEncodingException, CantRunException { if (perModule != null) { - final String classpath = getScope() == TestSearchScope.WHOLE_PROJECT ? null : javaParameters.getClassPath().getPathsString(); + String classpath = getScope() == TestSearchScope.WHOLE_PROJECT ? null : javaParameters.getClassPath().getPathsString(); try (PrintWriter wWriter = new PrintWriter(myWorkingDirsFile, CharsetToolkit.UTF8)) { wWriter.println(packageName); @@ -460,7 +461,7 @@ protected void writeClassesPerModule( wWriter.println(module.getName()); if (classpath == null) { - final OwnJavaParameters parameters = new OwnJavaParameters(); + OwnJavaParameters parameters = new OwnJavaParameters(); parameters.getClassPath().add(JavaSdkUtil.getJavaRtJarPath()); configureRTClasspath(parameters); JavaParametersUtil.configureModule( @@ -476,7 +477,7 @@ protected void writeClassesPerModule( wWriter.println(classpath); } - final List classNames = perModule.get(module); + List classNames = perModule.get(module); wWriter.println(classNames.size()); for (String className : classNames) { wWriter.println(className); diff --git a/java-execution-impl/src/main/java/com/intellij/java/execution/impl/RunConfigurationExtension.java b/java-execution-impl/src/main/java/com/intellij/java/execution/impl/RunConfigurationExtension.java index 3cf46fd5b8..8e61d74ae5 100644 --- a/java-execution-impl/src/main/java/com/intellij/java/execution/impl/RunConfigurationExtension.java +++ b/java-execution-impl/src/main/java/com/intellij/java/execution/impl/RunConfigurationExtension.java @@ -13,19 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -/* - * Created by IntelliJ IDEA. - * User: yole - * Date: 31.01.2007 - * Time: 13:56:12 - */ package com.intellij.java.execution.impl; import consulo.annotation.component.ComponentScope; import consulo.annotation.component.ExtensionAPI; import consulo.component.extension.ExtensionPointName; -import consulo.component.extension.Extensions; import consulo.execution.configuration.RunConfigurationBase; import consulo.execution.configuration.RunConfigurationExtensionBase; import consulo.execution.configuration.RunnerSettings; @@ -38,13 +30,17 @@ import jakarta.annotation.Nullable; +/* + * @author yole + * @since 2007-01-31 + */ @ExtensionAPI(ComponentScope.APPLICATION) public abstract class RunConfigurationExtension extends RunConfigurationExtensionBase { public static final ExtensionPointName EP_NAME = ExtensionPointName.create(RunConfigurationExtension.class); public abstract void updateJavaParameters( - final T configuration, - final OwnJavaParameters params, + T configuration, + OwnJavaParameters params, RunnerSettings runnerSettings ) throws ExecutionException; @@ -88,7 +84,7 @@ public static RefactoringElementListener wrapRefactoringElementListener( RunConfigurationBase runConfigurationBase, RefactoringElementListener listener ) { - for (RunConfigurationExtension extension : Extensions.getExtensions(EP_NAME)) { + for (RunConfigurationExtension extension : EP_NAME.getExtensions()) { listener = extension.wrapElementListener(element, runConfigurationBase, listener); } return listener; diff --git a/java-execution-impl/src/main/java/com/intellij/java/execution/impl/application/BaseJavaApplicationCommandLineState.java b/java-execution-impl/src/main/java/com/intellij/java/execution/impl/application/BaseJavaApplicationCommandLineState.java index fc07609c74..65c4bac6f8 100644 --- a/java-execution-impl/src/main/java/com/intellij/java/execution/impl/application/BaseJavaApplicationCommandLineState.java +++ b/java-execution-impl/src/main/java/com/intellij/java/execution/impl/application/BaseJavaApplicationCommandLineState.java @@ -34,7 +34,7 @@ public abstract class BaseJavaApplicationCommandLineState extends JavaCommandLineState { protected final T myConfiguration; - public BaseJavaApplicationCommandLineState(ExecutionEnvironment environment, @Nonnull final T configuration) { + public BaseJavaApplicationCommandLineState(ExecutionEnvironment environment, @Nonnull T configuration) { super(environment); myConfiguration = configuration; } diff --git a/java-indexing-impl/src/main/java/com/intellij/java/indexing/impl/search/CustomPropertyScopeProvider.java b/java-indexing-impl/src/main/java/com/intellij/java/indexing/impl/search/CustomPropertyScopeProvider.java index 8407f98b1e..563fec7605 100644 --- a/java-indexing-impl/src/main/java/com/intellij/java/indexing/impl/search/CustomPropertyScopeProvider.java +++ b/java-indexing-impl/src/main/java/com/intellij/java/indexing/impl/search/CustomPropertyScopeProvider.java @@ -25,5 +25,5 @@ public interface CustomPropertyScopeProvider { ExtensionPointName EP_NAME = ExtensionPointName.create(CustomPropertyScopeProvider.class); - SearchScope getScope(final Project project); + SearchScope getScope(Project project); } \ No newline at end of file diff --git a/java-language-api/src/main/java/com/intellij/java/language/codeInsight/runner/JavaMainMethodProvider.java b/java-language-api/src/main/java/com/intellij/java/language/codeInsight/runner/JavaMainMethodProvider.java index e9a5c62c03..f1daa7a2ac 100644 --- a/java-language-api/src/main/java/com/intellij/java/language/codeInsight/runner/JavaMainMethodProvider.java +++ b/java-language-api/src/main/java/com/intellij/java/language/codeInsight/runner/JavaMainMethodProvider.java @@ -28,9 +28,9 @@ public interface JavaMainMethodProvider { ExtensionPointName EP_NAME = ExtensionPointName.create(JavaMainMethodProvider.class); - boolean isApplicable(final PsiClass clazz); + boolean isApplicable(PsiClass clazz); - boolean hasMainMethod(final PsiClass clazz); + boolean hasMainMethod(PsiClass clazz); - PsiMethod findMainInClass(final PsiClass clazz); + PsiMethod findMainInClass(PsiClass clazz); } diff --git a/java-language-api/src/main/java/com/intellij/java/language/psi/augment/PsiAugmentProvider.java b/java-language-api/src/main/java/com/intellij/java/language/psi/augment/PsiAugmentProvider.java index a87b054f27..2b7d400e66 100644 --- a/java-language-api/src/main/java/com/intellij/java/language/psi/augment/PsiAugmentProvider.java +++ b/java-language-api/src/main/java/com/intellij/java/language/psi/augment/PsiAugmentProvider.java @@ -9,7 +9,6 @@ import consulo.application.util.CachedValue; import consulo.application.util.CachedValueProvider; import consulo.application.util.ConcurrentFactoryMap; -import consulo.application.util.function.Processor; import consulo.component.ProcessCanceledException; import consulo.component.extension.ExtensionPointName; import consulo.component.util.PluginExceptionUtil; @@ -23,7 +22,7 @@ import consulo.project.Project; import consulo.util.collection.SmartList; import consulo.util.dataholder.Key; -import consulo.util.lang.ref.Ref; +import consulo.util.lang.ref.SimpleReference; import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; @@ -32,6 +31,7 @@ import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Predicate; /** * Some code is not what it seems to be! @@ -74,10 +74,14 @@ protected List getAugments( } // cache to emulate previous behavior where augmenters were called just once, not for each name hint separately - Map cache = LanguageCachedValueUtil.getCachedValue(element, myCacheKey, () -> { - Map map = ConcurrentFactoryMap.createMap(c -> getAugments(element, c)); - return CachedValueProvider.Result.create(map, PsiModificationTracker.MODIFICATION_COUNT); - }); + Map cache = LanguageCachedValueUtil.getCachedValue( + element, + myCacheKey, + () -> { + Map map = ConcurrentFactoryMap.createMap(c -> getAugments(element, c)); + return CachedValueProvider.Result.create(map, PsiModificationTracker.MODIFICATION_COUNT); + } + ); return (List)cache.get(type); } @@ -161,24 +165,27 @@ public static List collectAugments( ) { List result = new SmartList<>(); - forEach(element.getProject(), provider -> { - List augments = provider.getAugments(element, type, nameHint); - for (Psi augment : augments) { - if (nameHint == null || !(augment instanceof PsiNamedElement) || nameHint.equals(((PsiNamedElement)augment).getName())) { - try { - PsiUtilCore.ensureValid(augment); - result.add(augment); - } - catch (ProcessCanceledException e) { - throw e; - } - catch (Throwable e) { - PluginExceptionUtil.logPluginError(LOG, e.getMessage(), e, provider.getClass()); + forEach( + element.getProject(), + provider -> { + List augments = provider.getAugments(element, type, nameHint); + for (Psi augment : augments) { + if (nameHint == null || !(augment instanceof PsiNamedElement namedElem) || nameHint.equals(namedElem.getName())) { + try { + PsiUtilCore.ensureValid(augment); + result.add(augment); + } + catch (ProcessCanceledException e) { + throw e; + } + catch (Throwable e) { + PluginExceptionUtil.logPluginError(LOG, e.getMessage(), e, provider.getClass()); + } } } + return true; } - return true; - }); + ); return result; } @@ -207,27 +214,30 @@ public static List collectExtensionMethods(PsiClass aClass, @Nullable public static PsiType getInferredType(@Nonnull PsiTypeElement typeElement) { - Ref result = Ref.create(); + SimpleReference result = SimpleReference.create(); - forEach(typeElement.getProject(), provider -> { - PsiType type = provider.inferType(typeElement); - if (type != null) { - try { - PsiUtil.ensureValidType(type); - } - catch (ProcessCanceledException e) { - throw e; + forEach( + typeElement.getProject(), + provider -> { + PsiType type = provider.inferType(typeElement); + if (type != null) { + try { + PsiUtil.ensureValidType(type); + } + catch (ProcessCanceledException e) { + throw e; + } + catch (Throwable e) { + PluginExceptionUtil.logPluginError(LOG, e.getMessage(), e, provider.getClass()); + } + result.set(type); + return false; } - catch (Throwable e) { - PluginExceptionUtil.logPluginError(LOG, e.getMessage(), e, provider.getClass()); + else { + return true; } - result.set(type); - return false; - } - else { - return true; } - }); + ); return result.get(); } @@ -271,22 +281,25 @@ public static Set transformModifierProperties( @Nonnull Project project, @Nonnull Set modifiers ) { - Ref> result = Ref.create(modifiers); + SimpleReference> result = SimpleReference.create(modifiers); - forEach(project, provider -> { - result.set(provider.transformModifiers(modifierList, Collections.unmodifiableSet(result.get()))); - return true; - }); + forEach( + project, + provider -> { + result.set(provider.transformModifiers(modifierList, Collections.unmodifiableSet(result.get()))); + return true; + } + ); return result.get(); } - private static void forEach(Project project, Processor processor) { + private static void forEach(Project project, Predicate processor) { boolean dumb = DumbService.isDumb(project); for (PsiAugmentProvider provider : EP_NAME.getExtensionList()) { if (!dumb || DumbService.isDumbAware(provider)) { try { - boolean goOn = processor.process(provider); + boolean goOn = processor.test(provider); if (!goOn) { break; } diff --git a/java-language-api/src/main/java/com/intellij/java/language/psi/util/PsiMethodUtil.java b/java-language-api/src/main/java/com/intellij/java/language/psi/util/PsiMethodUtil.java index 77a0b0cfee..fd961997f0 100644 --- a/java-language-api/src/main/java/com/intellij/java/language/psi/util/PsiMethodUtil.java +++ b/java-language-api/src/main/java/com/intellij/java/language/psi/util/PsiMethodUtil.java @@ -13,11 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.intellij.java.language.psi.util; import com.intellij.java.language.codeInsight.runner.JavaMainMethodProvider; import com.intellij.java.language.psi.*; +import consulo.java.language.module.util.JavaClassNames; import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; @@ -31,29 +31,30 @@ public class PsiMethodUtil { if (psiClass instanceof PsiAnonymousClass) { return false; } + //noinspection SimplifiableIfStatement if (psiClass.isInterface()) { return false; } - return psiClass.getContainingClass() == null || psiClass.hasModifierProperty(PsiModifier.STATIC); + return psiClass.getContainingClass() == null || psiClass.isStatic(); }; private PsiMethodUtil() { } @Nullable - public static PsiMethod findMainMethod(final PsiClass aClass) { + public static PsiMethod findMainMethod(PsiClass aClass) { for (JavaMainMethodProvider provider : JavaMainMethodProvider.EP_NAME.getExtensionList()) { if (provider.isApplicable(aClass)) { return provider.findMainInClass(aClass); } } - final PsiMethod[] mainMethods = aClass.findMethodsByName("main", true); + PsiMethod[] mainMethods = aClass.findMethodsByName("main", true); return findMainMethod(mainMethods); } @Nullable - private static PsiMethod findMainMethod(final PsiMethod[] mainMethods) { - for (final PsiMethod mainMethod : mainMethods) { + private static PsiMethod findMainMethod(PsiMethod[] mainMethods) { + for (PsiMethod mainMethod : mainMethods) { if (isMainMethod(mainMethod)) { return mainMethod; } @@ -61,32 +62,32 @@ private static PsiMethod findMainMethod(final PsiMethod[] mainMethods) { return null; } - public static boolean isMainMethod(final PsiMethod method) { + public static boolean isMainMethod(PsiMethod method) { if (method == null || method.getContainingClass() == null) { return false; } if (!PsiType.VOID.equals(method.getReturnType())) { return false; } - if (!method.hasModifierProperty(PsiModifier.STATIC)) { + if (!method.isStatic()) { return false; } - if (!method.hasModifierProperty(PsiModifier.PUBLIC)) { + if (!method.isPublic()) { return false; } - final PsiParameter[] parameters = method.getParameterList().getParameters(); + PsiParameter[] parameters = method.getParameterList().getParameters(); if (parameters.length != 1) { return false; } - final PsiType type = parameters[0].getType(); - if (!(type instanceof PsiArrayType)) { + PsiType type = parameters[0].getType(); + if (!(type instanceof PsiArrayType arrayType)) { return false; } - final PsiType componentType = ((PsiArrayType) type).getComponentType(); - return componentType.equalsToText("java.lang.String"); + PsiType componentType = arrayType.getComponentType(); + return componentType.equalsToText(JavaClassNames.JAVA_LANG_STRING); } - public static boolean hasMainMethod(final PsiClass psiClass) { + public static boolean hasMainMethod(PsiClass psiClass) { for (JavaMainMethodProvider provider : JavaMainMethodProvider.EP_NAME.getExtensionList()) { if (provider.isApplicable(psiClass)) { return provider.hasMainMethod(psiClass); @@ -101,15 +102,12 @@ public static boolean hasMainMethod(final PsiClass psiClass) { * @param aClass the class to check for a main method. * @return true if the class has a main method, false otherwise. */ - public static boolean hasMainInClass(@Nonnull final PsiClass aClass) { - if (!MAIN_CLASS.test(aClass)) { - return false; - } - return hasMainMethod(aClass); + public static boolean hasMainInClass(@Nonnull PsiClass aClass) { + return MAIN_CLASS.test(aClass) && hasMainMethod(aClass); } @Nullable - public static PsiMethod findMainInClass(final PsiClass aClass) { + public static PsiMethod findMainInClass(PsiClass aClass) { if (!MAIN_CLASS.test(aClass)) { return null; } diff --git a/java-language-impl/src/main/java/com/intellij/java/language/impl/codeInsight/ExceptionUtil.java b/java-language-impl/src/main/java/com/intellij/java/language/impl/codeInsight/ExceptionUtil.java index 73e08b4ecf..41573f51b7 100644 --- a/java-language-impl/src/main/java/com/intellij/java/language/impl/codeInsight/ExceptionUtil.java +++ b/java-language-impl/src/main/java/com/intellij/java/language/impl/codeInsight/ExceptionUtil.java @@ -28,6 +28,7 @@ import com.intellij.java.language.psi.util.MethodSignatureUtil; import com.intellij.java.language.psi.util.PsiUtil; import com.intellij.java.language.psi.util.TypeConversionUtil; +import consulo.annotation.access.RequiredReadAction; import consulo.java.language.impl.codeInsight.ExtraExceptionHandler; import consulo.java.language.module.util.JavaClassNames; import consulo.language.psi.PsiElement; @@ -44,7 +45,6 @@ import consulo.util.lang.Pair; import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; -import org.jetbrains.annotations.NonNls; import java.util.*; @@ -52,7 +52,6 @@ * @author mike */ public class ExceptionUtil { - @NonNls private static final String CLONE_METHOD_NAME = "clone"; private ExceptionUtil() { @@ -60,7 +59,7 @@ private ExceptionUtil() { @Nonnull public static List getThrownExceptions(@Nonnull PsiElement[] elements) { - List array = ContainerUtil.newArrayList(); + List array = new ArrayList<>(); for (PsiElement element : elements) { List exceptions = getThrownExceptions(element); addExceptions(array, exceptions); @@ -81,7 +80,7 @@ public static List getThrownCheckedExceptions(@Nonnull PsiElement. @Nonnull private static List filterOutUncheckedExceptions(@Nonnull List exceptions) { - List array = ContainerUtil.newArrayList(); + List array = new ArrayList<>(); for (PsiClassType exception : exceptions) { if (!isUncheckedException(exception)) { array.add(exception); @@ -95,8 +94,8 @@ public static List getThrownExceptions(@Nonnull PsiElement element List result = new ArrayList<>(); element.accept(new JavaRecursiveElementWalkingVisitor() { @Override - public void visitAnonymousClass(PsiAnonymousClass aClass) { - final PsiExpressionList argumentList = aClass.getArgumentList(); + public void visitAnonymousClass(@Nonnull PsiAnonymousClass aClass) { + PsiExpressionList argumentList = aClass.getArgumentList(); if (argumentList != null) { super.visitExpressionList(argumentList); } @@ -104,12 +103,12 @@ public void visitAnonymousClass(PsiAnonymousClass aClass) { } @Override - public void visitClass(PsiClass aClass) { + public void visitClass(@Nonnull PsiClass aClass) { // do not go inside class declaration } @Override - public void visitMethodCallExpression(PsiMethodCallExpression expression) { + public void visitMethodCallExpression(@Nonnull PsiMethodCallExpression expression) { PsiReferenceExpression methodRef = expression.getMethodExpression(); JavaResolveResult resolveResult = methodRef.advancedResolve(false); PsiMethod method = (PsiMethod)resolveResult.getElement(); @@ -120,7 +119,7 @@ public void visitMethodCallExpression(PsiMethodCallExpression expression) { } @Override - public void visitNewExpression(PsiNewExpression expression) { + public void visitNewExpression(@Nonnull PsiNewExpression expression) { JavaResolveResult resolveResult = expression.resolveMethodGenerics(); PsiMethod method = (PsiMethod)resolveResult.getElement(); if (method != null) { @@ -130,24 +129,25 @@ public void visitNewExpression(PsiNewExpression expression) { } @Override - public void visitThrowStatement(PsiThrowStatement statement) { - final PsiExpression expr = statement.getException(); + @RequiredReadAction + public void visitThrowStatement(@Nonnull PsiThrowStatement statement) { + PsiExpression expr = statement.getException(); if (expr != null) { addExceptions( result, - ContainerUtil.mapNotNull(getPreciseThrowTypes(expr), (it) -> it instanceof PsiClassType ? (PsiClassType)it : null) + ContainerUtil.mapNotNull(getPreciseThrowTypes(expr), it -> it instanceof PsiClassType classType ? classType : null) ); } super.visitThrowStatement(statement); } @Override - public void visitLambdaExpression(PsiLambdaExpression expression) { + public void visitLambdaExpression(@Nonnull PsiLambdaExpression expression) { // do not go inside lambda } @Override - public void visitResourceList(PsiResourceList resourceList) { + public void visitResourceList(@Nonnull PsiResourceList resourceList) { for (PsiResourceListElement listElement : resourceList) { addExceptions(result, getCloserExceptions(listElement)); } @@ -155,7 +155,7 @@ public void visitResourceList(PsiResourceList resourceList) { } @Override - public void visitTryStatement(PsiTryStatement statement) { + public void visitTryStatement(@Nonnull PsiTryStatement statement) { addExceptions(result, getTryExceptions(statement)); // do not call super: try exception goes into try body recursively } @@ -165,7 +165,7 @@ public void visitTryStatement(PsiTryStatement statement) { @Nonnull private static List getTryExceptions(@Nonnull PsiTryStatement tryStatement) { - List array = ContainerUtil.newArrayList(); + List array = new ArrayList<>(); PsiResourceList resourceList = tryStatement.getResourceList(); if (resourceList != null) { @@ -203,7 +203,7 @@ private static List getTryExceptions(@Nonnull PsiTryStatement tryS int completionReasons = ControlFlowUtil.getCompletionReasons(flow, 0, flow.getSize()); List thrownExceptions = getThrownExceptions(finallyBlock); if (!BitUtil.isSet(completionReasons, ControlFlowUtil.NORMAL_COMPLETION_REASON)) { - array = ContainerUtil.newArrayList(thrownExceptions); + array = new ArrayList<>(thrownExceptions); } else { addExceptions(array, thrownExceptions); @@ -218,11 +218,12 @@ private static List getTryExceptions(@Nonnull PsiTryStatement tryS } @Nonnull + @RequiredReadAction private static List getExceptionsByMethodAndChildren( @Nonnull PsiElement element, @Nonnull JavaResolveResult resolveResult ) { - List result = ContainerUtil.newArrayList(); + List result = new ArrayList<>(); PsiMethod method = (PsiMethod)resolveResult.getElement(); if (method != null) { @@ -247,11 +248,11 @@ private static List getExceptionsByMethod( GlobalSearchScope scope = place.getResolveScope(); - List result = ContainerUtil.newArrayList(); + List result = new ArrayList<>(); for (PsiType type : referenceTypes) { type = PsiClassImplUtil.correctType(substitutor.substitute(type), scope); - if (type instanceof PsiClassType) { - result.add((PsiClassType)type); + if (type instanceof PsiClassType classType) { + result.add(classType); } } @@ -281,21 +282,24 @@ private static void addException(@Nonnull List array, @Nullable Ps } @Nonnull + @RequiredReadAction public static Collection collectUnhandledExceptions(@Nonnull PsiElement element, @Nullable PsiElement topElement) { return collectUnhandledExceptions(element, topElement, true); } @Nonnull + @RequiredReadAction public static Collection collectUnhandledExceptions( @Nonnull PsiElement element, @Nullable PsiElement topElement, boolean includeSelfCalls ) { - final Set set = collectUnhandledExceptions(element, topElement, null, includeSelfCalls); + Set set = collectUnhandledExceptions(element, topElement, null, includeSelfCalls); return set == null ? Collections.emptyList() : set; } @Nullable + @RequiredReadAction private static Set collectUnhandledExceptions( @Nonnull PsiElement element, @Nullable PsiElement topElement, @@ -303,34 +307,31 @@ private static Set collectUnhandledExceptions( boolean includeSelfCalls ) { Collection unhandledExceptions = null; - if (element instanceof PsiCallExpression) { - PsiCallExpression expression = (PsiCallExpression)element; - unhandledExceptions = getUnhandledExceptions(expression, topElement, includeSelfCalls); + if (element instanceof PsiCallExpression call) { + unhandledExceptions = getUnhandledExceptions(call, topElement, includeSelfCalls); } - else if (element instanceof PsiMethodReferenceExpression) { - PsiExpression qualifierExpression = ((PsiMethodReferenceExpression)element).getQualifierExpression(); - return qualifierExpression != null ? collectUnhandledExceptions(qualifierExpression, topElement, null, false) : null; + else if (element instanceof PsiMethodReferenceExpression methodRef) { + PsiExpression qualifierExpression = methodRef.getQualifierExpression(); + return qualifierExpression != null + ? collectUnhandledExceptions(qualifierExpression, topElement, null, false) + : null; } else if (element instanceof PsiLambdaExpression) { return null; } - else if (element instanceof PsiThrowStatement) { - PsiThrowStatement statement = (PsiThrowStatement)element; - unhandledExceptions = getUnhandledExceptions(statement, topElement); + else if (element instanceof PsiThrowStatement throwStmt) { + unhandledExceptions = getUnhandledExceptions(throwStmt, topElement); } - else if (element instanceof PsiCodeBlock && element.getParent() instanceof PsiMethod && ((PsiMethod)element.getParent()).isConstructor() && !firstStatementIsConstructorCall( - (PsiCodeBlock) - element)) { + else if (element instanceof PsiCodeBlock codeBlock && codeBlock.getParent() instanceof PsiMethod constructor + && constructor.isConstructor() && !firstStatementIsConstructorCall(codeBlock)) { // there is implicit parent constructor call - final PsiMethod constructor = (PsiMethod)element.getParent(); - final PsiClass aClass = constructor.getContainingClass(); - final PsiClass superClass = aClass == null ? null : aClass.getSuperClass(); - final PsiMethod[] superConstructors = superClass == null ? PsiMethod.EMPTY_ARRAY : superClass.getConstructors(); + PsiClass aClass = constructor.getContainingClass(); + PsiClass superClass = aClass == null ? null : aClass.getSuperClass(); + PsiMethod[] superConstructors = superClass == null ? PsiMethod.EMPTY_ARRAY : superClass.getConstructors(); Set unhandled = new HashSet<>(); for (PsiMethod superConstructor : superConstructors) { - if (!superConstructor.hasModifierProperty(PsiModifier.PRIVATE) && superConstructor.getParameterList() - .getParametersCount() == 0) { - final PsiClassType[] exceptionTypes = superConstructor.getThrowsList().getReferencedTypes(); + if (!superConstructor.isPrivate() && superConstructor.getParameterList().getParametersCount() == 0) { + PsiClassType[] exceptionTypes = superConstructor.getThrowsList().getReferencedTypes(); for (PsiClassType exceptionType : exceptionTypes) { if (!isUncheckedException(exceptionType) && !isHandled(element, exceptionType, topElement)) { unhandled.add(exceptionType); @@ -342,10 +343,10 @@ else if (element instanceof PsiCodeBlock && element.getParent() instanceof PsiMe // plus all exceptions thrown in instance class initializers if (aClass != null) { - final PsiClassInitializer[] initializers = aClass.getInitializers(); - final Set thrownByInitializer = new HashSet<>(); + PsiClassInitializer[] initializers = aClass.getInitializers(); + Set thrownByInitializer = new HashSet<>(); for (PsiClassInitializer initializer : initializers) { - if (initializer.hasModifierProperty(PsiModifier.STATIC)) { + if (initializer.isStatic()) { continue; } thrownByInitializer.clear(); @@ -359,10 +360,10 @@ else if (element instanceof PsiCodeBlock && element.getParent() instanceof PsiMe } unhandledExceptions = unhandled; } - else if (element instanceof PsiResourceListElement) { - final List unhandled = getUnhandledCloserExceptions((PsiResourceListElement)element, topElement); + else if (element instanceof PsiResourceListElement resourceListElement) { + List unhandled = getUnhandledCloserExceptions(resourceListElement, topElement); if (!unhandled.isEmpty()) { - unhandledExceptions = ContainerUtil.newArrayList(unhandled); + unhandledExceptions = new ArrayList<>(unhandled); } } @@ -391,40 +392,37 @@ private static Collection getUnhandledExceptions( @Nonnull PsiMethodReferenceExpression methodReferenceExpression, PsiElement topElement ) { - final JavaResolveResult resolveResult = methodReferenceExpression.advancedResolve(false); - final PsiElement resolve = resolveResult.getElement(); - if (resolve instanceof PsiMethod) { - final PsiElement referenceNameElement = methodReferenceExpression.getReferenceNameElement(); - return getUnhandledExceptions((PsiMethod)resolve, referenceNameElement, topElement, resolveResult.getSubstitutor()); + JavaResolveResult resolveResult = methodReferenceExpression.advancedResolve(false); + if (resolveResult.getElement() instanceof PsiMethod method) { + PsiElement referenceNameElement = methodReferenceExpression.getReferenceNameElement(); + return getUnhandledExceptions(method, referenceNameElement, topElement, resolveResult.getSubstitutor()); } return Collections.emptyList(); } + @RequiredReadAction private static boolean firstStatementIsConstructorCall(@Nonnull PsiCodeBlock constructorBody) { - final PsiStatement[] statements = constructorBody.getStatements(); + PsiStatement[] statements = constructorBody.getStatements(); if (statements.length == 0) { return false; } - if (!(statements[0] instanceof PsiExpressionStatement)) { + if (!(statements[0] instanceof PsiExpressionStatement exprStmt) + || !(exprStmt.getExpression() instanceof PsiMethodCallExpression methodCall)) { return false; } - final PsiExpression expression = ((PsiExpressionStatement)statements[0]).getExpression(); - if (!(expression instanceof PsiMethodCallExpression)) { - return false; - } - final PsiMethod method = (PsiMethod)((PsiMethodCallExpression)expression).getMethodExpression().resolve(); + PsiMethod method = (PsiMethod)methodCall.getMethodExpression().resolve(); return method != null && method.isConstructor(); } @Nonnull public static List getUnhandledExceptions(final @Nonnull PsiElement[] elements) { - final List array = ContainerUtil.newArrayList(); + final List array = new ArrayList<>(); - final PsiElementVisitor visitor = new JavaRecursiveElementWalkingVisitor() { + PsiElementVisitor visitor = new JavaRecursiveElementWalkingVisitor() { @Override public void visitEnumConstant(PsiEnumConstant enumConstant) { - final PsiMethod method = enumConstant.resolveMethod(); + PsiMethod method = enumConstant.resolveMethod(); if (method != null) { addExceptions(array, getUnhandledExceptions(method, enumConstant, null, PsiSubstitutor.EMPTY)); } @@ -438,13 +436,14 @@ public void visitCallExpression(@Nonnull PsiCallExpression expression) { } @Override + @RequiredReadAction public void visitThrowStatement(@Nonnull PsiThrowStatement statement) { addExceptions(array, getUnhandledExceptions(statement, null)); visitElement(statement); } @Override - public void visitLambdaExpression(PsiLambdaExpression expression) { + public void visitLambdaExpression(@Nonnull PsiLambdaExpression expression) { if (ArrayUtil.find(elements, expression) >= 0) { visitElement(expression); } @@ -471,7 +470,7 @@ public void visitResourceExpression(@Nonnull PsiResourceExpression resource) { } @Override - public void visitClass(PsiClass aClass) { + public void visitClass(@Nonnull PsiClass aClass) { } }; @@ -489,32 +488,30 @@ public static List getUnhandledExceptions(@Nonnull PsiElement elem @Nonnull public static List getUnhandledExceptions( - @Nonnull final PsiCallExpression methodCall, - @Nullable final PsiElement topElement + @Nonnull PsiCallExpression methodCall, + @Nullable PsiElement topElement ) { return getUnhandledExceptions(methodCall, topElement, true); } @Nonnull public static List getUnhandledExceptions( - @Nonnull final PsiCallExpression methodCall, - @Nullable final PsiElement topElement, - final boolean includeSelfCalls + @Nonnull PsiCallExpression methodCall, + @Nullable PsiElement topElement, + boolean includeSelfCalls ) { //exceptions only influence the invocation type after overload resolution is complete if (MethodCandidateInfo.isOverloadCheck()) { return Collections.emptyList(); } - final MethodCandidateInfo.CurrentCandidateProperties properties = + MethodCandidateInfo.CurrentCandidateProperties properties = MethodCandidateInfo.getCurrentMethod(methodCall.getArgumentList()); - final JavaResolveResult result = + JavaResolveResult result = properties != null ? properties.getInfo() : PsiDiamondType.getDiamondsAwareResolveResult(methodCall); - final PsiElement element = result.getElement(); - final PsiMethod method = element instanceof PsiMethod ? (PsiMethod)element : null; - if (method == null) { + if (!(result.getElement() instanceof PsiMethod method)) { return Collections.emptyList(); } - final PsiMethod containingMethod = PsiTreeUtil.getParentOfType(methodCall, PsiMethod.class); + PsiMethod containingMethod = PsiTreeUtil.getParentOfType(methodCall, PsiMethod.class); if (!includeSelfCalls && method == containingMethod) { return Collections.emptyList(); } @@ -523,39 +520,42 @@ public static List getUnhandledExceptions( PsiUtilCore.ensureValid(method); } - final PsiClassType[] thrownExceptions = method.getThrowsList().getReferencedTypes(); + PsiClassType[] thrownExceptions = method.getThrowsList().getReferencedTypes(); if (thrownExceptions.length == 0) { return Collections.emptyList(); } - final PsiSubstitutor substitutor = result.getSubstitutor(); - if (!isArrayClone(method, methodCall) && methodCall instanceof PsiMethodCallExpression) { - final PsiFile containingFile = (containingMethod == null ? methodCall : containingMethod).getContainingFile(); - final MethodResolverProcessor processor = new MethodResolverProcessor((PsiMethodCallExpression)methodCall, containingFile); + PsiSubstitutor substitutor = result.getSubstitutor(); + if (!isArrayClone(method, methodCall) && methodCall instanceof PsiMethodCallExpression methodCallExpr) { + PsiFile containingFile = (containingMethod == null ? methodCallExpr : containingMethod).getContainingFile(); + MethodResolverProcessor processor = new MethodResolverProcessor(methodCallExpr, containingFile); try { - PsiScopesUtil.setupAndRunProcessor(processor, methodCall, false); - final List> candidates = ContainerUtil.mapNotNull(processor.getResults(), info -> - { - PsiElement element1 = info.getElement(); - if (info instanceof MethodCandidateInfo && element1 != method && //don't check self - MethodSignatureUtil.areSignaturesEqual(method, (PsiMethod)element1) - && !MethodSignatureUtil.isSuperMethod((PsiMethod)element1, method) && !(((MethodCandidateInfo)info) - .isToInferApplicability() && !((MethodCandidateInfo)info).isApplicable())) { - return Pair.create((PsiMethod)element1, ((MethodCandidateInfo)info).getSubstitutor(false)); + PsiScopesUtil.setupAndRunProcessor(processor, methodCallExpr, false); + List> candidates = ContainerUtil.mapNotNull( + processor.getResults(), + info -> { + if (info instanceof MethodCandidateInfo candidate + && info.getElement() instanceof PsiMethod otherMethod + && otherMethod != method /* don't check self */ + && MethodSignatureUtil.areSignaturesEqual(method, otherMethod) + && !MethodSignatureUtil.isSuperMethod(otherMethod, method) + && !(candidate.isToInferApplicability() && !candidate.isApplicable())) { + return Pair.create(otherMethod, candidate.getSubstitutor(false)); + } + return null; } - return null; - }); + ); if (!candidates.isEmpty()) { - GlobalSearchScope scope = methodCall.getResolveScope(); - final List ex = collectSubstituted(substitutor, thrownExceptions, scope); + GlobalSearchScope scope = methodCallExpr.getResolveScope(); + List ex = collectSubstituted(substitutor, thrownExceptions, scope); for (Pair pair : candidates) { - final PsiClassType[] exceptions = pair.first.getThrowsList().getReferencedTypes(); + PsiClassType[] exceptions = pair.first.getThrowsList().getReferencedTypes(); if (exceptions.length == 0) { - return getUnhandledExceptions(methodCall, topElement, PsiSubstitutor.EMPTY, PsiClassType.EMPTY_ARRAY); + return getUnhandledExceptions(methodCallExpr, topElement, PsiSubstitutor.EMPTY, PsiClassType.EMPTY_ARRAY); } retainExceptions(ex, collectSubstituted(pair.second, exceptions, scope)); } - return getUnhandledExceptions(methodCall, topElement, PsiSubstitutor.EMPTY, ex.toArray(new PsiClassType[ex.size()])); + return getUnhandledExceptions(methodCallExpr, topElement, PsiSubstitutor.EMPTY, ex.toArray(new PsiClassType[ex.size()])); } } catch (MethodProcessorSetupFailedException ignore) { @@ -567,7 +567,7 @@ public static List getUnhandledExceptions( } public static void retainExceptions(List ex, List thrownEx) { - final List replacement = new ArrayList<>(); + List replacement = new ArrayList<>(); for (Iterator iterator = ex.iterator(); iterator.hasNext(); ) { PsiClassType classType = iterator.next(); boolean found = false; @@ -595,17 +595,15 @@ public static List collectSubstituted( PsiClassType[] thrownExceptions, GlobalSearchScope scope ) { - final List ex = new ArrayList<>(); + List ex = new ArrayList<>(); for (PsiClassType thrownException : thrownExceptions) { - final PsiType psiType = PsiClassImplUtil.correctType(substitutor.substitute(thrownException), scope); - if (psiType instanceof PsiClassType) { - ex.add((PsiClassType)psiType); - } - else if (psiType instanceof PsiCapturedWildcardType) { - final PsiCapturedWildcardType capturedWildcardType = (PsiCapturedWildcardType)psiType; - final PsiType upperBound = capturedWildcardType.getUpperBound(); - if (upperBound instanceof PsiClassType) { - ex.add((PsiClassType)upperBound); + PsiType psiType = PsiClassImplUtil.correctType(substitutor.substitute(thrownException), scope); + if (psiType instanceof PsiClassType classType) { + ex.add(classType); + } + else if (psiType instanceof PsiCapturedWildcardType capturedWildcardType) { + if (capturedWildcardType.getUpperBound() instanceof PsiClassType upperBoundClassType) { + ex.add(upperBoundClassType); } } } @@ -623,24 +621,20 @@ public static List getUnhandledCloserExceptions( @Nonnull PsiResourceListElement resource, @Nullable PsiElement topElement ) { - final PsiType type = resource.getType(); + PsiType type = resource.getType(); return getUnhandledCloserExceptions(resource, topElement, type); } @Nonnull public static List getUnhandledCloserExceptions(PsiElement place, @Nullable PsiElement topElement, PsiType type) { List ex = type instanceof PsiClassType ? getExceptionsFromClose(type, place.getResolveScope()) : null; - return ex != null ? getUnhandledExceptions( - place, - topElement, - PsiSubstitutor.EMPTY, - ex.toArray(new PsiClassType[ex.size()]) - ) : Collections.emptyList(); + return ex != null + ? getUnhandledExceptions(place, topElement, PsiSubstitutor.EMPTY, ex.toArray(new PsiClassType[ex.size()])) + : Collections.emptyList(); } private static List getExceptionsFromClose(PsiResourceListElement resource) { - final PsiType type = resource.getType(); - return type instanceof PsiClassType ? getExceptionsFromClose(type, resource.getResolveScope()) : null; + return resource.getType() instanceof PsiClassType classType ? getExceptionsFromClose(classType, resource.getResolveScope()) : null; } private static List getExceptionsFromClose(PsiType type, GlobalSearchScope scope) { @@ -659,7 +653,7 @@ private static List getExceptionsFromClose(PsiType type, GlobalSea PsiSubstitutor substitutor = TypeConversionUtil.getClassSubstitutor(closerClass, resourceClass, resourceType.getSubstitutor()); if (substitutor != null) { - final PsiClassType[] exceptionTypes = method.getThrowsList().getReferencedTypes(); + PsiClassType[] exceptionTypes = method.getThrowsList().getReferencedTypes(); if (exceptionTypes.length == 0) { return Collections.emptyList(); } @@ -680,17 +674,17 @@ private static List getExceptionsFromClose(PsiType type, GlobalSea } @Nonnull + @RequiredReadAction public static List getUnhandledExceptions(@Nonnull PsiThrowStatement throwStatement, @Nullable PsiElement topElement) { List unhandled = new SmartList<>(); for (PsiType type : getPreciseThrowTypes(throwStatement.getException())) { List types = - type instanceof PsiDisjunctionType ? ((PsiDisjunctionType)type).getDisjunctions() : Collections.singletonList(type); + type instanceof PsiDisjunctionType disjunctionType ? disjunctionType.getDisjunctions() : Collections.singletonList(type); for (PsiType subType : types) { - if (subType instanceof PsiClassType) { - PsiClassType classType = (PsiClassType)subType; - if (!isUncheckedException(classType) && !isHandled(throwStatement, classType, topElement)) { - unhandled.add(classType); - } + if (subType instanceof PsiClassType classType + && !isUncheckedException(classType) + && !isHandled(throwStatement, classType, topElement)) { + unhandled.add(classType); } } } @@ -698,17 +692,18 @@ public static List getUnhandledExceptions(@Nonnull PsiThrowStateme } @Nonnull + @RequiredReadAction private static List getPreciseThrowTypes(@Nullable PsiExpression expression) { expression = PsiUtil.skipParenthesizedExprDown(expression); - if (expression instanceof PsiReferenceExpression) { - final PsiElement target = ((PsiReferenceExpression)expression).resolve(); + if (expression instanceof PsiReferenceExpression refExpr) { + PsiElement target = refExpr.resolve(); if (target != null && PsiUtil.isCatchParameter(target)) { return ((PsiCatchSection)target.getParent()).getPreciseCatchTypes(); } } if (expression != null) { - final PsiType type = expression.getType(); + PsiType type = expression.getType(); if (type != null) { return Collections.singletonList(type); } @@ -727,7 +722,7 @@ public static List getUnhandledExceptions( if (isArrayClone(method, element)) { return Collections.emptyList(); } - final PsiClassType[] referencedTypes = method.getThrowsList().getReferencedTypes(); + PsiClassType[] referencedTypes = method.getThrowsList().getReferencedTypes(); return getUnhandledExceptions(element, topElement, substitutor, referencedTypes); } @@ -738,30 +733,20 @@ private static List getUnhandledExceptions( PsiClassType[] referencedTypes ) { if (referencedTypes.length > 0) { - List result = ContainerUtil.newArrayList(); + List result = new ArrayList<>(); for (PsiClassType referencedType : referencedTypes) { - final PsiType type = PsiClassImplUtil.correctType( + PsiType type = PsiClassImplUtil.correctType( GenericsUtil.eliminateWildcards(substitutor.substitute(referencedType), false), element.getResolveScope() ); - if (!(type instanceof PsiClassType)) { - continue; - } - PsiClassType classType = (PsiClassType)type; - PsiClass exceptionClass = ((PsiClassType)type).resolve(); - if (exceptionClass == null) { - continue; - } + if (type instanceof PsiClassType exceptionClassType + && exceptionClassType.resolve() != null + && !isUncheckedException(exceptionClassType) + && !isHandled(element, exceptionClassType, topElement)) { - if (isUncheckedException(classType)) { - continue; + result.add(exceptionClassType); } - if (isHandled(element, classType, topElement)) { - continue; - } - - result.add((PsiClassType)type); } return result; @@ -777,17 +762,15 @@ private static boolean isArrayClone(@Nonnull PsiMethod method, PsiElement elemen if (containingClass == null || !JavaClassNames.JAVA_LANG_OBJECT.equals(containingClass.getQualifiedName())) { return false; } - if (element instanceof PsiMethodReferenceExpression) { - final PsiMethodReferenceExpression methodCallExpression = (PsiMethodReferenceExpression)element; - final PsiExpression qualifierExpression = methodCallExpression.getQualifierExpression(); + if (element instanceof PsiMethodReferenceExpression methodRef) { + PsiExpression qualifierExpression = methodRef.getQualifierExpression(); return qualifierExpression != null && qualifierExpression.getType() instanceof PsiArrayType; } - if (!(element instanceof PsiMethodCallExpression)) { + if (!(element instanceof PsiMethodCallExpression methodCall)) { return false; } - PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression)element; - final PsiExpression qualifierExpression = methodCallExpression.getMethodExpression().getQualifierExpression(); + PsiExpression qualifierExpression = methodCall.getMethodExpression().getQualifierExpression(); return qualifierExpression != null && qualifierExpression.getType() instanceof PsiArrayType; } @@ -801,12 +784,12 @@ public static boolean isUncheckedException(@Nonnull PsiClass psiClass) { || InheritanceUtil.isInheritor(psiClass, JavaClassNames.JAVA_LANG_ERROR); } - public static boolean isUncheckedExceptionOrSuperclass(@Nonnull final PsiClassType type) { + public static boolean isUncheckedExceptionOrSuperclass(@Nonnull PsiClassType type) { return isGeneralExceptionType(type) || isUncheckedException(type); } - public static boolean isGeneralExceptionType(@Nonnull final PsiType type) { - final String canonicalText = type.getCanonicalText(); + public static boolean isGeneralExceptionType(@Nonnull PsiType type) { + String canonicalText = type.getCanonicalText(); return JavaClassNames.JAVA_LANG_THROWABLE.equals(canonicalText) || JavaClassNames.JAVA_LANG_EXCEPTION.equals(canonicalText); } @@ -827,49 +810,47 @@ private static boolean isHandled(@Nullable PsiElement element, @Nonnull PsiClass return true; } - final PsiElement parent = element.getParent(); + PsiElement parent = element.getParent(); - if (parent instanceof PsiMethod) { - PsiMethod method = (PsiMethod)parent; + if (parent instanceof PsiMethod method) { return isHandledByMethodThrowsClause(method, exceptionType); } - else if (parent instanceof PsiClass) { + else if (parent instanceof PsiClass psiClass) { // arguments to anon class constructor should be handled higher // like in void f() throws XXX { new AA(methodThrowingXXX()) { ... }; } - return parent instanceof PsiAnonymousClass && isHandled(parent, exceptionType, topElement); + return psiClass instanceof PsiAnonymousClass && isHandled(psiClass, exceptionType, topElement); } - else if (parent instanceof PsiLambdaExpression || parent instanceof PsiMethodReferenceExpression && element == ((PsiMethodReferenceExpression)parent).getReferenceNameElement()) { - final PsiType interfaceType = ((PsiFunctionalExpression)parent).getFunctionalInterfaceType(); + else if (parent instanceof PsiLambdaExpression lambda + || parent instanceof PsiMethodReferenceExpression methodRef && element == methodRef.getReferenceNameElement()) { + PsiType interfaceType = ((PsiFunctionalExpression)parent).getFunctionalInterfaceType(); return isDeclaredBySAMMethod(exceptionType, interfaceType); } - else if (parent instanceof PsiClassInitializer) { - if (((PsiClassInitializer)parent).hasModifierProperty(PsiModifier.STATIC)) { + else if (parent instanceof PsiClassInitializer classInitializer) { + if (classInitializer.isStatic()) { return false; } // anonymous class initializers can throw any exceptions if (!(parent.getParent() instanceof PsiAnonymousClass)) { // exception thrown from within class instance initializer must be handled in every class constructor // check each constructor throws exception or superclass (there must be at least one) - final PsiClass aClass = ((PsiClassInitializer)parent).getContainingClass(); + PsiClass aClass = classInitializer.getContainingClass(); return areAllConstructorsThrow(aClass, exceptionType); } } - else if (parent instanceof PsiTryStatement) { - PsiTryStatement tryStatement = (PsiTryStatement)parent; - if (tryStatement.getTryBlock() == element && isCaught(tryStatement, exceptionType)) { + else if (parent instanceof PsiTryStatement tryStmt) { + if (tryStmt.getTryBlock() == element && isCaught(tryStmt, exceptionType)) { return true; } - if (tryStatement.getResourceList() == element && isCaught(tryStatement, exceptionType)) { + if (tryStmt.getResourceList() == element && isCaught(tryStmt, exceptionType)) { return true; } - PsiCodeBlock finallyBlock = tryStatement.getFinallyBlock(); + PsiCodeBlock finallyBlock = tryStmt.getFinallyBlock(); if (element instanceof PsiCatchSection && finallyBlock != null && blockCompletesAbruptly(finallyBlock)) { // exception swallowed return true; } } - else if (parent instanceof JavaCodeFragment) { - JavaCodeFragment codeFragment = (JavaCodeFragment)parent; + else if (parent instanceof JavaCodeFragment codeFragment) { JavaCodeFragment.ExceptionHandler exceptionHandler = codeFragment.getExceptionHandler(); return exceptionHandler != null && exceptionHandler.isHandledException(exceptionType); } @@ -879,9 +860,9 @@ else if (PsiImplUtil.isInServerPage(parent) && parent instanceof PsiFile) { else if (parent instanceof PsiFile) { return false; } - else if (parent instanceof PsiField && ((PsiField)parent).getInitializer() == element) { - final PsiClass aClass = ((PsiField)parent).getContainingClass(); - if (aClass != null && !(aClass instanceof PsiAnonymousClass) && !((PsiField)parent).hasModifierProperty(PsiModifier.STATIC)) { + else if (parent instanceof PsiField field && field.getInitializer() == element) { + PsiClass aClass = field.getContainingClass(); + if (aClass != null && !(aClass instanceof PsiAnonymousClass) && !field.isStatic()) { // exceptions thrown in field initializers should be thrown in all class constructors return areAllConstructorsThrow(aClass, exceptionType); } @@ -898,8 +879,8 @@ else if (parent instanceof PsiField && ((PsiField)parent).getInitializer() == el private static boolean isDeclaredBySAMMethod(@Nonnull PsiClassType exceptionType, @Nullable PsiType interfaceType) { if (interfaceType != null) { - final PsiClassType.ClassResolveResult resolveResult = PsiUtil.resolveGenericsClassInType(interfaceType); - final PsiMethod interfaceMethod = LambdaUtil.getFunctionalInterfaceMethod(resolveResult); + PsiClassType.ClassResolveResult resolveResult = PsiUtil.resolveGenericsClassInType(interfaceType); + PsiMethod interfaceMethod = LambdaUtil.getFunctionalInterfaceMethod(resolveResult); if (interfaceMethod != null) { return isHandledByMethodThrowsClause( interfaceMethod, @@ -911,11 +892,11 @@ private static boolean isDeclaredBySAMMethod(@Nonnull PsiClassType exceptionType return true; } - private static boolean areAllConstructorsThrow(@Nullable final PsiClass aClass, @Nonnull PsiClassType exceptionType) { + private static boolean areAllConstructorsThrow(@Nullable PsiClass aClass, @Nonnull PsiClassType exceptionType) { if (aClass == null) { return false; } - final PsiMethod[] constructors = aClass.getConstructors(); + PsiMethod[] constructors = aClass.getConstructors(); boolean thrown = constructors.length != 0; for (PsiMethod constructor : constructors) { if (!isHandledByMethodThrowsClause(constructor, exceptionType)) { @@ -933,7 +914,7 @@ private static boolean isCaught(@Nonnull PsiTryStatement tryStatement, @Nonnull return true; } - final PsiParameter[] catchBlockParameters = tryStatement.getCatchBlockParameters(); + PsiParameter[] catchBlockParameters = tryStatement.getCatchBlockParameters(); for (PsiParameter parameter : catchBlockParameters) { PsiType paramType = parameter.getType(); if (paramType.isAssignableFrom(exceptionType)) { @@ -944,7 +925,7 @@ private static boolean isCaught(@Nonnull PsiTryStatement tryStatement, @Nonnull return false; } - private static boolean blockCompletesAbruptly(@Nonnull final PsiCodeBlock finallyBlock) { + private static boolean blockCompletesAbruptly(@Nonnull PsiCodeBlock finallyBlock) { try { ControlFlow flow = ControlFlowFactory.getInstance(finallyBlock.getProject()) .getControlFlow(finallyBlock, LocalsOrMyInstanceFieldsControlFlowPolicy.getInstance(), false); @@ -968,7 +949,7 @@ private static boolean isHandledByMethodThrowsClause( @Nonnull PsiClassType exceptionType, PsiSubstitutor substitutor ) { - final PsiClassType[] referencedTypes = method.getThrowsList().getReferencedTypes(); + PsiClassType[] referencedTypes = method.getThrowsList().getReferencedTypes(); return isHandledBy(exceptionType, referencedTypes, substitutor); } diff --git a/java-language-impl/src/main/java/com/intellij/java/language/impl/psi/impl/compiled/ClsClassImpl.java b/java-language-impl/src/main/java/com/intellij/java/language/impl/psi/impl/compiled/ClsClassImpl.java index c6601a7863..cdddfeea4f 100644 --- a/java-language-impl/src/main/java/com/intellij/java/language/impl/psi/impl/compiled/ClsClassImpl.java +++ b/java-language-impl/src/main/java/com/intellij/java/language/impl/psi/impl/compiled/ClsClassImpl.java @@ -21,7 +21,6 @@ import consulo.annotation.access.RequiredReadAction; import consulo.application.dumb.IndexNotReadyException; import consulo.application.util.Queryable; -import consulo.component.extension.Extensions; import consulo.content.scope.SearchScope; import consulo.java.language.impl.psi.augment.JavaEnumAugmentProvider; import consulo.java.language.module.util.JavaClassNames; @@ -37,7 +36,6 @@ import consulo.util.lang.Pair; import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; -import org.jetbrains.annotations.NonNls; import java.util.*; @@ -49,16 +47,16 @@ public class ClsClassImpl extends ClsMemberImpl> implements PsiE private final ClassInnerStuffCache myInnersCache = new ClassInnerStuffCache(this); - public ClsClassImpl(final PsiClassStub stub) { + public ClsClassImpl(PsiClassStub stub) { super(stub); putUserData(JavaEnumAugmentProvider.FLAG, Boolean.TRUE); } - @RequiredReadAction - @Override @Nonnull + @Override + @RequiredReadAction public PsiElement[] getChildren() { - List children = ContainerUtil.newArrayList(); + List children = new ArrayList<>(); ContainerUtil.addAll( children, getChildren(getDocComment(), getModifierListInternal(), getNameIdentifier(), getExtendsList(), getImplementsList()) @@ -88,12 +86,12 @@ public String getQualifiedName() { private boolean isLocalClass() { PsiClassStub stub = getStub(); - return stub instanceof PsiClassStubImpl && ((PsiClassStubImpl)stub).isLocalClassInner(); + return stub instanceof PsiClassStubImpl classStub && classStub.isLocalClassInner(); } private boolean isAnonymousClass() { PsiClassStub stub = getStub(); - return stub instanceof PsiClassStubImpl && ((PsiClassStubImpl)stub).isAnonymousInner(); + return stub instanceof PsiClassStubImpl classStub && classStub.isAnonymousInner(); } private boolean isAnonymousOrLocalClass() { @@ -179,8 +177,7 @@ public PsiClassType[] getSuperTypes() { @Override public PsiClass getContainingClass() { - PsiElement parent = getParent(); - return parent instanceof PsiClass ? (PsiClass)parent : null; + return getParent() instanceof PsiClass containingClass ? containingClass : null; } @Override @@ -235,7 +232,7 @@ public List getOwnInnerClasses() { int anonymousOrLocalClassesCount = 0; for (PsiClass aClass : classes) { - if (aClass instanceof ClsClassImpl && ((ClsClassImpl)aClass).isAnonymousOrLocalClass()) { + if (aClass instanceof ClsClassImpl clsClass && clsClass.isAnonymousOrLocalClass()) { ++anonymousOrLocalClassesCount; } } @@ -245,7 +242,7 @@ public List getOwnInnerClasses() { ArrayList result = new ArrayList<>(classes.length - anonymousOrLocalClassesCount); for (PsiClass aClass : classes) { - if (!(aClass instanceof ClsClassImpl) || !((ClsClassImpl)aClass).isAnonymousOrLocalClass()) { + if (!(aClass instanceof ClsClassImpl clsClass) || !clsClass.isAnonymousOrLocalClass()) { result.add(aClass); } } @@ -326,14 +323,15 @@ public boolean isDeprecated() { return getStub().isDeprecated() || PsiImplUtil.isDeprecatedByAnnotation(this); } + @RequiredReadAction public String getSourceFileName() { - final String sfn = getStub().getSourceFileName(); + String sfn = getStub().getSourceFileName(); return sfn != null ? sfn : obtainSourceFileNameFromClassFileName(); } - @NonNls + @RequiredReadAction private String obtainSourceFileNameFromClassFileName() { - final String name = getContainingFile().getName(); + String name = getContainingFile().getName(); int i = name.indexOf('$'); if (i < 0) { i = name.indexOf('.'); @@ -370,7 +368,7 @@ public boolean isEnum() { } @Override - public void appendMirrorText(final int indentLevel, @Nonnull @NonNls final StringBuilder buffer) { + public void appendMirrorText(int indentLevel, @Nonnull StringBuilder buffer) { appendText(getDocComment(), indentLevel, buffer, NEXT_LINE); appendText(getModifierListInternal(), indentLevel, buffer); @@ -469,8 +467,7 @@ public void setMirror(@Nonnull TreeElement element) throws InvalidMirrorExceptio setMirror(getExtendsList(), mirror.getExtendsList()); setMirror(getImplementsList(), mirror.getImplementsList()); - if (mirror instanceof PsiExtensibleClass) { - PsiExtensibleClass extMirror = (PsiExtensibleClass)mirror; + if (mirror instanceof PsiExtensibleClass extMirror) { setMirrors(getOwnFields(), extMirror.getOwnFields()); setMirrors(getOwnMethods(), extMirror.getOwnMethods()); setMirrors(getOwnInnerClasses(), extMirror.getOwnInnerClasses()); @@ -484,20 +481,21 @@ public void setMirror(@Nonnull TreeElement element) throws InvalidMirrorExceptio @Override public void accept(@Nonnull PsiElementVisitor visitor) { - if (visitor instanceof JavaElementVisitor) { - ((JavaElementVisitor)visitor).visitClass(this); + if (visitor instanceof JavaElementVisitor javaElementVisitor) { + javaElementVisitor.visitClass(this); } else { visitor.visitElement(this); } } - @NonNls + @Override public String toString() { return "PsiClass:" + getName(); } @Override + @RequiredReadAction public boolean processDeclarations( @Nonnull PsiScopeProcessor processor, @Nonnull ResolveState state, @@ -505,7 +503,7 @@ public boolean processDeclarations( @Nonnull PsiElement place ) { LanguageLevel level = - processor instanceof MethodsProcessor ? ((MethodsProcessor)processor).getLanguageLevel() : PsiUtil.getLanguageLevel(place); + processor instanceof MethodsProcessor methodsProcessor ? methodsProcessor.getLanguageLevel() : PsiUtil.getLanguageLevel(place); return PsiClassImplUtil.processDeclarationsInClass(this, processor, state, null, lastParent, place, level, false); } @@ -525,20 +523,21 @@ public boolean isInheritor(@Nonnull PsiClass baseClass, boolean checkDeep) { } @Nullable + @RequiredReadAction public PsiClass getSourceMirrorClass() { - final PsiClass delegate = getUserData(DELEGATE_KEY); - if (delegate instanceof ClsClassImpl) { - return ((ClsClassImpl)delegate).getSourceMirrorClass(); + PsiClass delegate = getUserData(DELEGATE_KEY); + if (delegate instanceof ClsClassImpl clsClass) { + return clsClass.getSourceMirrorClass(); } - final String name = getName(); - final PsiElement parent = getParent(); + String name = getName(); + PsiElement parent = getParent(); if (parent instanceof PsiFile) { - if (!(parent instanceof PsiClassOwner)) { + if (!(parent instanceof PsiClassOwner classOwner)) { return null; } - PsiClassOwner fileNavigationElement = (PsiClassOwner)parent.getNavigationElement(); + PsiClassOwner fileNavigationElement = (PsiClassOwner)classOwner.getNavigationElement(); if (fileNavigationElement == parent) { return null; } @@ -569,10 +568,11 @@ else if (parent != null) { return null; } - @Override @Nonnull + @Override + @RequiredReadAction public PsiElement getNavigationElement() { - for (ClsCustomNavigationPolicy navigationPolicy : Extensions.getExtensions(ClsCustomNavigationPolicy.EP_NAME)) { + for (ClsCustomNavigationPolicy navigationPolicy : ClsCustomNavigationPolicy.EP_NAME.getExtensions()) { try { PsiElement navigationElement = navigationPolicy.getNavigationElement(this); if (navigationElement != null) { @@ -590,12 +590,8 @@ public PsiElement getNavigationElement() { } if ("package-info".equals(getName())) { - PsiElement parent = getParent(); - if (parent instanceof ClsFileImpl) { - PsiElement sourceFile = parent.getNavigationElement(); - if (sourceFile instanceof PsiJavaFile) { - return sourceFile; - } + if (getParent() instanceof ClsFileImpl clsFile && clsFile.getNavigationElement() instanceof PsiJavaFile javaFile) { + return javaFile; } } } @@ -611,7 +607,7 @@ public ItemPresentation getPresentation() { } @Override - public boolean isEquivalentTo(final PsiElement another) { + public boolean isEquivalentTo(PsiElement another) { return PsiClassImplUtil.isClassEquivalentTo(this, another); } @@ -633,10 +629,9 @@ public PsiRecordComponent[] getRecordComponents() { return header == null ? PsiRecordComponent.EMPTY_ARRAY : header.getRecordComponents(); } - @Override - public @Nullable - PsiRecordHeader getRecordHeader() { + @Override + public PsiRecordHeader getRecordHeader() { PsiRecordHeaderStub headerStub = getStub().findChildStubByType(JavaStubElementTypes.RECORD_HEADER); return headerStub == null ? null : headerStub.getPsi(); } diff --git a/java-language-impl/src/main/java/com/intellij/java/language/impl/psi/impl/compiled/ClsFieldImpl.java b/java-language-impl/src/main/java/com/intellij/java/language/impl/psi/impl/compiled/ClsFieldImpl.java index e7b38a2b84..6e6ba5cc40 100644 --- a/java-language-impl/src/main/java/com/intellij/java/language/impl/psi/impl/compiled/ClsFieldImpl.java +++ b/java-language-impl/src/main/java/com/intellij/java/language/impl/psi/impl/compiled/ClsFieldImpl.java @@ -19,10 +19,10 @@ import com.intellij.java.language.impl.psi.impl.PsiConstantEvaluationHelperImpl; import com.intellij.java.language.impl.psi.impl.PsiImplUtil; import com.intellij.java.language.impl.psi.impl.PsiVariableEx; -import com.intellij.java.language.impl.psi.impl.cache.TypeInfo; import com.intellij.java.language.impl.psi.impl.java.stubs.JavaStubElementTypes; import com.intellij.java.language.impl.psi.impl.java.stubs.PsiFieldStub; import com.intellij.java.language.psi.*; +import consulo.annotation.access.RequiredReadAction; import consulo.application.dumb.IndexNotReadyException; import consulo.component.extension.Extensions; import consulo.content.scope.SearchScope; @@ -52,7 +52,7 @@ public ClsFieldImpl(@Nonnull PsiFieldStub stub) { super(stub); myTypeElement = LazyValue.atomicNotNull(() -> { PsiFieldStub s = getStub(); - String typeText = TypeInfo.createTypeText(s.getType()); + String typeText = s.getType().text(); assert typeText != null : s; return new ClsTypeElementImpl(ClsFieldImpl.this, typeText, ClsTypeElementImpl.VARIANCE_NONE); }); @@ -65,8 +65,9 @@ public ClsFieldImpl(@Nonnull PsiFieldStub stub) { }); } - @Override @Nonnull + @Override + @RequiredReadAction public PsiElement[] getChildren() { return getChildren(getDocComment(), getModifierList(), getTypeElement(), getNameIdentifier()); } @@ -165,6 +166,7 @@ public void normalizeDeclaration() throws IncorrectOperationException { } @Override + @RequiredReadAction public void appendMirrorText(int indentLevel, @Nonnull StringBuilder buffer) { appendText(getDocComment(), indentLevel, buffer, NEXT_LINE); appendText(getModifierList(), indentLevel, buffer, ""); @@ -193,16 +195,17 @@ public void setMirror(@Nonnull TreeElement element) throws InvalidMirrorExceptio @Override public void accept(@Nonnull PsiElementVisitor visitor) { - if (visitor instanceof JavaElementVisitor) { - ((JavaElementVisitor)visitor).visitField(this); + if (visitor instanceof JavaElementVisitor elementVisitor) { + elementVisitor.visitField(this); } else { visitor.visitElement(this); } } - @Override @Nonnull + @Override + @RequiredReadAction @SuppressWarnings({ "Duplicates", "deprecation" @@ -240,12 +243,13 @@ public void setInitializer(PsiExpression initializer) throws IncorrectOperationE } @Override - public boolean isEquivalentTo(final PsiElement another) { + public boolean isEquivalentTo(PsiElement another) { return PsiClassImplUtil.isFieldEquivalentTo(this, another); } - @Override @Nonnull + @Override + @RequiredReadAction public SearchScope getUseScope() { return PsiImplUtil.getMemberUseScope(this); } diff --git a/java-language-impl/src/main/java/com/intellij/java/language/impl/psi/impl/compiled/ClsFileImpl.java b/java-language-impl/src/main/java/com/intellij/java/language/impl/psi/impl/compiled/ClsFileImpl.java index 040a9a9f8c..a1e4dfc0ef 100644 --- a/java-language-impl/src/main/java/com/intellij/java/language/impl/psi/impl/compiled/ClsFileImpl.java +++ b/java-language-impl/src/main/java/com/intellij/java/language/impl/psi/impl/compiled/ClsFileImpl.java @@ -62,7 +62,6 @@ import consulo.virtualFileSystem.VirtualFile; import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; -import org.jetbrains.annotations.NonNls; import java.io.IOException; import java.lang.ref.Reference; @@ -135,13 +134,15 @@ public PsiElement[] getChildren() { return module != null ? new PsiElement[]{module} : getClasses(); } - @Override @Nonnull + @Override + @RequiredReadAction public PsiClass[] getClasses() { return getStub().getClasses(); } @Override + @RequiredReadAction public PsiPackageStatement getPackageStatement() { ClsPackageStatementImpl statement = myPackageStatement; if (statement == null) { @@ -161,8 +162,8 @@ public PsiPackageStatement getPackageStatement() { private static String findPackageName(PsiClassHolderFileStub stub) { String packageName = null; - if (stub instanceof PsiJavaFileStub) { - packageName = ((PsiJavaFileStub)stub).getPackageName(); + if (stub instanceof PsiJavaFileStub javaFileStub) { + packageName = javaFileStub.getPackageName(); } else { PsiClass[] psiClasses = stub.getClasses(); @@ -180,15 +181,16 @@ private static String findPackageName(PsiClassHolderFileStub stub) { return !StringUtil.isEmpty(packageName) ? packageName : null; } - @Override @Nonnull + @Override + @RequiredReadAction public String getPackageName() { PsiPackageStatement statement = getPackageStatement(); return statement == null ? "" : statement.getPackageName(); } @Override - public void setPackageName(final String packageName) throws IncorrectOperationException { + public void setPackageName(String packageName) throws IncorrectOperationException { throw new IncorrectOperationException("Cannot set package name for compiled files"); } @@ -237,12 +239,13 @@ public PsiJavaCodeReferenceElement findImportReferenceTo(PsiClass aClass) { return null; } - @Override @Nonnull + @Override + @RequiredReadAction public LanguageLevel getLanguageLevel() { PsiClassHolderFileStub stub = getStub(); - if (stub instanceof PsiJavaFileStub) { - LanguageLevel level = ((PsiJavaFileStub)stub).getLanguageLevel(); + if (stub instanceof PsiJavaFileStub javaFileStub) { + LanguageLevel level = javaFileStub.getLanguageLevel(); if (level != null) { return level; } @@ -255,7 +258,7 @@ public LanguageLevel getLanguageLevel() { @Override public PsiJavaModule getModuleDeclaration() { PsiClassHolderFileStub stub = getStub(); - return stub instanceof PsiJavaFileStub ? ((PsiJavaFileStub)stub).getModule() : null; + return stub instanceof PsiJavaFileStub javaFileStub ? javaFileStub.getModule() : null; } @RequiredWriteAction @@ -308,11 +311,10 @@ public void setMirror(@Nonnull TreeElement element) throws InvalidMirrorExceptio @RequiredReadAction private void setFileMirror(@Nonnull TreeElement element) { PsiElement mirrorElement = SourceTreeToPsiMap.treeToPsiNotNull(element); - if (!(mirrorElement instanceof PsiJavaFile)) { + if (!(mirrorElement instanceof PsiJavaFile mirrorFile)) { throw new InvalidMirrorException("Unexpected mirror file: " + mirrorElement); } - PsiJavaFile mirrorFile = (PsiJavaFile)mirrorElement; PsiJavaModule module = getModuleDeclaration(); if (module != null) { ClsElementImpl.setMirror(module, mirrorFile.getModuleDeclaration()); @@ -360,7 +362,7 @@ public PsiElement getMirror() { String fileName = (classes.length > 0 ? classes[0].getName() : file.getNameWithoutExtension()) + JavaFileType.DOT_DEFAULT_EXTENSION; - final Document document = FileDocumentManager.getInstance().getDocument(file); + Document document = FileDocumentManager.getInstance().getDocument(file); assert document != null : file.getUrl(); CharSequence mirrorText = document.getImmutableCharSequence(); @@ -371,7 +373,7 @@ public PsiElement getMirror() { mirrorTreeElement = SourceTreeToPsiMap.psiToTreeNotNull(mirror); try { - final TreeElement finalMirrorTreeElement = mirrorTreeElement; + TreeElement finalMirrorTreeElement = mirrorTreeElement; ProgressManager.getInstance().executeNonCancelableSection(() -> { setFileMirror(finalMirrorTreeElement); putUserData(CLS_DOCUMENT_LINK_KEY, document); @@ -428,41 +430,40 @@ public PsiFile getDecompiledPsiFile() { @Override public void accept(@Nonnull PsiElementVisitor visitor) { - if (visitor instanceof JavaElementVisitor) { - ((JavaElementVisitor)visitor).visitJavaFile(this); + if (visitor instanceof JavaElementVisitor javaElementVisitor) { + javaElementVisitor.visitJavaFile(this); } else { visitor.visitFile(this); } } - @RequiredReadAction @Override - @NonNls + @RequiredReadAction public String toString() { return "PsiFile:" + getName(); } - @RequiredReadAction @Override + @RequiredReadAction public final TextRange getTextRange() { return TextRange.create(0, getTextLength()); } - @RequiredReadAction @Override + @RequiredReadAction public final int getStartOffsetInParent() { return 0; } - @RequiredReadAction @Override + @RequiredReadAction public final PsiElement findElementAt(int offset) { return getMirror().findElementAt(offset); } - @RequiredReadAction @Override + @RequiredReadAction public PsiReference findReferenceAt(int offset) { return getMirror().findReferenceAt(offset); } @@ -472,20 +473,21 @@ public final int getTextOffset() { return 0; } - @RequiredReadAction - @Override @Nonnull + @Override + @RequiredReadAction public char[] textToCharArray() { return getMirror().textToCharArray(); } - @RequiredReadAction @Nonnull + @RequiredReadAction public PsiClassHolderFileStub getStub() { return (PsiClassHolderFileStub)getStubTree().getRoot(); } @Override + @RequiredReadAction public boolean processDeclarations( @Nonnull PsiScopeProcessor processor, @Nonnull ResolveState state, @@ -493,9 +495,9 @@ public boolean processDeclarations( @Nonnull PsiElement place ) { processor.handleEvent(PsiScopeProcessor.Event.SET_DECLARATION_HOLDER, this); - final ElementClassHint classHint = processor.getHint(ElementClassHint.KEY); + ElementClassHint classHint = processor.getHint(ElementClassHint.KEY); if (classHint == null || classHint.shouldProcess(ElementClassHint.DeclarationKind.CLASS)) { - final PsiClass[] classes = getClasses(); + PsiClass[] classes = getClasses(); for (PsiClass aClass : classes) { if (!processor.execute(aClass, state)) { return false; @@ -585,8 +587,8 @@ public void putInfo(@Nonnull Map info) { @Nonnull public static CharSequence decompile(@Nonnull VirtualFile file) { PsiManager manager = PsiManager.getInstance(ProjectManager.getInstance().getDefaultProject()); - final ClsFileImpl clsFile = new ClsFileImpl(new ClassFileViewProvider(manager, file), true); - final StringBuilder buffer = new StringBuilder(); + ClsFileImpl clsFile = new ClsFileImpl(new ClassFileViewProvider(manager, file), true); + StringBuilder buffer = new StringBuilder(); Application.get().runReadAction(() -> clsFile.appendMirrorText(buffer)); return buffer; } diff --git a/java-language-impl/src/main/java/com/intellij/java/language/impl/psi/impl/compiled/ClsMethodImpl.java b/java-language-impl/src/main/java/com/intellij/java/language/impl/psi/impl/compiled/ClsMethodImpl.java index a26e151dd5..1bef989411 100644 --- a/java-language-impl/src/main/java/com/intellij/java/language/impl/psi/impl/compiled/ClsMethodImpl.java +++ b/java-language-impl/src/main/java/com/intellij/java/language/impl/psi/impl/compiled/ClsMethodImpl.java @@ -18,7 +18,6 @@ import com.intellij.java.language.impl.psi.impl.PsiClassImplUtil; import com.intellij.java.language.impl.psi.impl.PsiImplUtil; import com.intellij.java.language.impl.psi.impl.PsiSuperMethodImplUtil; -import com.intellij.java.language.impl.psi.impl.cache.TypeInfo; import com.intellij.java.language.impl.psi.impl.java.stubs.JavaStubElementTypes; import com.intellij.java.language.impl.psi.impl.java.stubs.PsiMethodStub; import com.intellij.java.language.impl.psi.scope.util.PsiScopesUtil; @@ -26,11 +25,11 @@ import com.intellij.java.language.psi.util.MethodSignature; import com.intellij.java.language.psi.util.MethodSignatureBackedByPsiMethod; import com.intellij.java.language.psi.util.MethodSignatureUtil; +import consulo.annotation.access.RequiredReadAction; import consulo.application.dumb.IndexNotReadyException; import consulo.application.util.AtomicNotNullLazyValue; import consulo.application.util.CachedValueProvider; import consulo.application.util.NotNullLazyValue; -import consulo.component.extension.Extensions; import consulo.content.scope.SearchScope; import consulo.language.content.FileIndexFacade; import consulo.language.impl.ast.TreeElement; @@ -53,22 +52,22 @@ public class ClsMethodImpl extends ClsMemberImpl implements PsiAn private final NotNullLazyValue myReturnType; private final NotNullLazyValue myDefaultValue; - public ClsMethodImpl(final PsiMethodStub stub) { + public ClsMethodImpl(PsiMethodStub stub) { super(stub); - myReturnType = isConstructor() ? null : new AtomicNotNullLazyValue() { + myReturnType = isConstructor() ? null : new AtomicNotNullLazyValue<>() { @Nonnull @Override protected PsiTypeElement compute() { PsiMethodStub stub = getStub(); - String typeText = TypeInfo.createTypeText(stub.getReturnTypeText()); + String typeText = stub.getReturnTypeText().text(); assert typeText != null : stub; return new ClsTypeElementImpl(ClsMethodImpl.this, typeText, ClsTypeElementImpl.VARIANCE_NONE); } }; final String text = getStub().getDefaultValueText(); - myDefaultValue = StringUtil.isEmptyOrSpaces(text) ? null : new AtomicNotNullLazyValue() { + myDefaultValue = StringUtil.isEmptyOrSpaces(text) ? null : new AtomicNotNullLazyValue<>() { @Nonnull @Override protected PsiAnnotationMemberValue compute() { @@ -77,8 +76,9 @@ protected PsiAnnotationMemberValue compute() { }; } - @Override @Nonnull + @Override + @RequiredReadAction public PsiElement[] getChildren() { return getChildren( getDocComment(), @@ -263,8 +263,8 @@ public void setMirror(@Nonnull TreeElement element) throws InvalidMirrorExceptio @Override public void accept(@Nonnull PsiElementVisitor visitor) { - if (visitor instanceof JavaElementVisitor) { - ((JavaElementVisitor)visitor).visitMethod(this); + if (visitor instanceof JavaElementVisitor javaElementVisitor) { + javaElementVisitor.visitMethod(this); } else { visitor.visitElement(this); @@ -287,7 +287,7 @@ public boolean processDeclarations( return false; } - final PsiParameter[] parameters = getParameterList().getParameters(); + PsiParameter[] parameters = getParameterList().getParameters(); for (PsiParameter parameter : parameters) { if (!processor.execute(parameter, state)) { return false; @@ -311,6 +311,7 @@ public PsiMethod getSourceMirrorMethod() { } @Nullable + @RequiredReadAction private PsiMethod calcSourceMirrorMethod() { PsiClass sourceClassMirror = ((ClsClassImpl)getParent()).getSourceMirrorClass(); if (sourceClassMirror == null) { @@ -327,7 +328,7 @@ private PsiMethod calcSourceMirrorMethod() { @Override @Nonnull public PsiElement getNavigationElement() { - for (ClsCustomNavigationPolicy customNavigationPolicy : Extensions.getExtensions(ClsCustomNavigationPolicy.EP_NAME)) { + for (ClsCustomNavigationPolicy customNavigationPolicy : ClsCustomNavigationPolicy.EP_NAME.getExtensions()) { try { PsiElement navigationElement = customNavigationPolicy.getNavigationElement(this); if (navigationElement != null) { @@ -339,7 +340,7 @@ public PsiElement getNavigationElement() { } try { - final PsiMethod method = getSourceMirrorMethod(); + PsiMethod method = getSourceMirrorMethod(); return method != null ? method.getNavigationElement() : this; } catch (IndexNotReadyException e) { @@ -364,12 +365,13 @@ public ItemPresentation getPresentation() { } @Override - public boolean isEquivalentTo(final PsiElement another) { + public boolean isEquivalentTo(PsiElement another) { return PsiClassImplUtil.isMethodEquivalentTo(this, another); } - @Override @Nonnull + @Override + @RequiredReadAction public SearchScope getUseScope() { return PsiImplUtil.getMemberUseScope(this); } diff --git a/java-language-impl/src/main/java/com/intellij/java/language/impl/psi/impl/compiled/ClsRepositoryPsiElement.java b/java-language-impl/src/main/java/com/intellij/java/language/impl/psi/impl/compiled/ClsRepositoryPsiElement.java index 5519e51467..6cd241ea54 100644 --- a/java-language-impl/src/main/java/com/intellij/java/language/impl/psi/impl/compiled/ClsRepositoryPsiElement.java +++ b/java-language-impl/src/main/java/com/intellij/java/language/impl/psi/impl/compiled/ClsRepositoryPsiElement.java @@ -15,6 +15,7 @@ */ package com.intellij.java.language.impl.psi.impl.compiled; +import consulo.annotation.access.RequiredReadAction; import consulo.language.psi.*; import consulo.language.psi.stub.IStubElementType; import consulo.language.psi.stub.PsiFileStub; @@ -27,10 +28,11 @@ public abstract class ClsRepositoryPsiElement extends ClsElementImpl implements StubBasedPsiElement { private final T myStub; - protected ClsRepositoryPsiElement(final T stub) { + protected ClsRepositoryPsiElement(T stub) { myStub = stub; } + @Nonnull @Override public IStubElementType getElementType() { return myStub.getStubType(); @@ -41,9 +43,10 @@ public PsiElement getParent() { return myStub.getParentStub().getPsi(); } + @Nonnull @Override public PsiManager getManager() { - final PsiFile file = getContainingFile(); + PsiFile file = getContainingFile(); if (file == null) { throw new PsiInvalidElementAccessException(this); } @@ -69,10 +72,11 @@ public boolean isPhysical() { return getContainingFile().isPhysical(); } - @Override @Nonnull + @Override + @RequiredReadAction public PsiElement[] getChildren() { - final List stubs = getStub().getChildrenStubs(); + List stubs = getStub().getChildrenStubs(); PsiElement[] children = new PsiElement[stubs.size()]; for (int i = 0; i < stubs.size(); i++) { children[i] = ((StubElement)stubs.get(i)).getPsi(); @@ -81,8 +85,9 @@ public PsiElement[] getChildren() { } @Override + @RequiredReadAction public PsiElement getFirstChild() { - final List children = getStub().getChildrenStubs(); + List children = getStub().getChildrenStubs(); if (children.isEmpty()) { return null; } @@ -90,8 +95,9 @@ public PsiElement getFirstChild() { } @Override + @RequiredReadAction public PsiElement getLastChild() { - final List children = getStub().getChildrenStubs(); + List children = getStub().getChildrenStubs(); if (children.isEmpty()) { return null; } @@ -99,9 +105,10 @@ public PsiElement getLastChild() { } @Override + @RequiredReadAction public PsiElement getNextSibling() { - final PsiElement[] psiElements = getParent().getChildren(); - final int i = ArrayUtil.indexOf(psiElements, this); + PsiElement[] psiElements = getParent().getChildren(); + int i = ArrayUtil.indexOf(psiElements, this); if (i < 0 || i >= psiElements.length - 1) { return null; } @@ -110,9 +117,10 @@ public PsiElement getNextSibling() { @Override + @RequiredReadAction public PsiElement getPrevSibling() { - final PsiElement[] psiElements = getParent().getChildren(); - final int i = ArrayUtil.indexOf(psiElements, this); + PsiElement[] psiElements = getParent().getChildren(); + int i = ArrayUtil.indexOf(psiElements, this); if (i < 1) { return null; } diff --git a/java-language-impl/src/main/java/com/intellij/java/language/impl/psi/impl/smartPointers/SmartTypePointerManagerImpl.java b/java-language-impl/src/main/java/com/intellij/java/language/impl/psi/impl/smartPointers/SmartTypePointerManagerImpl.java index 1088688bf1..21381ecc20 100644 --- a/java-language-impl/src/main/java/com/intellij/java/language/impl/psi/impl/smartPointers/SmartTypePointerManagerImpl.java +++ b/java-language-impl/src/main/java/com/intellij/java/language/impl/psi/impl/smartPointers/SmartTypePointerManagerImpl.java @@ -19,19 +19,18 @@ import com.intellij.java.language.impl.psi.impl.source.PsiImmediateClassType; import com.intellij.java.language.psi.*; import com.intellij.java.language.psi.util.PsiUtil; +import consulo.annotation.access.RequiredReadAction; import consulo.annotation.component.ServiceImpl; -import consulo.language.psi.PsiElement; import consulo.language.psi.PsiManager; import consulo.language.psi.SmartPointerManager; import consulo.language.psi.SmartPsiElementPointer; import consulo.project.Project; import consulo.util.collection.ContainerUtil; +import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; import jakarta.inject.Inject; import jakarta.inject.Singleton; -import jakarta.annotation.Nonnull; - import java.util.*; import java.util.stream.Stream; @@ -41,18 +40,13 @@ @Singleton @ServiceImpl public class SmartTypePointerManagerImpl extends SmartTypePointerManager { - private static final SmartTypePointer NULL_POINTER = new SmartTypePointer() { - @Override - public PsiType getType() { - return null; - } - }; + private static final SmartTypePointer NULL_POINTER = () -> null; private final SmartPointerManager myPsiPointerManager; private final Project myProject; @Inject - public SmartTypePointerManagerImpl(final SmartPointerManager psiPointerManager, final Project project) { + public SmartTypePointerManagerImpl(SmartPointerManager psiPointerManager, Project project) { myPsiPointerManager = psiPointerManager; myProject = project; } @@ -60,7 +54,7 @@ public SmartTypePointerManagerImpl(final SmartPointerManager psiPointerManager, @Override @Nonnull public SmartTypePointer createSmartTypePointer(@Nonnull PsiType type) { - final SmartTypePointer pointer = type.accept(new SmartTypeCreatingVisitor()); + SmartTypePointer pointer = type.accept(new SmartTypeCreatingVisitor()); return pointer != null ? pointer : NULL_POINTER; } @@ -88,7 +82,7 @@ public ArrayTypePointer(@Nonnull PsiArrayType type, @Nonnull SmartTypePointer co @Nullable @Override protected PsiArrayType calcType() { - final PsiType type = myComponentTypePointer.getType(); + PsiType type = myComponentTypePointer.getType(); return type == null ? null : new PsiArrayType(type); } } @@ -111,7 +105,7 @@ protected PsiWildcardType calcType() { return PsiWildcardType.createUnbounded(myManager); } else { - final PsiType type = myBoundPointer.getType(); + PsiType type = myBoundPointer.getType(); assert type != null : myBoundPointer; if (myIsExtending) { return PsiWildcardType.createExtends(myManager, type); @@ -142,13 +136,13 @@ private static class ClassTypePointer extends TypePointerBase { } @Override + @RequiredReadAction protected PsiClassType calcType() { - final PsiElement classElement = myClass.getElement(); - if (!(classElement instanceof PsiClass)) { + if (!(myClass.getElement() instanceof PsiClass classElement)) { return null; } Map resurrected = new HashMap<>(); - final Set, SmartTypePointer>> set = myMap.entrySet(); + Set, SmartTypePointer>> set = myMap.entrySet(); for (Map.Entry, SmartTypePointer> entry : set) { PsiTypeParameter element = entry.getKey().getElement(); if (element != null) { @@ -156,16 +150,18 @@ protected PsiClassType calcType() { resurrected.put(element, typePointer == null ? null : typePointer.getType()); } } - for (PsiTypeParameter typeParameter : PsiUtil.typeParametersIterable((PsiClass)classElement)) { + for (PsiTypeParameter typeParameter : PsiUtil.typeParametersIterable(classElement)) { if (!resurrected.containsKey(typeParameter)) { resurrected.put(typeParameter, null); } } - final PsiSubstitutor resurrectedSubstitutor = PsiSubstitutor.createSubstitutor(resurrected); + PsiSubstitutor resurrectedSubstitutor = PsiSubstitutor.createSubstitutor(resurrected); - PsiAnnotation[] resurrectedAnnotations = - Stream.of(myAnnotations).map(SmartPsiElementPointer::getElement).filter(Objects::nonNull).toArray(PsiAnnotation[]::new); - return new PsiImmediateClassType((PsiClass)classElement, resurrectedSubstitutor, myLevel, resurrectedAnnotations); + PsiAnnotation[] resurrectedAnnotations = Stream.of(myAnnotations) + .map(SmartPsiElementPointer::getElement) + .filter(Objects::nonNull) + .toArray(PsiAnnotation[]::new); + return new PsiImmediateClassType(classElement, resurrectedSubstitutor, myLevel, resurrectedAnnotations); } } @@ -179,7 +175,7 @@ private DisjunctionTypePointer(@Nonnull PsiDisjunctionType type) { @Override protected PsiDisjunctionType calcType() { - final List types = ContainerUtil.map(myPointers, SmartTypePointer::getType); + List types = ContainerUtil.map(myPointers, SmartTypePointer::getType); return new PsiDisjunctionType(types, PsiManager.getInstance(myProject)); } } @@ -192,31 +188,31 @@ public SmartTypePointer visitPrimitiveType(PsiPrimitiveType primitiveType) { @Override public SmartTypePointer visitArrayType(PsiArrayType arrayType) { - final SmartTypePointer componentTypePointer = arrayType.getComponentType().accept(this); + SmartTypePointer componentTypePointer = arrayType.getComponentType().accept(this); return componentTypePointer != null ? new ArrayTypePointer(arrayType, componentTypePointer) : null; } @Override public SmartTypePointer visitWildcardType(PsiWildcardType wildcardType) { - final PsiType bound = wildcardType.getBound(); - final SmartTypePointer boundPointer = bound == null ? null : bound.accept(this); + PsiType bound = wildcardType.getBound(); + SmartTypePointer boundPointer = bound == null ? null : bound.accept(this); return new WildcardTypePointer(wildcardType, boundPointer); } @Override public SmartTypePointer visitClassType(PsiClassType classType) { - final PsiClassType.ClassResolveResult resolveResult = classType.resolveGenerics(); - final PsiClass aClass = resolveResult.getElement(); + PsiClassType.ClassResolveResult resolveResult = classType.resolveGenerics(); + PsiClass aClass = resolveResult.getElement(); if (aClass == null) { return createClassReferenceTypePointer(classType); } - final PsiSubstitutor substitutor = resolveResult.getSubstitutor(); - final HashMap, SmartTypePointer> pointerMap = new HashMap<>(); - final Map map = new HashMap<>(); + PsiSubstitutor substitutor = resolveResult.getSubstitutor(); + HashMap, SmartTypePointer> pointerMap = new HashMap<>(); + Map map = new HashMap<>(); for (PsiTypeParameter typeParameter : PsiUtil.typeParametersIterable(aClass)) { - final PsiType substitutionResult = substitutor.substitute(typeParameter); + PsiType substitutionResult = substitutor.substitute(typeParameter); if (substitutionResult != null) { - final SmartPsiElementPointer pointer = + SmartPsiElementPointer pointer = myPsiPointerManager.createSmartPsiElementPointer(typeParameter); SmartTypePointer typePointer = substitutionResult.accept(this); pointerMap.put(pointer, typePointer); diff --git a/java-language-impl/src/main/java/com/intellij/java/language/impl/psi/impl/source/PsiClassReferenceType.java b/java-language-impl/src/main/java/com/intellij/java/language/impl/psi/impl/source/PsiClassReferenceType.java index c016e483f7..90ef12aac5 100644 --- a/java-language-impl/src/main/java/com/intellij/java/language/impl/psi/impl/source/PsiClassReferenceType.java +++ b/java-language-impl/src/main/java/com/intellij/java/language/impl/psi/impl/source/PsiClassReferenceType.java @@ -8,6 +8,7 @@ import com.intellij.java.language.psi.augment.PsiAugmentProvider; import com.intellij.java.language.psi.infos.PatternCandidateInfo; import com.intellij.java.language.psi.util.PsiUtil; +import consulo.annotation.access.RequiredReadAction; import consulo.language.psi.PsiElement; import consulo.language.psi.PsiInvalidElementAccessException; import consulo.language.psi.PsiManager; @@ -27,6 +28,7 @@ public class PsiClassReferenceType extends PsiClassType.Stub { private final ClassReferencePointer myReference; + @RequiredReadAction public PsiClassReferenceType(@Nonnull PsiJavaCodeReferenceElement reference, LanguageLevel level) { this(reference, level, collectAnnotations(reference)); } @@ -54,20 +56,22 @@ public PsiClassReferenceType( } @Nonnull + @RequiredReadAction private static PsiAnnotation[] collectAnnotations(PsiJavaCodeReferenceElement reference) { List result = null; for (PsiElement child = reference.getFirstChild(); child != null; child = child.getNextSibling()) { - if (child instanceof PsiAnnotation) { + if (child instanceof PsiAnnotation annotation) { if (result == null) { result = new SmartList<>(); } - result.add((PsiAnnotation)child); + result.add(annotation); } } return result == null ? PsiAnnotation.EMPTY_ARRAY : result.toArray(PsiAnnotation.EMPTY_ARRAY); } @Override + @RequiredReadAction public boolean isValid() { PsiJavaCodeReferenceElement reference = myReference.retrieveReference(); if (reference != null && reference.isValid()) { @@ -94,12 +98,14 @@ public GlobalSearchScope getResolveScope() { return getReference().getResolveScope(); } - @Override @Nonnull + @Override + @RequiredReadAction public PsiAnnotation[] getAnnotations() { return getAnnotations(true); } + @RequiredReadAction private PsiAnnotation[] getAnnotations(boolean merge) { PsiAnnotation[] annotations = super.getAnnotations(); @@ -122,10 +128,10 @@ private PsiAnnotation[] getAnnotations(boolean merge) { return annotations; } - @Override - public @Nonnull - LanguageLevel getLanguageLevel() { + @Override + @RequiredReadAction + public LanguageLevel getLanguageLevel() { if (myLanguageLevel != null) { return myLanguageLevel; } @@ -135,7 +141,7 @@ LanguageLevel getLanguageLevel() { @Override public @Nonnull - PsiClassType setLanguageLevel(final @Nonnull LanguageLevel languageLevel) { + PsiClassType setLanguageLevel(@Nonnull LanguageLevel languageLevel) { if (languageLevel.equals(myLanguageLevel)) { return this; } @@ -189,46 +195,44 @@ public boolean isPackagePrefixPackageReference() { @Override @Nullable public String getInferenceError() { - return myDelegate instanceof PatternCandidateInfo ? ((PatternCandidateInfo)myDelegate).getInferenceError() : null; + return myDelegate instanceof PatternCandidateInfo patternCandidateInfo ? patternCandidateInfo.getInferenceError() : null; } @Override public PsiClass getElement() { - final PsiElement element = myDelegate.getElement(); - return element instanceof PsiClass ? (PsiClass)element : null; + return myDelegate.getElement() instanceof PsiClass psiClass ? psiClass : null; } } - @Override @Nonnull + @Override public ClassResolveResult resolveGenerics() { PsiJavaCodeReferenceElement reference = getReference(); if (!reference.isValid()) { - if (reference instanceof LightClassTypeReference) { - PsiUtil.ensureValidType(((LightClassTypeReference)reference).getType()); + if (reference instanceof LightClassTypeReference lightClassTypeRef) { + PsiUtil.ensureValidType(lightClassTypeRef.getType()); } throw new PsiInvalidElementAccessException( reference, myReference.toString() + "; augmenters=" + PsiAugmentProvider.EP_NAME.getExtensionList() ); } - final JavaResolveResult result = reference.advancedResolve(false); + JavaResolveResult result = reference.advancedResolve(false); return result.getElement() == null ? ClassResolveResult.EMPTY : new DelegatingClassResolveResult(result); } - @Override @Nonnull + @Override + @RequiredReadAction public PsiClassType rawType() { PsiJavaCodeReferenceElement reference = getReference(); - PsiElement resolved = reference.resolve(); - if (resolved instanceof PsiClass) { - PsiClass aClass = (PsiClass)resolved; + if (reference.resolve() instanceof PsiClass aClass) { if (!PsiUtil.typeParametersIterable(aClass).iterator().hasNext()) { return this; } PsiManager manager = reference.getManager(); - final PsiElementFactory factory = JavaPsiFacade.getElementFactory(manager.getProject()); - final PsiSubstitutor rawSubstitutor = factory.createRawSubstitutor(aClass); + PsiElementFactory factory = JavaPsiFacade.getElementFactory(manager.getProject()); + PsiSubstitutor rawSubstitutor = factory.createRawSubstitutor(aClass); return new PsiImmediateClassType(aClass, rawSubstitutor, getLanguageLevel(), getAnnotationProvider()); } String qualifiedName = reference.getQualifiedName(); @@ -252,10 +256,10 @@ public PsiType[] getParameters() { return getReference().getTypeParameters(); } - @Override - public @Nonnull - String getPresentableText(boolean annotated) { + @Override + @RequiredReadAction + public String getPresentableText(boolean annotated) { PsiJavaCodeReferenceElement ref = getReference(); if (!annotated) { return PsiNameHelper.getPresentableText(ref); @@ -272,24 +276,24 @@ String getPresentableText(boolean annotated) { return PsiNameHelper.getPresentableText(ref.getReferenceName(), annotations, ref.getTypeParameters()); } - @Override - public @Nonnull - String getCanonicalText(boolean annotated) { + @Override + @RequiredReadAction + public String getCanonicalText(boolean annotated) { return getText(annotated); } - @Override - public @Nonnull - String getInternalCanonicalText() { + @Override + @RequiredReadAction + public String getInternalCanonicalText() { return getCanonicalText(true); } + @RequiredReadAction private String getText(boolean annotated) { PsiJavaCodeReferenceElement reference = getReference(); - if (reference instanceof PsiAnnotatedJavaCodeReferenceElement) { - PsiAnnotatedJavaCodeReferenceElement ref = (PsiAnnotatedJavaCodeReferenceElement)reference; + if (reference instanceof PsiAnnotatedJavaCodeReferenceElement ref) { PsiAnnotation[] annotations = annotated ? getAnnotations(false) : PsiAnnotation.EMPTY_ARRAY; return ref.getCanonicalText(annotated, annotations.length == 0 ? null : annotations); } diff --git a/java-language-impl/src/main/java/com/intellij/java/language/impl/psi/impl/source/resolve/graphInference/InferenceVariable.java b/java-language-impl/src/main/java/com/intellij/java/language/impl/psi/impl/source/resolve/graphInference/InferenceVariable.java index 4a76993b61..8d20a64ff7 100644 --- a/java-language-impl/src/main/java/com/intellij/java/language/impl/psi/impl/source/resolve/graphInference/InferenceVariable.java +++ b/java-language-impl/src/main/java/com/intellij/java/language/impl/psi/impl/source/resolve/graphInference/InferenceVariable.java @@ -22,7 +22,6 @@ import com.intellij.java.language.psi.util.TypeConversionUtil; import consulo.language.psi.PsiElement; import consulo.language.psi.util.PsiTreeUtil; - import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; @@ -39,7 +38,7 @@ public PsiTypeParameter getParameter() { } private boolean myThrownBound; - private final Map> myBounds = new HashMap>(); + private final Map> myBounds = new HashMap<>(); private final String myName; private PsiType myInstantiation = PsiType.NULL; @@ -62,22 +61,21 @@ public void setInstantiation(PsiType instantiation) { @Nonnull @Override public PsiClassType[] getExtendsListTypes() { - final List result = new ArrayList(); + List result = new ArrayList<>(); for (PsiType type : getBounds(InferenceBound.UPPER)) { - if (type instanceof PsiClassType) { - result.add((PsiClassType)type); + if (type instanceof PsiClassType classType) { + result.add(classType); } } return result.toArray(new PsiClassType[result.size()]); } public static void addBound(PsiType inferenceVariableType, PsiType boundType, InferenceBound inferenceBound, InferenceSession session) { - final InferenceVariable variable = session.getInferenceVariable(inferenceVariableType); + InferenceVariable variable = session.getInferenceVariable(inferenceVariableType); if (variable != null) { for (TypeAnnotationModifier modifier : TypeAnnotationModifier.EP_NAME.getExtensions()) { - if (boundType instanceof PsiClassType) { - final TypeAnnotationProvider annotationProvider = - modifier.modifyAnnotations(inferenceVariableType, (PsiClassType)boundType); + if (boundType instanceof PsiClassType boundClassType) { + TypeAnnotationProvider annotationProvider = modifier.modifyAnnotations(inferenceVariableType, boundClassType); if (annotationProvider != null) { boundType = boundType.annotate(annotationProvider); } @@ -94,7 +92,7 @@ public boolean addBound(PsiType classType, InferenceBound inferenceBound, @Nulla } List bounds = myBounds.get(inferenceBound); if (bounds == null) { - bounds = new ArrayList(); + bounds = new ArrayList<>(); myBounds.put(inferenceBound, bounds); } @@ -113,17 +111,17 @@ public boolean addBound(PsiType classType, InferenceBound inferenceBound, @Nulla } public List getBounds(InferenceBound inferenceBound) { - final List bounds = myBounds.get(inferenceBound); - return bounds != null ? new ArrayList(bounds) : Collections.emptyList(); + List bounds = myBounds.get(inferenceBound); + return bounds != null ? new ArrayList<>(bounds) : Collections.emptyList(); } public List getReadOnlyBounds(InferenceBound inferenceBound) { - final List bounds = myBounds.get(inferenceBound); + List bounds = myBounds.get(inferenceBound); return bounds != null ? bounds : Collections.emptyList(); } public Set getDependencies(InferenceSession session) { - final Set dependencies = new LinkedHashSet(); + Set dependencies = new LinkedHashSet<>(); collectBoundDependencies(session, dependencies); collectTransitiveDependencies(session, dependencies, dependencies); @@ -149,7 +147,7 @@ private void collectTransitiveDependencies( Set dependencies, Set rootDependencies ) { - final LinkedHashSet newDependencies = new LinkedHashSet(); + LinkedHashSet newDependencies = new LinkedHashSet<>(); for (InferenceVariable dependency : dependencies) { dependency.collectBoundDependencies(session, newDependencies); @@ -200,15 +198,13 @@ public boolean isInheritor(@Nonnull PsiClass baseClass, boolean checkDeep) { @Override public boolean isEquivalentTo(PsiElement another) { + //noinspection SimplifiableIfStatement if (this == another) { return true; } - if (getDelegate() == another && myContext != null - && !PsiTreeUtil.isAncestor(((PsiTypeParameter)another).getOwner(), myContext, false)) { - return true; - } - return false; + return getDelegate() == another && myContext != null + && !PsiTreeUtil.isAncestor(((PsiTypeParameter)another).getOwner(), myContext, false); } @Override diff --git a/java-properties-impl/src/main/java/consulo/java/properties/impl/i18n/I18nizeAction.java b/java-properties-impl/src/main/java/consulo/java/properties/impl/i18n/I18nizeAction.java index 5a34795b70..5ab2d0005c 100644 --- a/java-properties-impl/src/main/java/consulo/java/properties/impl/i18n/I18nizeAction.java +++ b/java-properties-impl/src/main/java/consulo/java/properties/impl/i18n/I18nizeAction.java @@ -62,8 +62,8 @@ public void update(@Nonnull AnActionEvent e) { @Nullable @RequiredReadAction - public static I18nQuickFixHandler getHandler(final AnActionEvent e) { - final Editor editor = getEditor(e); + public static I18nQuickFixHandler getHandler(AnActionEvent e) { + Editor editor = getEditor(e); if (editor == null) { return null; } @@ -78,7 +78,7 @@ public static I18nQuickFixHandler getHandler(final AnActionEvent e) { return null; } - final PsiLiteralExpression literalExpression = getEnclosingStringLiteral(psiFile, editor); + PsiLiteralExpression literalExpression = getEnclosingStringLiteral(psiFile, editor); PsiElement element = psiFile.findElementAt(editor.getCaretModel().getOffset()); if (element == null) { return null; @@ -102,7 +102,7 @@ else if (literalExpression != null && literalExpression.getTextRange().contains( @Nullable @RequiredReadAction - public static PsiLiteralExpression getEnclosingStringLiteral(final PsiFile psiFile, final Editor editor) { + public static PsiLiteralExpression getEnclosingStringLiteral(PsiFile psiFile, Editor editor) { PsiElement psiElement = psiFile.findElementAt(editor.getCaretModel().getOffset()); if (psiElement == null) { return null; @@ -114,16 +114,16 @@ public static PsiLiteralExpression getEnclosingStringLiteral(final PsiFile psiFi return expression; } - private static Editor getEditor(final AnActionEvent e) { + private static Editor getEditor(AnActionEvent e) { return e.getData(Editor.KEY); } @RequiredUIAccess public static void doI18nSelectedString( - final @Nonnull Project project, - final @Nonnull Editor editor, - final @Nonnull PsiFile psiFile, - final @Nonnull I18nQuickFixHandler handler + @Nonnull Project project, + @Nonnull Editor editor, + @Nonnull PsiFile psiFile, + @Nonnull I18nQuickFixHandler handler ) { try { handler.checkApplicability(psiFile, editor); @@ -133,7 +133,7 @@ public static void doI18nSelectedString( return; } - final JavaI18nizeQuickFixDialog dialog = handler.createDialog(project, editor, psiFile); + JavaI18nizeQuickFixDialog dialog = handler.createDialog(project, editor, psiFile); if (dialog == null) { return; } @@ -145,16 +145,19 @@ public static void doI18nSelectedString( if (!FileModificationService.getInstance().prepareFileForWrite(psiFile)) { return; } - final Collection propertiesFiles = dialog.getAllPropertiesFiles(); + Collection propertiesFiles = dialog.getAllPropertiesFiles(); for (PropertiesFile file : propertiesFiles) { if (!FileModificationService.getInstance().prepareFileForWrite(file.getContainingFile())) { return; } } - project.getApplication().runWriteAction(() -> CommandProcessor.getInstance().executeCommand( - project, - () -> { + CommandProcessor.getInstance().newCommand() + .project(project) + .name(CodeInsightLocalize.quickfixI18nCommandName()) + .groupId(project) + .inWriteAction() + .run(() -> { try { handler.performI18nization( psiFile, @@ -171,23 +174,20 @@ public static void doI18nSelectedString( catch (IncorrectOperationException e) { LOG.error(e); } - }, - CodeInsightLocalize.quickfixI18nCommandName().get(), - project - )); + }); } @Override @RequiredUIAccess public void actionPerformed(@Nonnull AnActionEvent e) { - final Editor editor = getEditor(e); - final Project project = editor.getProject(); + Editor editor = getEditor(e); + Project project = editor.getProject(); assert project != null; - final PsiFile psiFile = e.getData(PsiFile.KEY); + PsiFile psiFile = e.getData(PsiFile.KEY); if (psiFile == null) { return; } - final I18nQuickFixHandler handler = getHandler(e); + I18nQuickFixHandler handler = getHandler(e); if (handler == null) { return; } diff --git a/java-properties-impl/src/main/java/consulo/java/properties/impl/i18n/I18nizeHandlerProvider.java b/java-properties-impl/src/main/java/consulo/java/properties/impl/i18n/I18nizeHandlerProvider.java index 85117b639c..c7d65c1a75 100644 --- a/java-properties-impl/src/main/java/consulo/java/properties/impl/i18n/I18nizeHandlerProvider.java +++ b/java-properties-impl/src/main/java/consulo/java/properties/impl/i18n/I18nizeHandlerProvider.java @@ -33,5 +33,5 @@ public abstract class I18nizeHandlerProvider { public static final ExtensionPointName EP_NAME = ExtensionPointName.create(I18nizeHandlerProvider.class); @Nullable - public abstract I18nQuickFixHandler getHandler(@Nonnull final PsiFile psiFile, @Nonnull final Editor editor, @Nonnull TextRange range); + public abstract I18nQuickFixHandler getHandler(@Nonnull PsiFile psiFile, @Nonnull Editor editor, @Nonnull TextRange range); } From 580ab7c64693cb9858ff16654bade64445c28792 Mon Sep 17 00:00:00 2001 From: UNV Date: Tue, 6 May 2025 20:31:29 +0300 Subject: [PATCH 3/3] Refactoring and localizing users of EP_NAME (part 13). --- .../java/debugger/engine/evaluation/EvaluateExceptionUtil.java | 2 +- .../java/debugger/impl/settings/NodeRendererSettings.java | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/java-debugger-api/src/main/java/com/intellij/java/debugger/engine/evaluation/EvaluateExceptionUtil.java b/java-debugger-api/src/main/java/com/intellij/java/debugger/engine/evaluation/EvaluateExceptionUtil.java index 56ebfeb359..0bccb553c7 100644 --- a/java-debugger-api/src/main/java/com/intellij/java/debugger/engine/evaluation/EvaluateExceptionUtil.java +++ b/java-debugger-api/src/main/java/com/intellij/java/debugger/engine/evaluation/EvaluateExceptionUtil.java @@ -75,7 +75,7 @@ public static EvaluateException createEvaluateException(String reason) { private static LocalizeValue reason(Throwable th) { if (th instanceof InvalidTypeException) { String originalReason = th.getMessage(); - return LocalizeValue.join(JavaDebuggerLocalize.evaluationErrorTypeMismatch(), LocalizeValue.ofNullable(originalReason)); + return LocalizeValue.join(JavaDebuggerLocalize.evaluationErrorTypeMismatch(), LocalizeValue.space(), LocalizeValue.ofNullable(originalReason)); } else if (th instanceof AbsentInformationException) { return JavaDebuggerLocalize.evaluationErrorDebugInfoUnavailable(); diff --git a/java-debugger-impl/src/main/java/com/intellij/java/debugger/impl/settings/NodeRendererSettings.java b/java-debugger-impl/src/main/java/com/intellij/java/debugger/impl/settings/NodeRendererSettings.java index bd4e57964f..9b03a48128 100644 --- a/java-debugger-impl/src/main/java/com/intellij/java/debugger/impl/settings/NodeRendererSettings.java +++ b/java-debugger-impl/src/main/java/com/intellij/java/debugger/impl/settings/NodeRendererSettings.java @@ -531,6 +531,7 @@ private Value doEval( catch (EvaluateException ex) { LocalizeValue message = LocalizeValue.join( JavaDebuggerLocalize.errorUnableToEvaluateExpression(), + LocalizeValue.space(), LocalizeValue.ofNullable(ex.getMessage()) ); throw new EvaluateException(message.get(), ex);