prompt: We are currently solving the following issue within our repository. Here is the issue text:
  --- BEGIN ISSUE ---
  Stray WPS513 warning.
  # Bug report
  
  `WPS513` is emitted on `if`/`else`/`if` chains that contain other statements in the last `if` block.
  
  ## What's wrong
  
  The following snippet:
  
  ```python
  if private_key is not None:
      if isinstance(private_key, PKey):
          key = private_key
      else:
          if isinstance(private_key, str):  # WPS513 Found implicit `elif` condition
              stream = io.StringIO()
              stream.write(private_key)
              stream.seek(0)
              private_key = stream
          key = RSAKey.from_private_key(private_key)
  ```
  
  triggers a stray WPS513 warning.  Seems like the assignment to `key` is not taken into account.
  
  ## How is that should be
  
  `WPS513` should only be emitted if the dangling `if` statement is the only one present in the `else` block.
  
  --- END ISSUE ---
  
  Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
  --- BEGIN FILES ---
  Path: `wemake_python_styleguide/visitors/tokenize/conditions.py`
  Content:
  ```
  1 import tokenize
  2 from typing import ClassVar, FrozenSet
  3 
  4 from typing_extensions import final
  5 
  6 from wemake_python_styleguide.violations.refactoring import (
  7     ImplicitElifViolation,
  8 )
  9 from wemake_python_styleguide.visitors.base import BaseTokenVisitor
  10 
  11 
  12 @final
  13 class IfElseVisitor(BaseTokenVisitor):
  14     """
  15     Checks if tokens tokens.
  16 
  17     We use ``tokenize`` instead of ``ast`` because
  18 
  19     .. code:: python
  20 
  21        if some:
  22            ...
  23         else:
  24             if other:
  25                 ...
  26 
  27     has the same ``ast`` representation as:
  28 
  29     .. code:: python
  30 
  31       if some:
  32           ...
  33       elif other:
  34           ...
  35 
  36     That's why we have to use ``tokenize`` to find
  37     the raw tokens inside the text.
  38 
  39     """
  40 
  41     _allowed_token_types: ClassVar[FrozenSet[int]] = frozenset((
  42         tokenize.NEWLINE,
  43         tokenize.NL,
  44         tokenize.COLON,
  45         tokenize.INDENT,
  46     ))
  47 
  48     def visit_name(self, token: tokenize.TokenInfo) -> None:
  49         """
  50         Checks that ``if`` nodes are defined correctly.
  51 
  52         Raises:
  53             ImplicitElifViolation
  54 
  55         """
  56         self._check_implicit_elif(token)
  57 
  58     def _does_else_belong_to_if(self, start_index: int) -> bool:
  59         previous_token = self.file_tokens[start_index - 1]
  60 
  61         if previous_token.type != tokenize.DEDENT:
  62             # This is not the first token on the line, which means that it can
  63             # also be "embedded" else: x if A else B
  64             return False
  65 
  66         for token in reversed(self.file_tokens[:start_index - 1]):
  67             if token.type != tokenize.NAME:
  68                 continue
  69 
  70             # Here we rely upon an intuition that in Python else have to be
  71             # on the same level (same indentation) as parent statement.
  72             if token.start[1] == previous_token.start[1]:
  73                 return token.string in {'if', 'elif'}
  74 
  75         return False
  76 
  77     def _check_implicit_elif(self, token: tokenize.TokenInfo) -> None:
  78         if token.string != 'else':
  79             return
  80 
  81         index = self.file_tokens.index(token)
  82 
  83         # `else` token can belong also to `for` and `try/except` statement,
  84         # which can trigger false positive for that violation.
  85         if not self._does_else_belong_to_if(index):
  86             return
  87 
  88         # There's a bug in coverage, I am not sure how to make it work.
  89         for next_token in self.file_tokens[index + 1:]:  # pragma: no cover
  90             if next_token.exact_type in self._allowed_token_types:
  91                 continue
  92             elif next_token.string == 'if':
  93                 self.add_violation(ImplicitElifViolation(next_token))
  94             return
  95
  ```
  --- END FILES ---
  
  Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.
  
  Here is an example:
  
  ```diff
  diff --git a/examples/server_async.py b/examples/server_async.py
  --- a/examples/server_async.py
  +++ b/examples/server_async.py
  @@ -313,4 +313,4 @@
   
   
   if __name__ == "__main__":
  -    asyncio.run(run_async_server("."), debug=True)
  +    asyncio.run(run_async_server(), debug=True)
  diff --git a/examples/server_sync.py b/examples/server_sync.py
  --- a/examples/server_sync.py
  +++ b/examples/server_sync.py
  @@ -313,5 +313,5 @@
   
   
   if __name__ == "__main__":
  -    server = run_sync_server(".")
  +    server = run_sync_server()
       server.shutdown()
  
  ```
  
