PsiInstanceOfExpression (@NotNull PsiTypeCastExpression cast) { PsiElement context = PsiUtil.skipParenthesizedExprUp(cast.getParent()); if (context instanceof PsiLocalVariable) { context = context.getParent(); } else { while (true) { if (context instanceof PsiPolyadicExpression) { IElementType tokenType = ((PsiPolyadicExpression)context).getOperationTokenType(); if (tokenType.equals(JavaTokenType.ANDAND) || tokenType.equals(JavaTokenType.OROR)) { PsiInstanceOfExpression instanceOf = findInstanceOf((PsiExpression)context, cast, tokenType.equals(JavaTokenType.ANDAND)); if (instanceOf != null) { return instanceOf; } } } if (context instanceof PsiConditionalExpression) { PsiExpression condition = ((PsiConditionalExpression)context).getCondition(); if (!PsiTreeUtil.isAncestor(condition, cast, true)) { boolean whenTrue = PsiTreeUtil.isAncestor(((PsiConditionalExpression)context).getThenExpression(), cast, false); PsiInstanceOfExpression instanceOf = findInstanceOf(condition, cast, whenTrue); if (instanceOf != null) { return instanceOf; } } } if ((context instanceof PsiExpression && !(context instanceof PsiLambdaExpression)) || context instanceof PsiExpressionList || context instanceof PsiLocalVariable) { context = context.getParent(); continue; } break; } if (!(context instanceof PsiStatement)) return null; } PsiElement parent = context.getParent(); if (parent instanceof PsiCodeBlock) { for (PsiElement stmt = context.getPrevSibling(); stmt != null; stmt = stmt.getPrevSibling()) { if (stmt instanceof PsiIfStatement ifStatement) { PsiStatement thenBranch = ifStatement.getThenBranch(); PsiStatement elseBranch = ifStatement.getElseBranch(); boolean thenCompletes = canCompleteNormally(parent, thenBranch); boolean elseCompletes = canCompleteNormally(parent, elseBranch); if (thenCompletes != elseCompletes) { PsiInstanceOfExpression instanceOf = findInstanceOf(ifStatement.getCondition(), cast, thenCompletes); if (instanceOf != null) { return instanceOf; } } } if (stmt instanceof PsiWhileStatement || stmt instanceof PsiDoWhileStatement || stmt instanceof PsiForStatement) { PsiConditionalLoopStatement loop = (PsiConditionalLoopStatement)stmt; if (PsiTreeUtil.processElements( loop, e -> !(e instanceof PsiBreakStatement) || ((PsiBreakStatement)e).findExitedStatement() != loop)) { PsiInstanceOfExpression instanceOf = findInstanceOf(loop.getCondition(), cast, false); if (instanceOf != null) { return instanceOf; } } } if (stmt instanceof PsiSwitchLabelStatementBase) break; } if (parent.getParent() instanceof PsiBlockStatement) { context = parent.getParent(); parent = context.getParent(); } } return processParent(cast, context, parent); }