We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
False positive implicit yield violation
# Bug report

<!--
Hi, thanks for submitting a bug. We appreciate that.

But, we will need some information about what's wrong to help you.
-->

## What's wrong
With common function to split iterable by chunks WPS raises `ImplicitYieldFromViolation`
<!-- Describe what is not working. Please, attach a traceback. -->
```
def chunks(value, chunk_size):
    """Yield successive n-sized chunks from l."""
    for index in range(0, len(value), chunk_size):
        yield value[index:index + chunk_size]
```

## How is that should be
`ImplicitYieldFromViolation` should be raised only if no other operations with iterable item.
<!-- Describe how it should work. -->

<!--

  Love wemake-python-styleguide? ❤️
  Do you want your bugs to be solved faster?

  Please consider supporting our collective:
👉  https://opencollective.com/wemake-python-styleguide/donate

-->


--- 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/ast/loops.py`
Content:
```
1 # -*- coding: utf-8 -*-
2 
3 import ast
4 from collections import defaultdict
5 from typing import ClassVar, DefaultDict, List, Optional, Union
6 
7 from typing_extensions import final
8 
9 from wemake_python_styleguide.compat.aliases import AssignNodes, ForNodes
10 from wemake_python_styleguide.compat.functions import get_assign_targets
11 from wemake_python_styleguide.logic import (
12     nodes,
13     operators,
14     slices,
15     source,
16     walk,
17 )
18 from wemake_python_styleguide.logic.variables import (
19     is_valid_block_variable_definition,
20 )
21 from wemake_python_styleguide.types import AnyFor, AnyNodes
22 from wemake_python_styleguide.violations.best_practices import (
23     LambdaInsideLoopViolation,
24     LoopVariableDefinitionViolation,
25     YieldInComprehensionViolation,
26 )
27 from wemake_python_styleguide.violations.complexity import (
28     TooManyForsInComprehensionViolation,
29 )
30 from wemake_python_styleguide.violations.consistency import (
31     MultilineLoopViolation,
32     MultipleIfsInComprehensionViolation,
33     UselessContinueViolation,
34     WrongLoopIterTypeViolation,
35 )
36 from wemake_python_styleguide.violations.refactoring import (
37     ImplicitItemsIteratorViolation,
38     ImplicitSumViolation,
39     ImplicitYieldFromViolation,
40     UselessLoopElseViolation,
41 )
42 from wemake_python_styleguide.visitors import base, decorators
43 
44 _AnyLoop = Union[AnyFor, ast.While]
45 _AnyComprehension = Union[
46     ast.ListComp,
47     ast.DictComp,
48     ast.SetComp,
49     ast.GeneratorExp,
50 ]
51 
52 
53 @final
54 @decorators.alias('visit_any_comprehension', (
55     'visit_ListComp',
56     'visit_DictComp',
57     'visit_SetComp',
58     'visit_GeneratorExp',
59 ))
60 class WrongComprehensionVisitor(base.BaseNodeVisitor):
61     """Checks comprehensions for correctness."""
62 
63     _max_ifs: ClassVar[int] = 1
64     _max_fors: ClassVar[int] = 2
65 
66     def __init__(self, *args, **kwargs) -> None:
67         """Creates a counter for tracked metrics."""
68         super().__init__(*args, **kwargs)
69         self._fors: DefaultDict[ast.AST, int] = defaultdict(int)
70 
71     def visit_comprehension(self, node: ast.comprehension) -> None:
72         """
73         Finds multiple ``if`` and ``for`` nodes inside the comprehension.
74 
75         Raises:
76             MultipleIfsInComprehensionViolation
77             TooManyForsInComprehensionViolation
78 
79         """
80         self._check_ifs(node)
81         self._check_fors(node)
82         self.generic_visit(node)
83 
84     def visit_any_comprehension(self, node: _AnyComprehension) -> None:
85         """
86         Finds incorrect patterns inside comprehensions.
87 
88         Raises:
89             YieldInComprehensionViolation
90 
91         """
92         self._check_contains_yield(node)
93         self.generic_visit(node)
94 
95     def _check_ifs(self, node: ast.comprehension) -> None:
96         if len(node.ifs) > self._max_ifs:
97             # We are trying to fix line number in the report,
98             # since `comprehension` does not have this property.
99             parent = nodes.get_parent(node) or node
100             self.add_violation(MultipleIfsInComprehensionViolation(parent))
101 
102     def _check_fors(self, node: ast.comprehension) -> None:
103         parent = nodes.get_parent(node)
104         self._fors[parent] = len(parent.generators)  # type: ignore
105 
106     def _check_contains_yield(self, node: _AnyComprehension) -> None:
107         for sub_node in ast.walk(node):
108             if isinstance(sub_node, ast.Yield):
109                 self.add_violation(YieldInComprehensionViolation(node))
110 
111     def _post_visit(self) -> None:
112         for node, for_count in self._fors.items():
113             if for_count > self._max_fors:
114                 self.add_violation(TooManyForsInComprehensionViolation(node))
115 
116 
117 @final
118 @decorators.alias('visit_any_loop', (
119     'visit_For',
120     'visit_While',
121     'visit_AsyncFor',
122 ))
123 class WrongLoopVisitor(base.BaseNodeVisitor):
124     """Responsible for examining loops."""
125 
126     def visit_any_loop(self, node: _AnyLoop) -> None:
127         """
128         Checks ``for`` and ``while`` loops.
129 
130         Raises:
131             UselessLoopElseViolation
132             LambdaInsideLoopViolation
133             MultilineLoopViolation
134 
135         """
136         self._check_loop_needs_else(node)
137         self._check_lambda_inside_loop(node)
138         self._check_useless_continue(node)
139         self._check_multiline_loop(node)
140         self.generic_visit(node)
141 
142     def _does_loop_contain_node(  # TODO: move, reuse in annotations.py
143         self,
144         loop: Optional[_AnyLoop],
145         to_check: ast.Break,
146     ) -> bool:
147         if loop is None:
148             return False
149 
150         for inner_node in ast.walk(loop):
151             # We are checking this specific node, not just any `break`:
152             if to_check is inner_node:
153                 return True
154         return False
155 
156     def _has_break(self, node: _AnyLoop) -> bool:
157         closest_loop = None
158 
159         for subnode in ast.walk(node):
160             if isinstance(subnode, (*ForNodes, ast.While)):
161                 if subnode is not node:
162                     closest_loop = subnode
163 
164             if isinstance(subnode, ast.Break):
165                 is_nested_break = self._does_loop_contain_node(
166                     closest_loop, subnode,
167                 )
168                 if not is_nested_break:
169                     return True
170         return False
171 
172     def _check_loop_needs_else(self, node: _AnyLoop) -> None:
173         if node.orelse and not self._has_break(node):
174             self.add_violation(UselessLoopElseViolation(node))
175 
176     def _check_lambda_inside_loop(self, node: _AnyLoop) -> None:
177         for subnode in node.body:
178             if walk.is_contained(subnode, (ast.Lambda,)):
179                 self.add_violation(LambdaInsideLoopViolation(node))
180 
181     def _check_useless_continue(self, node: _AnyLoop) -> None:
182         nodes_at_line: DefaultDict[int, List[ast.AST]] = defaultdict(list)
183         for sub_node in ast.walk(node):
184             lineno = getattr(sub_node, 'lineno', None)
185             if lineno is not None:
186                 nodes_at_line[lineno].append(sub_node)
187 
188         last_line = nodes_at_line[sorted(nodes_at_line.keys())[-1]]
189         if any(isinstance(last, ast.Continue) for last in last_line):
190             self.add_violation(UselessContinueViolation(node))
191 
192     def _check_multiline_loop(self, node: _AnyLoop) -> None:
193         start_lineno = getattr(node, 'lineno', None)
194 
195         if isinstance(node, ast.While):
196             node_to_check = node.test
197         else:
198             node_to_check = node.iter
199 
200         for sub_node in ast.walk(node_to_check):
201             sub_lineno = getattr(sub_node, 'lineno', None)
202             if sub_lineno is not None and sub_lineno > start_lineno:
203                 self.add_violation(MultilineLoopViolation(node))
204                 break
205 
206 
207 @final
208 @decorators.alias('visit_any_for', (
209     'visit_For',
210     'visit_AsyncFor',
211 ))
212 class WrongLoopDefinitionVisitor(base.BaseNodeVisitor):
213     """Responsible for ``for`` loops and comprehensions definitions."""
214 
215     _forbidden_for_iters: ClassVar[AnyNodes] = (
216         ast.List,
217         ast.ListComp,
218         ast.Dict,
219         ast.DictComp,
220         ast.Set,
221         ast.SetComp,
222         ast.GeneratorExp,
223         ast.Num,
224         ast.NameConstant,
225     )
226 
227     def visit_any_for(self, node: AnyFor) -> None:
228         """
229         Ensures that ``for`` loop definitions are correct.
230 
231         Raises:
232             LoopVariableDefinitionViolation
233             WrongLoopIterTypeViolation
234             ImplicitSumViolation
235 
236         """
237         self._check_variable_definitions(node.target)
238         self._check_explicit_iter_type(node)
239         self._check_implicit_sum(node)
240         self._check_implicit_yield_from(node)
241         self.generic_visit(node)
242 
243     def visit_comprehension(self, node: ast.comprehension) -> None:
244         """
245         Ensures that comprehension definitions are correct.
246 
247         Raises:
248             LoopVariableDefinitionViolation
249 
250         """
251         self._check_variable_definitions(node.target)
252         self._check_explicit_iter_type(node)
253         self.generic_visit(node)
254 
255     def _check_variable_definitions(self, node: ast.AST) -> None:
256         if not is_valid_block_variable_definition(node):
257             self.add_violation(LoopVariableDefinitionViolation(node))
258 
259     def _check_explicit_iter_type(
260         self,
261         node: Union[AnyFor, ast.comprehension],
262     ) -> None:
263         node_iter = operators.unwrap_unary_node(node.iter)
264         is_wrong = isinstance(node_iter, self._forbidden_for_iters)
265         is_empty = isinstance(node_iter, ast.Tuple) and not node_iter.elts
266         if is_wrong or is_empty:
267             self.add_violation(WrongLoopIterTypeViolation(node_iter))
268 
269     def _check_implicit_sum(self, node: AnyFor) -> None:
270         is_implicit_sum = (
271             len(node.body) == 1 and
272             isinstance(node.body[0], ast.AugAssign) and
273             isinstance(node.body[0].op, ast.Add) and
274             isinstance(node.body[0].target, ast.Name)
275         )
276         if is_implicit_sum:
277             self.add_violation(ImplicitSumViolation(node))
278 
279     def _check_implicit_yield_from(self, node: AnyFor) -> None:
280         is_implicit_yield_from = (
281             len(node.body) == 1 and
282             isinstance(node.body[0], ast.Expr) and
283             isinstance(node.body[0].value, ast.Yield)
284         )
285         if is_implicit_yield_from:
286             self.add_violation(ImplicitYieldFromViolation(node))
287 
288 
289 @final
290 class SyncForLoopVisitor(base.BaseNodeVisitor):
291     """We use this visitor to check just sync ``for`` loops."""
292 
293     def visit_For(self, node: ast.For) -> None:
294         """
295         Checks for hidden patterns in sync loops.
296 
297         Raises:
298             ImplicitItemsIteratorViolation
299 
300         """
301         self._check_implicit_items(node)
302         self.generic_visit(node)
303 
304     def _check_implicit_items(self, node: ast.For) -> None:
305         iterable = source.node_to_string(node.iter)
306         target = source.node_to_string(node.target)
307 
308         for sub in ast.walk(node):
309             if isinstance(sub, ast.Subscript):
310                 if self._is_assigned_target(sub):
311                     continue
312 
313                 if slices.is_same_slice(iterable, target, sub):
314                     self.add_violation(ImplicitItemsIteratorViolation(node))
315                     break
316 
317     def _is_assigned_target(self, node: ast.Subscript) -> bool:
318         parent = nodes.get_parent(node)
319         if not isinstance(parent, (*AssignNodes, ast.AugAssign)):
320             return False
321         return any(node == target for target in get_assign_targets(parent))
322
```
--- 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()

```