golden_diff: diff --git a/wemake_python_styleguide/visitors/tokenize/conditions.py b/wemake_python_styleguide/visitors/tokenize/conditions.py
  --- a/wemake_python_styleguide/visitors/tokenize/conditions.py
  +++ b/wemake_python_styleguide/visitors/tokenize/conditions.py
  @@ -1,5 +1,5 @@
   import tokenize
  -from typing import ClassVar, FrozenSet
  +from typing import ClassVar, FrozenSet, Sequence
   
   from typing_extensions import final
   
  @@ -74,21 +74,63 @@
   
           return False
   
  -    def _check_implicit_elif(self, token: tokenize.TokenInfo) -> None:
  -        if token.string != 'else':
  -            return
  +    def _if_has_code_below(
  +        self,
  +        remaining_tokens: Sequence[tokenize.TokenInfo],
  +    ) -> bool:
  +        """
  +        Checks code immediately below an if statement to remove false positives.
  +
  +        Checks that, below an if that comes immediately after an else, there is
  +        more code to be considered so as not to throw an incorrect violation.
  +        """
  +        index = 1
  +
  +        while remaining_tokens[index - 1].exact_type != tokenize.INDENT:
  +            index += 1
  +
  +        context_count = 1
   
  -        index = self.file_tokens.index(token)
  +        while context_count:
  +            next_token = remaining_tokens[index]
  +            if next_token.exact_type == tokenize.INDENT:
  +                context_count += 1
  +            if next_token.exact_type == tokenize.DEDENT:
  +                context_count -= 1
  +            index += 1
  +
  +        return remaining_tokens[index].exact_type != tokenize.DEDENT
  +
  +    def _check_complex_else(
  +        self,
  +        tokens: Sequence[tokenize.TokenInfo],
  +        current_token: tokenize.TokenInfo,
  +        index: int,
  +    ) -> None:
  +        complex_else = self._if_has_code_below(tokens[index + 1:])
  +        if not complex_else:
  +            self.add_violation(ImplicitElifViolation(current_token))
  +
  +    def _is_invalid_token(self, index: int, token: tokenize.TokenInfo) -> bool:
  +        is_not_else = token.string != 'else'
   
           # `else` token can belong also to `for` and `try/except` statement,
           # which can trigger false positive for that violation.
  -        if not self._does_else_belong_to_if(index):
  +        belongs_to_if = self._does_else_belong_to_if(index)
  +
  +        return is_not_else or not belongs_to_if
  +
  +    def _check_implicit_elif(self, token: tokenize.TokenInfo) -> None:
  +        token_index = self.file_tokens.index(token)
  +
  +        if self._is_invalid_token(token_index, token):
               return
   
           # There's a bug in coverage, I am not sure how to make it work.
  -        for next_token in self.file_tokens[index + 1:]:  # pragma: no cover
  +        next_tokens = self.file_tokens[token_index + 1:]
  +        for index, next_token in enumerate(next_tokens):  # pragma: no cover
               if next_token.exact_type in self._allowed_token_types:
                   continue
               elif next_token.string == 'if':
  -                self.add_violation(ImplicitElifViolation(next_token))
  +                self._check_complex_else(next_tokens, next_token, index)
               return
  
