boolean (@NotNull PsiInstanceOfExpression expression) { PsiIfStatement ifStatement = PsiTreeUtil.getParentOfType(expression, PsiIfStatement.class); if (!PsiTreeUtil.isAncestor(ifStatement, expression, false)) { //something strange, return true as safe result return true; } return JavaPsiPatternUtil.getExposedPatternVariables(expression) .stream().flatMap(variable -> VariableAccessUtils.getVariableReferences(variable, ifStatement.getParent()).stream()) .anyMatch(variable -> !PsiTreeUtil.isAncestor(ifStatement, variable, false)); }