diff --git a/wemake_python_styleguide/visitors/ast/loops.py b/wemake_python_styleguide/visitors/ast/loops.py
--- a/wemake_python_styleguide/visitors/ast/loops.py
+++ b/wemake_python_styleguide/visitors/ast/loops.py
@@ -277,6 +277,9 @@
             self.add_violation(ImplicitSumViolation(node))
 
     def _check_implicit_yield_from(self, node: AnyFor) -> None:
+        if isinstance(nodes.get_context(node), ast.AsyncFunctionDef):
+            # Python does not support 'yield from' inside async functions
+            return
         is_implicit_yield_from = (
             len(node.body) == 1 and
             isinstance(node.body[0], ast.Expr) and

{"golden_diff": "diff --git a/wemake_python_styleguide/visitors/ast/loops.py b/wemake_python_styleguide/visitors/ast/loops.py\n--- a/wemake_python_styleguide/visitors/ast/loops.py\n+++ b/wemake_python_styleguide/visitors/ast/loops.py\n@@ -277,6 +277,9 @@\n             self.add_violation(ImplicitSumViolation(node))\n \n     def _check_implicit_yield_from(self, node: AnyFor) -> None:\n+        if isinstance(nodes.get_context(node), ast.AsyncFunctionDef):\n+            # Python does not support 'yield from' inside async functions\n+            return\n         is_implicit_yield_from = (\n             len(node.body) == 1 and\n             isinstance(node.body[0], ast.Expr) and\n", "issue": "False positive implicit yield violation\n# Bug report\r\n\r\n<!--\r\nHi, thanks for submitting a bug. We appreciate that.\r\n\r\nBut, we will need some information about what's wrong to help you.\r\n-->\r\n\r\n## What's wrong\r\nWith common function to split iterable by chunks WPS raises `ImplicitYieldFromViolation`\r\n<!-- Describe what is not working. Please, attach a traceback. -->\r\n```\r\ndef chunks(value, chunk_size):\r\n    \"\"\"Yield successive n-sized chunks from l.\"\"\"\r\n    for index in range(0, len(value), chunk_size):\r\n        yield value[index:index + chunk_size]\r\n```\r\n\r\n## How is that should be\r\n`ImplicitYieldFromViolation` should be raised only if no other operations with iterable item.\r\n<!-- Describe how it should work. -->\r\n\r\n<!--\r\n\r\n  Love wemake-python-styleguide? \u2764\ufe0f\r\n  Do you want your bugs to be solved faster?\r\n\r\n  Please consider supporting our collective:\r\n\ud83d\udc49  https://opencollective.com/wemake-python-styleguide/donate\r\n\r\n-->\r\n\n", "before_files": [{"content": "# -*- coding: utf-8 -*-\n\nimport ast\nfrom collections import defaultdict\nfrom typing import ClassVar, DefaultDict, List, Optional, Union\n\nfrom typing_extensions import final\n\nfrom wemake_python_styleguide.compat.aliases import AssignNodes, ForNodes\nfrom wemake_python_styleguide.compat.functions import get_assign_targets\nfrom wemake_python_styleguide.logic import (\n    nodes,\n    operators,\n    slices,\n    source,\n    walk,\n)\nfrom wemake_python_styleguide.logic.variables import (\n    is_valid_block_variable_definition,\n)\nfrom wemake_python_styleguide.types import AnyFor, AnyNodes\nfrom wemake_python_styleguide.violations.best_practices import (\n    LambdaInsideLoopViolation,\n    LoopVariableDefinitionViolation,\n    YieldInComprehensionViolation,\n)\nfrom wemake_python_styleguide.violations.complexity import (\n    TooManyForsInComprehensionViolation,\n)\nfrom wemake_python_styleguide.violations.consistency import (\n    MultilineLoopViolation,\n    MultipleIfsInComprehensionViolation,\n    UselessContinueViolation,\n    WrongLoopIterTypeViolation,\n)\nfrom wemake_python_styleguide.violations.refactoring import (\n    ImplicitItemsIteratorViolation,\n    ImplicitSumViolation,\n    ImplicitYieldFromViolation,\n    UselessLoopElseViolation,\n)\nfrom wemake_python_styleguide.visitors import base, decorators\n\n_AnyLoop = Union[AnyFor, ast.While]\n_AnyComprehension = Union[\n    ast.ListComp,\n    ast.DictComp,\n    ast.SetComp,\n    ast.GeneratorExp,\n]\n\n\n@final\n@decorators.alias('visit_any_comprehension', (\n    'visit_ListComp',\n    'visit_DictComp',\n    'visit_SetComp',\n    'visit_GeneratorExp',\n))\nclass WrongComprehensionVisitor(base.BaseNodeVisitor):\n    \"\"\"Checks comprehensions for correctness.\"\"\"\n\n    _max_ifs: ClassVar[int] = 1\n    _max_fors: ClassVar[int] = 2\n\n    def __init__(self, *args, **kwargs) -> None:\n        \"\"\"Creates a counter for tracked metrics.\"\"\"\n        super().__init__(*args, **kwargs)\n        self._fors: DefaultDict[ast.AST, int] = defaultdict(int)\n\n    def visit_comprehension(self, node: ast.comprehension) -> None:\n        \"\"\"\n        Finds multiple ``if`` and ``for`` nodes inside the comprehension.\n\n        Raises:\n            MultipleIfsInComprehensionViolation\n            TooManyForsInComprehensionViolation\n\n        \"\"\"\n        self._check_ifs(node)\n        self._check_fors(node)\n        self.generic_visit(node)\n\n    def visit_any_comprehension(self, node: _AnyComprehension) -> None:\n        \"\"\"\n        Finds incorrect patterns inside comprehensions.\n\n        Raises:\n            YieldInComprehensionViolation\n\n        \"\"\"\n        self._check_contains_yield(node)\n        self.generic_visit(node)\n\n    def _check_ifs(self, node: ast.comprehension) -> None:\n        if len(node.ifs) > self._max_ifs:\n            # We are trying to fix line number in the report,\n            # since `comprehension` does not have this property.\n            parent = nodes.get_parent(node) or node\n            self.add_violation(MultipleIfsInComprehensionViolation(parent))\n\n    def _check_fors(self, node: ast.comprehension) -> None:\n        parent = nodes.get_parent(node)\n        self._fors[parent] = len(parent.generators)  # type: ignore\n\n    def _check_contains_yield(self, node: _AnyComprehension) -> None:\n        for sub_node in ast.walk(node):\n            if isinstance(sub_node, ast.Yield):\n                self.add_violation(YieldInComprehensionViolation(node))\n\n    def _post_visit(self) -> None:\n        for node, for_count in self._fors.items():\n            if for_count > self._max_fors:\n                self.add_violation(TooManyForsInComprehensionViolation(node))\n\n\n@final\n@decorators.alias('visit_any_loop', (\n    'visit_For',\n    'visit_While',\n    'visit_AsyncFor',\n))\nclass WrongLoopVisitor(base.BaseNodeVisitor):\n    \"\"\"Responsible for examining loops.\"\"\"\n\n    def visit_any_loop(self, node: _AnyLoop) -> None:\n        \"\"\"\n        Checks ``for`` and ``while`` loops.\n\n        Raises:\n            UselessLoopElseViolation\n            LambdaInsideLoopViolation\n            MultilineLoopViolation\n\n        \"\"\"\n        self._check_loop_needs_else(node)\n        self._check_lambda_inside_loop(node)\n        self._check_useless_continue(node)\n        self._check_multiline_loop(node)\n        self.generic_visit(node)\n\n    def _does_loop_contain_node(  # TODO: move, reuse in annotations.py\n        self,\n        loop: Optional[_AnyLoop],\n        to_check: ast.Break,\n    ) -> bool:\n        if loop is None:\n            return False\n\n        for inner_node in ast.walk(loop):\n            # We are checking this specific node, not just any `break`:\n            if to_check is inner_node:\n                return True\n        return False\n\n    def _has_break(self, node: _AnyLoop) -> bool:\n        closest_loop = None\n\n        for subnode in ast.walk(node):\n            if isinstance(subnode, (*ForNodes, ast.While)):\n                if subnode is not node:\n                    closest_loop = subnode\n\n            if isinstance(subnode, ast.Break):\n                is_nested_break = self._does_loop_contain_node(\n                    closest_loop, subnode,\n                )\n                if not is_nested_break:\n                    return True\n        return False\n\n    def _check_loop_needs_else(self, node: _AnyLoop) -> None:\n        if node.orelse and not self._has_break(node):\n            self.add_violation(UselessLoopElseViolation(node))\n\n    def _check_lambda_inside_loop(self, node: _AnyLoop) -> None:\n        for subnode in node.body:\n            if walk.is_contained(subnode, (ast.Lambda,)):\n                self.add_violation(LambdaInsideLoopViolation(node))\n\n    def _check_useless_continue(self, node: _AnyLoop) -> None:\n        nodes_at_line: DefaultDict[int, List[ast.AST]] = defaultdict(list)\n        for sub_node in ast.walk(node):\n            lineno = getattr(sub_node, 'lineno', None)\n            if lineno is not None:\n                nodes_at_line[lineno].append(sub_node)\n\n        last_line = nodes_at_line[sorted(nodes_at_line.keys())[-1]]\n        if any(isinstance(last, ast.Continue) for last in last_line):\n            self.add_violation(UselessContinueViolation(node))\n\n    def _check_multiline_loop(self, node: _AnyLoop) -> None:\n        start_lineno = getattr(node, 'lineno', None)\n\n        if isinstance(node, ast.While):\n            node_to_check = node.test\n        else:\n            node_to_check = node.iter\n\n        for sub_node in ast.walk(node_to_check):\n            sub_lineno = getattr(sub_node, 'lineno', None)\n            if sub_lineno is not None and sub_lineno > start_lineno:\n                self.add_violation(MultilineLoopViolation(node))\n                break\n\n\n@final\n@decorators.alias('visit_any_for', (\n    'visit_For',\n    'visit_AsyncFor',\n))\nclass WrongLoopDefinitionVisitor(base.BaseNodeVisitor):\n    \"\"\"Responsible for ``for`` loops and comprehensions definitions.\"\"\"\n\n    _forbidden_for_iters: ClassVar[AnyNodes] = (\n        ast.List,\n        ast.ListComp,\n        ast.Dict,\n        ast.DictComp,\n        ast.Set,\n        ast.SetComp,\n        ast.GeneratorExp,\n        ast.Num,\n        ast.NameConstant,\n    )\n\n    def visit_any_for(self, node: AnyFor) -> None:\n        \"\"\"\n        Ensures that ``for`` loop definitions are correct.\n\n        Raises:\n            LoopVariableDefinitionViolation\n            WrongLoopIterTypeViolation\n            ImplicitSumViolation\n\n        \"\"\"\n        self._check_variable_definitions(node.target)\n        self._check_explicit_iter_type(node)\n        self._check_implicit_sum(node)\n        self._check_implicit_yield_from(node)\n        self.generic_visit(node)\n\n    def visit_comprehension(self, node: ast.comprehension) -> None:\n        \"\"\"\n        Ensures that comprehension definitions are correct.\n\n        Raises:\n            LoopVariableDefinitionViolation\n\n        \"\"\"\n        self._check_variable_definitions(node.target)\n        self._check_explicit_iter_type(node)\n        self.generic_visit(node)\n\n    def _check_variable_definitions(self, node: ast.AST) -> None:\n        if not is_valid_block_variable_definition(node):\n            self.add_violation(LoopVariableDefinitionViolation(node))\n\n    def _check_explicit_iter_type(\n        self,\n        node: Union[AnyFor, ast.comprehension],\n    ) -> None:\n        node_iter = operators.unwrap_unary_node(node.iter)\n        is_wrong = isinstance(node_iter, self._forbidden_for_iters)\n        is_empty = isinstance(node_iter, ast.Tuple) and not node_iter.elts\n        if is_wrong or is_empty:\n            self.add_violation(WrongLoopIterTypeViolation(node_iter))\n\n    def _check_implicit_sum(self, node: AnyFor) -> None:\n        is_implicit_sum = (\n            len(node.body) == 1 and\n            isinstance(node.body[0], ast.AugAssign) and\n            isinstance(node.body[0].op, ast.Add) and\n            isinstance(node.body[0].target, ast.Name)\n        )\n        if is_implicit_sum:\n            self.add_violation(ImplicitSumViolation(node))\n\n    def _check_implicit_yield_from(self, node: AnyFor) -> None:\n        is_implicit_yield_from = (\n            len(node.body) == 1 and\n            isinstance(node.body[0], ast.Expr) and\n            isinstance(node.body[0].value, ast.Yield)\n        )\n        if is_implicit_yield_from:\n            self.add_violation(ImplicitYieldFromViolation(node))\n\n\n@final\nclass SyncForLoopVisitor(base.BaseNodeVisitor):\n    \"\"\"We use this visitor to check just sync ``for`` loops.\"\"\"\n\n    def visit_For(self, node: ast.For) -> None:\n        \"\"\"\n        Checks for hidden patterns in sync loops.\n\n        Raises:\n            ImplicitItemsIteratorViolation\n\n        \"\"\"\n        self._check_implicit_items(node)\n        self.generic_visit(node)\n\n    def _check_implicit_items(self, node: ast.For) -> None:\n        iterable = source.node_to_string(node.iter)\n        target = source.node_to_string(node.target)\n\n        for sub in ast.walk(node):\n            if isinstance(sub, ast.Subscript):\n                if self._is_assigned_target(sub):\n                    continue\n\n                if slices.is_same_slice(iterable, target, sub):\n                    self.add_violation(ImplicitItemsIteratorViolation(node))\n                    break\n\n    def _is_assigned_target(self, node: ast.Subscript) -> bool:\n        parent = nodes.get_parent(node)\n        if not isinstance(parent, (*AssignNodes, ast.AugAssign)):\n            return False\n        return any(node == target for target in get_assign_targets(parent))\n", "path": "wemake_python_styleguide/visitors/ast/loops.py"}], "after_files": [{"content": "# -*- coding: utf-8 -*-\n\nimport ast\nfrom collections import defaultdict\nfrom typing import ClassVar, DefaultDict, List, Optional, Union\n\nfrom typing_extensions import final\n\nfrom wemake_python_styleguide.compat.aliases import AssignNodes, ForNodes\nfrom wemake_python_styleguide.compat.functions import get_assign_targets\nfrom wemake_python_styleguide.logic import (\n    nodes,\n    operators,\n    slices,\n    source,\n    walk,\n)\nfrom wemake_python_styleguide.logic.variables import (\n    is_valid_block_variable_definition,\n)\nfrom wemake_python_styleguide.types import AnyFor, AnyNodes\nfrom wemake_python_styleguide.violations.best_practices import (\n    LambdaInsideLoopViolation,\n    LoopVariableDefinitionViolation,\n    YieldInComprehensionViolation,\n)\nfrom wemake_python_styleguide.violations.complexity import (\n    TooManyForsInComprehensionViolation,\n)\nfrom wemake_python_styleguide.violations.consistency import (\n    MultilineLoopViolation,\n    MultipleIfsInComprehensionViolation,\n    UselessContinueViolation,\n    WrongLoopIterTypeViolation,\n)\nfrom wemake_python_styleguide.violations.refactoring import (\n    ImplicitItemsIteratorViolation,\n    ImplicitSumViolation,\n    ImplicitYieldFromViolation,\n    UselessLoopElseViolation,\n)\nfrom wemake_python_styleguide.visitors import base, decorators\n\n_AnyLoop = Union[AnyFor, ast.While]\n_AnyComprehension = Union[\n    ast.ListComp,\n    ast.DictComp,\n    ast.SetComp,\n    ast.GeneratorExp,\n]\n\n\n@final\n@decorators.alias('visit_any_comprehension', (\n    'visit_ListComp',\n    'visit_DictComp',\n    'visit_SetComp',\n    'visit_GeneratorExp',\n))\nclass WrongComprehensionVisitor(base.BaseNodeVisitor):\n    \"\"\"Checks comprehensions for correctness.\"\"\"\n\n    _max_ifs: ClassVar[int] = 1\n    _max_fors: ClassVar[int] = 2\n\n    def __init__(self, *args, **kwargs) -> None:\n        \"\"\"Creates a counter for tracked metrics.\"\"\"\n        super().__init__(*args, **kwargs)\n        self._fors: DefaultDict[ast.AST, int] = defaultdict(int)\n\n    def visit_comprehension(self, node: ast.comprehension) -> None:\n        \"\"\"\n        Finds multiple ``if`` and ``for`` nodes inside the comprehension.\n\n        Raises:\n            MultipleIfsInComprehensionViolation\n            TooManyForsInComprehensionViolation\n\n        \"\"\"\n        self._check_ifs(node)\n        self._check_fors(node)\n        self.generic_visit(node)\n\n    def visit_any_comprehension(self, node: _AnyComprehension) -> None:\n        \"\"\"\n        Finds incorrect patterns inside comprehensions.\n\n        Raises:\n            YieldInComprehensionViolation\n\n        \"\"\"\n        self._check_contains_yield(node)\n        self.generic_visit(node)\n\n    def _check_ifs(self, node: ast.comprehension) -> None:\n        if len(node.ifs) > self._max_ifs:\n            # We are trying to fix line number in the report,\n            # since `comprehension` does not have this property.\n            parent = nodes.get_parent(node) or node\n            self.add_violation(MultipleIfsInComprehensionViolation(parent))\n\n    def _check_fors(self, node: ast.comprehension) -> None:\n        parent = nodes.get_parent(node)\n        self._fors[parent] = len(parent.generators)  # type: ignore\n\n    def _check_contains_yield(self, node: _AnyComprehension) -> None:\n        for sub_node in ast.walk(node):\n            if isinstance(sub_node, ast.Yield):\n                self.add_violation(YieldInComprehensionViolation(node))\n\n    def _post_visit(self) -> None:\n        for node, for_count in self._fors.items():\n            if for_count > self._max_fors:\n                self.add_violation(TooManyForsInComprehensionViolation(node))\n\n\n@final\n@decorators.alias('visit_any_loop', (\n    'visit_For',\n    'visit_While',\n    'visit_AsyncFor',\n))\nclass WrongLoopVisitor(base.BaseNodeVisitor):\n    \"\"\"Responsible for examining loops.\"\"\"\n\n    def visit_any_loop(self, node: _AnyLoop) -> None:\n        \"\"\"\n        Checks ``for`` and ``while`` loops.\n\n        Raises:\n            UselessLoopElseViolation\n            LambdaInsideLoopViolation\n            MultilineLoopViolation\n\n        \"\"\"\n        self._check_loop_needs_else(node)\n        self._check_lambda_inside_loop(node)\n        self._check_useless_continue(node)\n        self._check_multiline_loop(node)\n        self.generic_visit(node)\n\n    def _does_loop_contain_node(  # TODO: move, reuse in annotations.py\n        self,\n        loop: Optional[_AnyLoop],\n        to_check: ast.Break,\n    ) -> bool:\n        if loop is None:\n            return False\n\n        for inner_node in ast.walk(loop):\n            # We are checking this specific node, not just any `break`:\n            if to_check is inner_node:\n                return True\n        return False\n\n    def _has_break(self, node: _AnyLoop) -> bool:\n        closest_loop = None\n\n        for subnode in ast.walk(node):\n            if isinstance(subnode, (*ForNodes, ast.While)):\n                if subnode is not node:\n                    closest_loop = subnode\n\n            if isinstance(subnode, ast.Break):\n                is_nested_break = self._does_loop_contain_node(\n                    closest_loop, subnode,\n                )\n                if not is_nested_break:\n                    return True\n        return False\n\n    def _check_loop_needs_else(self, node: _AnyLoop) -> None:\n        if node.orelse and not self._has_break(node):\n            self.add_violation(UselessLoopElseViolation(node))\n\n    def _check_lambda_inside_loop(self, node: _AnyLoop) -> None:\n        for subnode in node.body:\n            if walk.is_contained(subnode, (ast.Lambda,)):\n                self.add_violation(LambdaInsideLoopViolation(node))\n\n    def _check_useless_continue(self, node: _AnyLoop) -> None:\n        nodes_at_line: DefaultDict[int, List[ast.AST]] = defaultdict(list)\n        for sub_node in ast.walk(node):\n            lineno = getattr(sub_node, 'lineno', None)\n            if lineno is not None:\n                nodes_at_line[lineno].append(sub_node)\n\n        last_line = nodes_at_line[sorted(nodes_at_line.keys())[-1]]\n        if any(isinstance(last, ast.Continue) for last in last_line):\n            self.add_violation(UselessContinueViolation(node))\n\n    def _check_multiline_loop(self, node: _AnyLoop) -> None:\n        start_lineno = getattr(node, 'lineno', None)\n\n        if isinstance(node, ast.While):\n            node_to_check = node.test\n        else:\n            node_to_check = node.iter\n\n        for sub_node in ast.walk(node_to_check):\n            sub_lineno = getattr(sub_node, 'lineno', None)\n            if sub_lineno is not None and sub_lineno > start_lineno:\n                self.add_violation(MultilineLoopViolation(node))\n                break\n\n\n@final\n@decorators.alias('visit_any_for', (\n    'visit_For',\n    'visit_AsyncFor',\n))\nclass WrongLoopDefinitionVisitor(base.BaseNodeVisitor):\n    \"\"\"Responsible for ``for`` loops and comprehensions definitions.\"\"\"\n\n    _forbidden_for_iters: ClassVar[AnyNodes] = (\n        ast.List,\n        ast.ListComp,\n        ast.Dict,\n        ast.DictComp,\n        ast.Set,\n        ast.SetComp,\n        ast.GeneratorExp,\n        ast.Num,\n        ast.NameConstant,\n    )\n\n    def visit_any_for(self, node: AnyFor) -> None:\n        \"\"\"\n        Ensures that ``for`` loop definitions are correct.\n\n        Raises:\n            LoopVariableDefinitionViolation\n            WrongLoopIterTypeViolation\n            ImplicitSumViolation\n\n        \"\"\"\n        self._check_variable_definitions(node.target)\n        self._check_explicit_iter_type(node)\n        self._check_implicit_sum(node)\n        self._check_implicit_yield_from(node)\n        self.generic_visit(node)\n\n    def visit_comprehension(self, node: ast.comprehension) -> None:\n        \"\"\"\n        Ensures that comprehension definitions are correct.\n\n        Raises:\n            LoopVariableDefinitionViolation\n\n        \"\"\"\n        self._check_variable_definitions(node.target)\n        self._check_explicit_iter_type(node)\n        self.generic_visit(node)\n\n    def _check_variable_definitions(self, node: ast.AST) -> None:\n        if not is_valid_block_variable_definition(node):\n            self.add_violation(LoopVariableDefinitionViolation(node))\n\n    def _check_explicit_iter_type(\n        self,\n        node: Union[AnyFor, ast.comprehension],\n    ) -> None:\n        node_iter = operators.unwrap_unary_node(node.iter)\n        is_wrong = isinstance(node_iter, self._forbidden_for_iters)\n        is_empty = isinstance(node_iter, ast.Tuple) and not node_iter.elts\n        if is_wrong or is_empty:\n            self.add_violation(WrongLoopIterTypeViolation(node_iter))\n\n    def _check_implicit_sum(self, node: AnyFor) -> None:\n        is_implicit_sum = (\n            len(node.body) == 1 and\n            isinstance(node.body[0], ast.AugAssign) and\n            isinstance(node.body[0].op, ast.Add) and\n            isinstance(node.body[0].target, ast.Name)\n        )\n        if is_implicit_sum:\n            self.add_violation(ImplicitSumViolation(node))\n\n    def _check_implicit_yield_from(self, node: AnyFor) -> None:\n        if isinstance(nodes.get_context(node), ast.AsyncFunctionDef):\n            # Python does not support 'yield from' inside async functions\n            return\n        is_implicit_yield_from = (\n            len(node.body) == 1 and\n            isinstance(node.body[0], ast.Expr) and\n            isinstance(node.body[0].value, ast.Yield)\n        )\n        if is_implicit_yield_from:\n            self.add_violation(ImplicitYieldFromViolation(node))\n\n\n@final\nclass SyncForLoopVisitor(base.BaseNodeVisitor):\n    \"\"\"We use this visitor to check just sync ``for`` loops.\"\"\"\n\n    def visit_For(self, node: ast.For) -> None:\n        \"\"\"\n        Checks for hidden patterns in sync loops.\n\n        Raises:\n            ImplicitItemsIteratorViolation\n\n        \"\"\"\n        self._check_implicit_items(node)\n        self.generic_visit(node)\n\n    def _check_implicit_items(self, node: ast.For) -> None:\n        iterable = source.node_to_string(node.iter)\n        target = source.node_to_string(node.target)\n\n        for sub in ast.walk(node):\n            if isinstance(sub, ast.Subscript):\n                if self._is_assigned_target(sub):\n                    continue\n\n                if slices.is_same_slice(iterable, target, sub):\n                    self.add_violation(ImplicitItemsIteratorViolation(node))\n                    break\n\n    def _is_assigned_target(self, node: ast.Subscript) -> bool:\n        parent = nodes.get_parent(node)\n        if not isinstance(parent, (*AssignNodes, ast.AugAssign)):\n            return False\n        return any(node == target for target in get_assign_targets(parent))\n", "path": "wemake_python_styleguide/visitors/ast/loops.py"}]}