verification_info: {"golden_diff": "diff --git a/wemake_python_styleguide/visitors/tokenize/conditions.py b/wemake_python_styleguide/visitors/tokenize/conditions.py\n--- a/wemake_python_styleguide/visitors/tokenize/conditions.py\n+++ b/wemake_python_styleguide/visitors/tokenize/conditions.py\n@@ -1,5 +1,5 @@\n import tokenize\n-from typing import ClassVar, FrozenSet\n+from typing import ClassVar, FrozenSet, Sequence\n \n from typing_extensions import final\n \n@@ -74,21 +74,63 @@\n \n         return False\n \n-    def _check_implicit_elif(self, token: tokenize.TokenInfo) -> None:\n-        if token.string != 'else':\n-            return\n+    def _if_has_code_below(\n+        self,\n+        remaining_tokens: Sequence[tokenize.TokenInfo],\n+    ) -> bool:\n+        \"\"\"\n+        Checks code immediately below an if statement to remove false positives.\n+\n+        Checks that, below an if that comes immediately after an else, there is\n+        more code to be considered so as not to throw an incorrect violation.\n+        \"\"\"\n+        index = 1\n+\n+        while remaining_tokens[index - 1].exact_type != tokenize.INDENT:\n+            index += 1\n+\n+        context_count = 1\n \n-        index = self.file_tokens.index(token)\n+        while context_count:\n+            next_token = remaining_tokens[index]\n+            if next_token.exact_type == tokenize.INDENT:\n+                context_count += 1\n+            if next_token.exact_type == tokenize.DEDENT:\n+                context_count -= 1\n+            index += 1\n+\n+        return remaining_tokens[index].exact_type != tokenize.DEDENT\n+\n+    def _check_complex_else(\n+        self,\n+        tokens: Sequence[tokenize.TokenInfo],\n+        current_token: tokenize.TokenInfo,\n+        index: int,\n+    ) -> None:\n+        complex_else = self._if_has_code_below(tokens[index + 1:])\n+        if not complex_else:\n+            self.add_violation(ImplicitElifViolation(current_token))\n+\n+    def _is_invalid_token(self, index: int, token: tokenize.TokenInfo) -> bool:\n+        is_not_else = token.string != 'else'\n \n         # `else` token can belong also to `for` and `try/except` statement,\n         # which can trigger false positive for that violation.\n-        if not self._does_else_belong_to_if(index):\n+        belongs_to_if = self._does_else_belong_to_if(index)\n+\n+        return is_not_else or not belongs_to_if\n+\n+    def _check_implicit_elif(self, token: tokenize.TokenInfo) -> None:\n+        token_index = self.file_tokens.index(token)\n+\n+        if self._is_invalid_token(token_index, token):\n             return\n \n         # There's a bug in coverage, I am not sure how to make it work.\n-        for next_token in self.file_tokens[index + 1:]:  # pragma: no cover\n+        next_tokens = self.file_tokens[token_index + 1:]\n+        for index, next_token in enumerate(next_tokens):  # pragma: no cover\n             if next_token.exact_type in self._allowed_token_types:\n                 continue\n             elif next_token.string == 'if':\n-                self.add_violation(ImplicitElifViolation(next_token))\n+                self._check_complex_else(next_tokens, next_token, index)\n             return\n", "issue": "Stray WPS513 warning.\n# Bug report\r\n\r\n`WPS513` is emitted on `if`/`else`/`if` chains that contain other statements in the last `if` block.\r\n\r\n## What's wrong\r\n\r\nThe following snippet:\r\n\r\n```python\r\nif private_key is not None:\r\n    if isinstance(private_key, PKey):\r\n        key = private_key\r\n    else:\r\n        if isinstance(private_key, str):  # WPS513 Found implicit `elif` condition\r\n            stream = io.StringIO()\r\n            stream.write(private_key)\r\n            stream.seek(0)\r\n            private_key = stream\r\n        key = RSAKey.from_private_key(private_key)\r\n```\r\n\r\ntriggers a stray WPS513 warning.  Seems like the assignment to `key` is not taken into account.\r\n\r\n## How is that should be\r\n\r\n`WPS513` should only be emitted if the dangling `if` statement is the only one present in the `else` block.\n", "before_files": [{"content": "import tokenize\nfrom typing import ClassVar, FrozenSet\n\nfrom typing_extensions import final\n\nfrom wemake_python_styleguide.violations.refactoring import (\n    ImplicitElifViolation,\n)\nfrom wemake_python_styleguide.visitors.base import BaseTokenVisitor\n\n\n@final\nclass IfElseVisitor(BaseTokenVisitor):\n    \"\"\"\n    Checks if tokens tokens.\n\n    We use ``tokenize`` instead of ``ast`` because\n\n    .. code:: python\n\n       if some:\n           ...\n        else:\n            if other:\n                ...\n\n    has the same ``ast`` representation as:\n\n    .. code:: python\n\n      if some:\n          ...\n      elif other:\n          ...\n\n    That's why we have to use ``tokenize`` to find\n    the raw tokens inside the text.\n\n    \"\"\"\n\n    _allowed_token_types: ClassVar[FrozenSet[int]] = frozenset((\n        tokenize.NEWLINE,\n        tokenize.NL,\n        tokenize.COLON,\n        tokenize.INDENT,\n    ))\n\n    def visit_name(self, token: tokenize.TokenInfo) -> None:\n        \"\"\"\n        Checks that ``if`` nodes are defined correctly.\n\n        Raises:\n            ImplicitElifViolation\n\n        \"\"\"\n        self._check_implicit_elif(token)\n\n    def _does_else_belong_to_if(self, start_index: int) -> bool:\n        previous_token = self.file_tokens[start_index - 1]\n\n        if previous_token.type != tokenize.DEDENT:\n            # This is not the first token on the line, which means that it can\n            # also be \"embedded\" else: x if A else B\n            return False\n\n        for token in reversed(self.file_tokens[:start_index - 1]):\n            if token.type != tokenize.NAME:\n                continue\n\n            # Here we rely upon an intuition that in Python else have to be\n            # on the same level (same indentation) as parent statement.\n            if token.start[1] == previous_token.start[1]:\n                return token.string in {'if', 'elif'}\n\n        return False\n\n    def _check_implicit_elif(self, token: tokenize.TokenInfo) -> None:\n        if token.string != 'else':\n            return\n\n        index = self.file_tokens.index(token)\n\n        # `else` token can belong also to `for` and `try/except` statement,\n        # which can trigger false positive for that violation.\n        if not self._does_else_belong_to_if(index):\n            return\n\n        # There's a bug in coverage, I am not sure how to make it work.\n        for next_token in self.file_tokens[index + 1:]:  # pragma: no cover\n            if next_token.exact_type in self._allowed_token_types:\n                continue\n            elif next_token.string == 'if':\n                self.add_violation(ImplicitElifViolation(next_token))\n            return\n", "path": "wemake_python_styleguide/visitors/tokenize/conditions.py"}], "after_files": [{"content": "import tokenize\nfrom typing import ClassVar, FrozenSet, Sequence\n\nfrom typing_extensions import final\n\nfrom wemake_python_styleguide.violations.refactoring import (\n    ImplicitElifViolation,\n)\nfrom wemake_python_styleguide.visitors.base import BaseTokenVisitor\n\n\n@final\nclass IfElseVisitor(BaseTokenVisitor):\n    \"\"\"\n    Checks if tokens tokens.\n\n    We use ``tokenize`` instead of ``ast`` because\n\n    .. code:: python\n\n       if some:\n           ...\n        else:\n            if other:\n                ...\n\n    has the same ``ast`` representation as:\n\n    .. code:: python\n\n      if some:\n          ...\n      elif other:\n          ...\n\n    That's why we have to use ``tokenize`` to find\n    the raw tokens inside the text.\n\n    \"\"\"\n\n    _allowed_token_types: ClassVar[FrozenSet[int]] = frozenset((\n        tokenize.NEWLINE,\n        tokenize.NL,\n        tokenize.COLON,\n        tokenize.INDENT,\n    ))\n\n    def visit_name(self, token: tokenize.TokenInfo) -> None:\n        \"\"\"\n        Checks that ``if`` nodes are defined correctly.\n\n        Raises:\n            ImplicitElifViolation\n\n        \"\"\"\n        self._check_implicit_elif(token)\n\n    def _does_else_belong_to_if(self, start_index: int) -> bool:\n        previous_token = self.file_tokens[start_index - 1]\n\n        if previous_token.type != tokenize.DEDENT:\n            # This is not the first token on the line, which means that it can\n            # also be \"embedded\" else: x if A else B\n            return False\n\n        for token in reversed(self.file_tokens[:start_index - 1]):\n            if token.type != tokenize.NAME:\n                continue\n\n            # Here we rely upon an intuition that in Python else have to be\n            # on the same level (same indentation) as parent statement.\n            if token.start[1] == previous_token.start[1]:\n                return token.string in {'if', 'elif'}\n\n        return False\n\n    def _if_has_code_below(\n        self,\n        remaining_tokens: Sequence[tokenize.TokenInfo],\n    ) -> bool:\n        \"\"\"\n        Checks code immediately below an if statement to remove false positives.\n\n        Checks that, below an if that comes immediately after an else, there is\n        more code to be considered so as not to throw an incorrect violation.\n        \"\"\"\n        index = 1\n\n        while remaining_tokens[index - 1].exact_type != tokenize.INDENT:\n            index += 1\n\n        context_count = 1\n\n        while context_count:\n            next_token = remaining_tokens[index]\n            if next_token.exact_type == tokenize.INDENT:\n                context_count += 1\n            if next_token.exact_type == tokenize.DEDENT:\n                context_count -= 1\n            index += 1\n\n        return remaining_tokens[index].exact_type != tokenize.DEDENT\n\n    def _check_complex_else(\n        self,\n        tokens: Sequence[tokenize.TokenInfo],\n        current_token: tokenize.TokenInfo,\n        index: int,\n    ) -> None:\n        complex_else = self._if_has_code_below(tokens[index + 1:])\n        if not complex_else:\n            self.add_violation(ImplicitElifViolation(current_token))\n\n    def _is_invalid_token(self, index: int, token: tokenize.TokenInfo) -> bool:\n        is_not_else = token.string != 'else'\n\n        # `else` token can belong also to `for` and `try/except` statement,\n        # which can trigger false positive for that violation.\n        belongs_to_if = self._does_else_belong_to_if(index)\n\n        return is_not_else or not belongs_to_if\n\n    def _check_implicit_elif(self, token: tokenize.TokenInfo) -> None:\n        token_index = self.file_tokens.index(token)\n\n        if self._is_invalid_token(token_index, token):\n            return\n\n        # There's a bug in coverage, I am not sure how to make it work.\n        next_tokens = self.file_tokens[token_index + 1:]\n        for index, next_token in enumerate(next_tokens):  # pragma: no cover\n            if next_token.exact_type in self._allowed_token_types:\n                continue\n            elif next_token.string == 'if':\n                self._check_complex_else(next_tokens, next_token, index)\n            return\n", "path": "wemake_python_styleguide/visitors/tokenize/conditions.py"}]}