[java][switch resolve] IDEA-273929 Good code red - cannot resolve symbol in switch statement group

The resolver used to fail when a case label element is parenthesized. The patch fixes this problem by stripping parens from a case element if necessary

GitOrigin-RevId: de2113905ccabcc7c675c94c320cb2b26fccf487
This commit is contained in:
Nikita Eshkeev
2021-08-02 22:50:16 +00:00
committed by intellij-monorepo-bot
parent 6be1da1730
commit a7100b4e2e
4 changed files with 36 additions and 8 deletions
@@ -5,10 +5,13 @@ import com.intellij.lang.ASTNode;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.tree.*;
import com.intellij.psi.scope.PsiScopeProcessor;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.psi.util.PsiUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.function.Predicate;
public class PsiCaseLabelElementListImpl extends CompositePsiElement implements PsiCaseLabelElementList {
private volatile PsiCaseLabelElement[] myElements;
@@ -90,16 +93,25 @@ public class PsiCaseLabelElementListImpl extends CompositePsiElement implements
@NotNull ResolveState state,
PsiElement lastParent,
@NotNull PsiElement place) {
// Do not resolve elements from the list of elements of the case rule
if (lastParent != null) return true;
if (oneOfElements(place)) return true;
final PsiCaseLabelElement[] elements = getElements();
if (ContainerUtil.exists(elements, e -> e == place)) return true;
for (PsiCaseLabelElement label : elements) {
for (PsiCaseLabelElement label : getElements()) {
boolean shouldKeepGoing = label.processDeclarations(processor, state, null, place);
if (!shouldKeepGoing) return false;
}
return true;
}
private boolean oneOfElements(@NotNull PsiElement place) {
return Arrays.stream(getElements())
.map(PsiCaseLabelElementListImpl::skipParenthesis)
.anyMatch(Predicate.isEqual(place));
}
@Nullable
private static PsiCaseLabelElement skipParenthesis(PsiCaseLabelElement e) {
if (!(e instanceof PsiParenthesizedExpression)) return e;
return PsiUtil.skipParenthesizedExprDown((PsiParenthesizedExpression)e);
}
}
@@ -96,7 +96,7 @@ public class PsiSwitchLabelStatementImpl extends PsiSwitchLabelStatementBaseImpl
final AtomicBoolean thisSwitchLabelIsImmediate = new AtomicBoolean();
PsiTreeUtil.treeWalkUp(place, getParent(), (currentScope, prevScope) -> {
PsiTreeUtil.treeWalkUp(place, getParent(), (currentScope, __) -> {
PsiSwitchLabelStatementBase immediateSwitchLabel;
@@ -0,0 +1,11 @@
class Main {
final int i = 2;
void f(Object obj) {
switch (obj) {
case Integer i, ((i<caret>)):
System.out.println(i);
}
}
}
}
@@ -128,6 +128,11 @@ public class GotoDeclarationTest extends LightJavaCodeInsightTestCase {
doTestPatternMatchingGuard();
}
public void testPatternMatchingWithParensAroundReference() {
doTestPatternMatchingGuard();
}
public void testReferenceFieldInPatternMatchingInSwitchStatement() {
doTestPatternMatchingGuard();
}