We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Type annotation check doesn't work for type aliases
# 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
Type annotation check doesn't work if type aliases are used. For example, this code
```
type_alias = Literal[None]

def my_func(arg: type_alias):
    pass
```
passes flake8 checks without raising `WPS701` error, while this code
```
def my_func(arg: Literal[None]):
    pass
```
makes flake8 complain: "WPS701 Found useless `Literal[None]` typing annotation".
## How is that should be
Type annotation errors should be raised whether type aliases are used or not.

## System information
wemake-python-styleguide: 0.12.5

--- 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/violations/annotations.py`
Content:
```
1 # -*- coding: utf-8 -*-
2 
3 """
4 These checks help to prevent incorrect usage of Python 3 typing annotations.
5 
6 While they maybe of a great help in writing clear
7 and concise code, they still can be abused.
8 
9 Once again, these rules are highly subjective. But, we love them.
10 
11 .. currentmodule:: wemake_python_styleguide.violations.annotations
12 
13 Summary
14 -------
15 
16 .. autosummary::
17    :nosignatures:
18 
19    LiteralNoneViolation
20    NestedAnnotationsViolation
21    UnionNestedInOptionalViolation
22 
23 Annotation checks
24 ------------------
25 
26 .. autoclass:: LiteralNoneViolation
27 .. autoclass:: NestedAnnotationsViolation
28 .. autoclass:: UnionNestedInOptionalViolation
29 
30 """
31 
32 from typing_extensions import final
33 
34 from wemake_python_styleguide.violations.base import ASTViolation
35 
36 
37 @final
38 class LiteralNoneViolation(ASTViolation):
39     """
40     Forbids to use ``Literal[None]`` typing annotation.
41 
42     Reasoning:
43         Literal[None] is just the same as None.
44         There's no need to use the first version.
45         It is not type related, it is a consistency rule.
46 
47     Solution:
48         Replace ``Literal[None]`` with ``None``.
49 
50     Example::
51 
52         # Correct:
53         def func(empty: None):
54             '''Empty function.'''
55 
56         # Wrong:
57         def func(empty: Literal[None]):
58             '''Empty function.'''
59 
60     .. versionadded:: 0.13.0
61 
62     """
63 
64     code = 700
65     error_template = 'Found useless `Literal[None]` typing annotation'
66 
67 
68 @final
69 class NestedAnnotationsViolation(ASTViolation):
70     """
71     Forbids use of nested Literal and Union Annotation.
72 
73     Reasoning:
74         There is no need to nest certain annotations of the same type.
75         They are exactly equivalent to the flattened version.
76         Use the flattened version for consistency.
77 
78     Solution:
79         Flatten consecutively nested ``typing.Literal`` and ``typing.Union``.
80 
81     Example::
82 
83         # Correct:
84         Literal[1, 2, 3, "foo", 5, None]
85         Union[int, str, float]
86 
87         # Wrong:
88         Literal[Literal[Literal[1, 2, 3], "foo"], 5, None]
89         Union[Union[int, str], float]
90 
91     .. versionadded:: 0.13.0
92 
93     """
94 
95     error_template = 'Found redundant nested typing annotation'
96     code = 701
97 
98 
99 @final
100 class UnionNestedInOptionalViolation(ASTViolation):
101     """
102     Forbids to use ``Optional[Union[int, str]]`` annotation.
103 
104     Reasoning:
105         Optional[Union[int, str]] equals to Union[int, str, None].
106         Use Union[int, str, None] version for consistency.
107 
108     Solution:
109         Replace ``Optional[Union[int, str]]`` with ``Union[int, str, None]``.
110 
111     Example::
112 
113         # Correct:
114         Union[int, str, None]
115 
116         # Wrong:
117         Optional[Union[int, str]]
118 
119     .. versionadded:: 0.13.0
120 
121     """
122 
123     error_template = 'Found typing annotation with `Union` nested in `Optional`'
124     code = 702
125
```

Path: `wemake_python_styleguide/visitors/ast/annotations.py`
Content:
```
1 # -*- coding: utf-8 -*-
2 
3 import ast
4 from typing import ClassVar, FrozenSet, Optional
5 
6 from typing_extensions import final
7 
8 from wemake_python_styleguide.logic import source
9 from wemake_python_styleguide.types import AnyFunctionDef
10 from wemake_python_styleguide.violations.annotations import (
11     LiteralNoneViolation,
12     NestedAnnotationsViolation,
13     UnionNestedInOptionalViolation,
14 )
15 from wemake_python_styleguide.violations.consistency import (
16     MultilineFunctionAnnotationViolation,
17 )
18 from wemake_python_styleguide.visitors.base import BaseNodeVisitor
19 from wemake_python_styleguide.visitors.decorators import alias
20 
21 
22 @alias('visit_any_function', (
23     'visit_FunctionDef',
24     'visit_AsyncFunctionDef',
25 ))
26 class _GenericAnnotationVisitor(BaseNodeVisitor):
27     """Base class for all annotations visitors."""
28 
29     _possible_prefixes: ClassVar[FrozenSet[str]] = frozenset((
30         'typing.',
31         'typing_extensions.',
32     ))
33 
34     @final
35     def visit_AnnAssign(self, node: ast.AnnAssign) -> None:
36         """
37         Checks for assigned value annotation.
38 
39         Raises:
40             LiteralNoneAnnotation
41 
42         """
43         self._check_annotation(node.annotation)
44         self.generic_visit(node)
45 
46     @final
47     def visit_any_function(self, node: AnyFunctionDef) -> None:
48         """
49         Checks return type annotations.
50 
51         Raises:
52             LiteralNoneAnnotation
53 
54         """
55         self._check_annotation(node.returns)
56         self.generic_visit(node)
57 
58     @final
59     def visit_arg(self, node: ast.arg) -> None:
60         """
61         Checks arguments annotations.
62 
63         Raises:
64             LiteralNoneAnnotation
65 
66         """
67         self._check_annotation(node.annotation)
68         self.generic_visit(node)
69 
70     @final
71     def _get_annotation(self, node: ast.AST) -> str:
72         """Smartly turns annotation node to string."""
73         full_annotation = source.node_to_string(node)
74         for prefix in self._possible_prefixes:
75             full_annotation = full_annotation.replace(prefix, '')
76         return full_annotation
77 
78     def _check_annotation(self, annotation: Optional[ast.expr]) -> None:
79         """The only method that need to me implemented in child visitors."""
80 
81 
82 @final
83 class SemanticAnnotationVisitor(_GenericAnnotationVisitor):
84     """Ensures that nested annotations are used correctly."""
85 
86     _flat_types: ClassVar[FrozenSet[str]] = frozenset((
87         'Literal',
88         'Union',
89         'Annotated',
90     ))
91 
92     def _check_annotation(self, annotation: Optional[ast.expr]) -> None:
93         if not annotation:
94             return
95 
96         self._check_nested_annotations(annotation)
97         self._check_literal_none(annotation)
98         self._check_union_nested_in_optional(annotation)
99 
100     def _check_nested_annotations(self, annotation: ast.expr) -> None:
101         annotation_string = self._get_annotation(annotation)
102         for flat_type in self._flat_types:
103             if annotation_string.count(flat_type) > 1:
104                 self.add_violation(NestedAnnotationsViolation(annotation))
105 
106     def _check_literal_none(self, annotation: ast.expr) -> None:
107         annotation_string = self._get_annotation(annotation)
108         if 'Literal[None]' in annotation_string:
109             self.add_violation(LiteralNoneViolation(annotation))
110 
111     def _check_union_nested_in_optional(self, annotation: ast.expr) -> None:
112         annotation_string = self._get_annotation(annotation)
113         if 'Optional[Union[' in annotation_string:
114             self.add_violation(UnionNestedInOptionalViolation(annotation))
115 
116 
117 @final
118 @alias('visit_any_function', (
119     'visit_FunctionDef',
120     'visit_AsyncFunctionDef',
121 ))
122 class WrongAnnotationVisitor(BaseNodeVisitor):
123     """Ensures that annotations are used correctly."""
124 
125     def visit_any_function(self, node: AnyFunctionDef) -> None:
126         """
127         Checks return type annotations.
128 
129         Raises:
130             MultilineFunctionAnnotationViolation
131             LiteralNoneAnnotation
132 
133         """
134         self._check_return_annotation(node)
135         self.generic_visit(node)
136 
137     def visit_arg(self, node: ast.arg) -> None:
138         """
139         Checks arguments annotations.
140 
141         Raises:
142             MultilineFunctionAnnotationViolation
143             LiteralNoneAnnotation
144 
145         """
146         self._check_arg_annotation(node)
147         self.generic_visit(node)
148 
149     def _check_arg_annotation(self, node: ast.arg) -> None:
150         for sub_node in ast.walk(node):
151             lineno = getattr(sub_node, 'lineno', None)
152             if lineno and lineno != node.lineno:
153                 self.add_violation(MultilineFunctionAnnotationViolation(node))
154                 return
155 
156     def _check_return_annotation(self, node: AnyFunctionDef) -> None:
157         if not node.returns:
158             return
159 
160         for sub_node in ast.walk(node.returns):
161             lineno = getattr(sub_node, 'lineno', None)
162             if lineno and lineno != node.returns.lineno:
163                 self.add_violation(MultilineFunctionAnnotationViolation(node))
164                 return
165
```
--- 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/violations/annotations.py b/wemake_python_styleguide/violations/annotations.py
--- a/wemake_python_styleguide/violations/annotations.py
+++ b/wemake_python_styleguide/violations/annotations.py
@@ -54,6 +54,8 @@
             '''Empty function.'''
 
         # Wrong:
+        NONE_ALIAS = Literal[None]
+
         def func(empty: Literal[None]):
             '''Empty function.'''
 
diff --git a/wemake_python_styleguide/visitors/ast/annotations.py b/wemake_python_styleguide/visitors/ast/annotations.py
--- a/wemake_python_styleguide/visitors/ast/annotations.py
+++ b/wemake_python_styleguide/visitors/ast/annotations.py
@@ -1,7 +1,9 @@
 # -*- coding: utf-8 -*-
 
 import ast
-from typing import ClassVar, FrozenSet, Optional
+import re
+from typing import ClassVar, FrozenSet, Union
+from typing.re import Pattern
 
 from typing_extensions import final
 
@@ -31,6 +33,11 @@
         'typing_extensions.',
     ))
 
+    def visit_Assign(self, node: ast.Assign) -> None:
+        """Checks assignment patterns."""
+        self._check_annotation(node)
+        self.generic_visit(node)
+
     @final
     def visit_AnnAssign(self, node: ast.AnnAssign) -> None:
         """
@@ -75,7 +82,9 @@
             full_annotation = full_annotation.replace(prefix, '')
         return full_annotation
 
-    def _check_annotation(self, annotation: Optional[ast.expr]) -> None:
+    def _check_annotation(
+        self, annotation: Union[ast.expr, ast.Assign, None],
+    ) -> None:
         """The only method that need to me implemented in child visitors."""
 
 
@@ -83,13 +92,17 @@
 class SemanticAnnotationVisitor(_GenericAnnotationVisitor):
     """Ensures that nested annotations are used correctly."""
 
-    _flat_types: ClassVar[FrozenSet[str]] = frozenset((
-        'Literal',
-        'Union',
-        'Annotated',
+    # matches nested annotation like Literal[Literal[]],
+    # but not neighbors like Literal[], Literal[]
+    _flat_types: ClassVar[FrozenSet[Pattern]] = frozenset((
+        re.compile(r'^.*Literal\[[^\]]*Literal'),
+        re.compile(r'^.*Union\[[^\]]*Union'),
+        re.compile(r'^.*Annotated\[[^\]]*Annotated'),
     ))
 
-    def _check_annotation(self, annotation: Optional[ast.expr]) -> None:
+    def _check_annotation(
+        self, annotation: Union[ast.expr, ast.Assign, None],
+    ) -> None:
         if not annotation:
             return
 
@@ -97,18 +110,28 @@
         self._check_literal_none(annotation)
         self._check_union_nested_in_optional(annotation)
 
-    def _check_nested_annotations(self, annotation: ast.expr) -> None:
+    def _check_nested_annotations(
+        self, annotation: Union[ast.expr, ast.Assign],
+    ) -> None:
         annotation_string = self._get_annotation(annotation)
         for flat_type in self._flat_types:
-            if annotation_string.count(flat_type) > 1:
+            if flat_type.search(annotation_string):
                 self.add_violation(NestedAnnotationsViolation(annotation))
 
-    def _check_literal_none(self, annotation: ast.expr) -> None:
+    def _check_literal_none(
+        self, annotation: Union[ast.expr, ast.Assign],
+    ) -> None:
         annotation_string = self._get_annotation(annotation)
-        if 'Literal[None]' in annotation_string:
+        assign_string = (
+            isinstance(annotation, ast.Assign) and
+            isinstance(annotation.value, ast.Str)
+        )
+        if not assign_string and 'Literal[None]' in annotation_string:
             self.add_violation(LiteralNoneViolation(annotation))
 
-    def _check_union_nested_in_optional(self, annotation: ast.expr) -> None:
+    def _check_union_nested_in_optional(
+        self, annotation: Union[ast.expr, ast.Assign],
+    ) -> None:
         annotation_string = self._get_annotation(annotation)
         if 'Optional[Union[' in annotation_string:
             self.add_violation(UnionNestedInOptionalViolation(annotation))

{"golden_diff": "diff --git a/wemake_python_styleguide/violations/annotations.py b/wemake_python_styleguide/violations/annotations.py\n--- a/wemake_python_styleguide/violations/annotations.py\n+++ b/wemake_python_styleguide/violations/annotations.py\n@@ -54,6 +54,8 @@\n             '''Empty function.'''\n \n         # Wrong:\n+        NONE_ALIAS = Literal[None]\n+\n         def func(empty: Literal[None]):\n             '''Empty function.'''\n \ndiff --git a/wemake_python_styleguide/visitors/ast/annotations.py b/wemake_python_styleguide/visitors/ast/annotations.py\n--- a/wemake_python_styleguide/visitors/ast/annotations.py\n+++ b/wemake_python_styleguide/visitors/ast/annotations.py\n@@ -1,7 +1,9 @@\n # -*- coding: utf-8 -*-\n \n import ast\n-from typing import ClassVar, FrozenSet, Optional\n+import re\n+from typing import ClassVar, FrozenSet, Union\n+from typing.re import Pattern\n \n from typing_extensions import final\n \n@@ -31,6 +33,11 @@\n         'typing_extensions.',\n     ))\n \n+    def visit_Assign(self, node: ast.Assign) -> None:\n+        \"\"\"Checks assignment patterns.\"\"\"\n+        self._check_annotation(node)\n+        self.generic_visit(node)\n+\n     @final\n     def visit_AnnAssign(self, node: ast.AnnAssign) -> None:\n         \"\"\"\n@@ -75,7 +82,9 @@\n             full_annotation = full_annotation.replace(prefix, '')\n         return full_annotation\n \n-    def _check_annotation(self, annotation: Optional[ast.expr]) -> None:\n+    def _check_annotation(\n+        self, annotation: Union[ast.expr, ast.Assign, None],\n+    ) -> None:\n         \"\"\"The only method that need to me implemented in child visitors.\"\"\"\n \n \n@@ -83,13 +92,17 @@\n class SemanticAnnotationVisitor(_GenericAnnotationVisitor):\n     \"\"\"Ensures that nested annotations are used correctly.\"\"\"\n \n-    _flat_types: ClassVar[FrozenSet[str]] = frozenset((\n-        'Literal',\n-        'Union',\n-        'Annotated',\n+    # matches nested annotation like Literal[Literal[]],\n+    # but not neighbors like Literal[], Literal[]\n+    _flat_types: ClassVar[FrozenSet[Pattern]] = frozenset((\n+        re.compile(r'^.*Literal\\[[^\\]]*Literal'),\n+        re.compile(r'^.*Union\\[[^\\]]*Union'),\n+        re.compile(r'^.*Annotated\\[[^\\]]*Annotated'),\n     ))\n \n-    def _check_annotation(self, annotation: Optional[ast.expr]) -> None:\n+    def _check_annotation(\n+        self, annotation: Union[ast.expr, ast.Assign, None],\n+    ) -> None:\n         if not annotation:\n             return\n \n@@ -97,18 +110,28 @@\n         self._check_literal_none(annotation)\n         self._check_union_nested_in_optional(annotation)\n \n-    def _check_nested_annotations(self, annotation: ast.expr) -> None:\n+    def _check_nested_annotations(\n+        self, annotation: Union[ast.expr, ast.Assign],\n+    ) -> None:\n         annotation_string = self._get_annotation(annotation)\n         for flat_type in self._flat_types:\n-            if annotation_string.count(flat_type) > 1:\n+            if flat_type.search(annotation_string):\n                 self.add_violation(NestedAnnotationsViolation(annotation))\n \n-    def _check_literal_none(self, annotation: ast.expr) -> None:\n+    def _check_literal_none(\n+        self, annotation: Union[ast.expr, ast.Assign],\n+    ) -> None:\n         annotation_string = self._get_annotation(annotation)\n-        if 'Literal[None]' in annotation_string:\n+        assign_string = (\n+            isinstance(annotation, ast.Assign) and\n+            isinstance(annotation.value, ast.Str)\n+        )\n+        if not assign_string and 'Literal[None]' in annotation_string:\n             self.add_violation(LiteralNoneViolation(annotation))\n \n-    def _check_union_nested_in_optional(self, annotation: ast.expr) -> None:\n+    def _check_union_nested_in_optional(\n+        self, annotation: Union[ast.expr, ast.Assign],\n+    ) -> None:\n         annotation_string = self._get_annotation(annotation)\n         if 'Optional[Union[' in annotation_string:\n             self.add_violation(UnionNestedInOptionalViolation(annotation))\n", "issue": "Type annotation check doesn't work for type aliases\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\nType annotation check doesn't work if type aliases are used. For example, this code\r\n```\r\ntype_alias = Literal[None]\r\n\r\ndef my_func(arg: type_alias):\r\n    pass\r\n```\r\npasses flake8 checks without raising `WPS701` error, while this code\r\n```\r\ndef my_func(arg: Literal[None]):\r\n    pass\r\n```\r\nmakes flake8 complain: \"WPS701 Found useless `Literal[None]` typing annotation\".\r\n## How is that should be\r\nType annotation errors should be raised whether type aliases are used or not.\r\n\r\n## System information\r\nwemake-python-styleguide: 0.12.5\n", "before_files": [{"content": "# -*- coding: utf-8 -*-\n\n\"\"\"\nThese checks help to prevent incorrect usage of Python 3 typing annotations.\n\nWhile they maybe of a great help in writing clear\nand concise code, they still can be abused.\n\nOnce again, these rules are highly subjective. But, we love them.\n\n.. currentmodule:: wemake_python_styleguide.violations.annotations\n\nSummary\n-------\n\n.. autosummary::\n   :nosignatures:\n\n   LiteralNoneViolation\n   NestedAnnotationsViolation\n   UnionNestedInOptionalViolation\n\nAnnotation checks\n------------------\n\n.. autoclass:: LiteralNoneViolation\n.. autoclass:: NestedAnnotationsViolation\n.. autoclass:: UnionNestedInOptionalViolation\n\n\"\"\"\n\nfrom typing_extensions import final\n\nfrom wemake_python_styleguide.violations.base import ASTViolation\n\n\n@final\nclass LiteralNoneViolation(ASTViolation):\n    \"\"\"\n    Forbids to use ``Literal[None]`` typing annotation.\n\n    Reasoning:\n        Literal[None] is just the same as None.\n        There's no need to use the first version.\n        It is not type related, it is a consistency rule.\n\n    Solution:\n        Replace ``Literal[None]`` with ``None``.\n\n    Example::\n\n        # Correct:\n        def func(empty: None):\n            '''Empty function.'''\n\n        # Wrong:\n        def func(empty: Literal[None]):\n            '''Empty function.'''\n\n    .. versionadded:: 0.13.0\n\n    \"\"\"\n\n    code = 700\n    error_template = 'Found useless `Literal[None]` typing annotation'\n\n\n@final\nclass NestedAnnotationsViolation(ASTViolation):\n    \"\"\"\n    Forbids use of nested Literal and Union Annotation.\n\n    Reasoning:\n        There is no need to nest certain annotations of the same type.\n        They are exactly equivalent to the flattened version.\n        Use the flattened version for consistency.\n\n    Solution:\n        Flatten consecutively nested ``typing.Literal`` and ``typing.Union``.\n\n    Example::\n\n        # Correct:\n        Literal[1, 2, 3, \"foo\", 5, None]\n        Union[int, str, float]\n\n        # Wrong:\n        Literal[Literal[Literal[1, 2, 3], \"foo\"], 5, None]\n        Union[Union[int, str], float]\n\n    .. versionadded:: 0.13.0\n\n    \"\"\"\n\n    error_template = 'Found redundant nested typing annotation'\n    code = 701\n\n\n@final\nclass UnionNestedInOptionalViolation(ASTViolation):\n    \"\"\"\n    Forbids to use ``Optional[Union[int, str]]`` annotation.\n\n    Reasoning:\n        Optional[Union[int, str]] equals to Union[int, str, None].\n        Use Union[int, str, None] version for consistency.\n\n    Solution:\n        Replace ``Optional[Union[int, str]]`` with ``Union[int, str, None]``.\n\n    Example::\n\n        # Correct:\n        Union[int, str, None]\n\n        # Wrong:\n        Optional[Union[int, str]]\n\n    .. versionadded:: 0.13.0\n\n    \"\"\"\n\n    error_template = 'Found typing annotation with `Union` nested in `Optional`'\n    code = 702\n", "path": "wemake_python_styleguide/violations/annotations.py"}, {"content": "# -*- coding: utf-8 -*-\n\nimport ast\nfrom typing import ClassVar, FrozenSet, Optional\n\nfrom typing_extensions import final\n\nfrom wemake_python_styleguide.logic import source\nfrom wemake_python_styleguide.types import AnyFunctionDef\nfrom wemake_python_styleguide.violations.annotations import (\n    LiteralNoneViolation,\n    NestedAnnotationsViolation,\n    UnionNestedInOptionalViolation,\n)\nfrom wemake_python_styleguide.violations.consistency import (\n    MultilineFunctionAnnotationViolation,\n)\nfrom wemake_python_styleguide.visitors.base import BaseNodeVisitor\nfrom wemake_python_styleguide.visitors.decorators import alias\n\n\n@alias('visit_any_function', (\n    'visit_FunctionDef',\n    'visit_AsyncFunctionDef',\n))\nclass _GenericAnnotationVisitor(BaseNodeVisitor):\n    \"\"\"Base class for all annotations visitors.\"\"\"\n\n    _possible_prefixes: ClassVar[FrozenSet[str]] = frozenset((\n        'typing.',\n        'typing_extensions.',\n    ))\n\n    @final\n    def visit_AnnAssign(self, node: ast.AnnAssign) -> None:\n        \"\"\"\n        Checks for assigned value annotation.\n\n        Raises:\n            LiteralNoneAnnotation\n\n        \"\"\"\n        self._check_annotation(node.annotation)\n        self.generic_visit(node)\n\n    @final\n    def visit_any_function(self, node: AnyFunctionDef) -> None:\n        \"\"\"\n        Checks return type annotations.\n\n        Raises:\n            LiteralNoneAnnotation\n\n        \"\"\"\n        self._check_annotation(node.returns)\n        self.generic_visit(node)\n\n    @final\n    def visit_arg(self, node: ast.arg) -> None:\n        \"\"\"\n        Checks arguments annotations.\n\n        Raises:\n            LiteralNoneAnnotation\n\n        \"\"\"\n        self._check_annotation(node.annotation)\n        self.generic_visit(node)\n\n    @final\n    def _get_annotation(self, node: ast.AST) -> str:\n        \"\"\"Smartly turns annotation node to string.\"\"\"\n        full_annotation = source.node_to_string(node)\n        for prefix in self._possible_prefixes:\n            full_annotation = full_annotation.replace(prefix, '')\n        return full_annotation\n\n    def _check_annotation(self, annotation: Optional[ast.expr]) -> None:\n        \"\"\"The only method that need to me implemented in child visitors.\"\"\"\n\n\n@final\nclass SemanticAnnotationVisitor(_GenericAnnotationVisitor):\n    \"\"\"Ensures that nested annotations are used correctly.\"\"\"\n\n    _flat_types: ClassVar[FrozenSet[str]] = frozenset((\n        'Literal',\n        'Union',\n        'Annotated',\n    ))\n\n    def _check_annotation(self, annotation: Optional[ast.expr]) -> None:\n        if not annotation:\n            return\n\n        self._check_nested_annotations(annotation)\n        self._check_literal_none(annotation)\n        self._check_union_nested_in_optional(annotation)\n\n    def _check_nested_annotations(self, annotation: ast.expr) -> None:\n        annotation_string = self._get_annotation(annotation)\n        for flat_type in self._flat_types:\n            if annotation_string.count(flat_type) > 1:\n                self.add_violation(NestedAnnotationsViolation(annotation))\n\n    def _check_literal_none(self, annotation: ast.expr) -> None:\n        annotation_string = self._get_annotation(annotation)\n        if 'Literal[None]' in annotation_string:\n            self.add_violation(LiteralNoneViolation(annotation))\n\n    def _check_union_nested_in_optional(self, annotation: ast.expr) -> None:\n        annotation_string = self._get_annotation(annotation)\n        if 'Optional[Union[' in annotation_string:\n            self.add_violation(UnionNestedInOptionalViolation(annotation))\n\n\n@final\n@alias('visit_any_function', (\n    'visit_FunctionDef',\n    'visit_AsyncFunctionDef',\n))\nclass WrongAnnotationVisitor(BaseNodeVisitor):\n    \"\"\"Ensures that annotations are used correctly.\"\"\"\n\n    def visit_any_function(self, node: AnyFunctionDef) -> None:\n        \"\"\"\n        Checks return type annotations.\n\n        Raises:\n            MultilineFunctionAnnotationViolation\n            LiteralNoneAnnotation\n\n        \"\"\"\n        self._check_return_annotation(node)\n        self.generic_visit(node)\n\n    def visit_arg(self, node: ast.arg) -> None:\n        \"\"\"\n        Checks arguments annotations.\n\n        Raises:\n            MultilineFunctionAnnotationViolation\n            LiteralNoneAnnotation\n\n        \"\"\"\n        self._check_arg_annotation(node)\n        self.generic_visit(node)\n\n    def _check_arg_annotation(self, node: ast.arg) -> None:\n        for sub_node in ast.walk(node):\n            lineno = getattr(sub_node, 'lineno', None)\n            if lineno and lineno != node.lineno:\n                self.add_violation(MultilineFunctionAnnotationViolation(node))\n                return\n\n    def _check_return_annotation(self, node: AnyFunctionDef) -> None:\n        if not node.returns:\n            return\n\n        for sub_node in ast.walk(node.returns):\n            lineno = getattr(sub_node, 'lineno', None)\n            if lineno and lineno != node.returns.lineno:\n                self.add_violation(MultilineFunctionAnnotationViolation(node))\n                return\n", "path": "wemake_python_styleguide/visitors/ast/annotations.py"}], "after_files": [{"content": "# -*- coding: utf-8 -*-\n\n\"\"\"\nThese checks help to prevent incorrect usage of Python 3 typing annotations.\n\nWhile they maybe of a great help in writing clear\nand concise code, they still can be abused.\n\nOnce again, these rules are highly subjective. But, we love them.\n\n.. currentmodule:: wemake_python_styleguide.violations.annotations\n\nSummary\n-------\n\n.. autosummary::\n   :nosignatures:\n\n   LiteralNoneViolation\n   NestedAnnotationsViolation\n   UnionNestedInOptionalViolation\n\nAnnotation checks\n------------------\n\n.. autoclass:: LiteralNoneViolation\n.. autoclass:: NestedAnnotationsViolation\n.. autoclass:: UnionNestedInOptionalViolation\n\n\"\"\"\n\nfrom typing_extensions import final\n\nfrom wemake_python_styleguide.violations.base import ASTViolation\n\n\n@final\nclass LiteralNoneViolation(ASTViolation):\n    \"\"\"\n    Forbids to use ``Literal[None]`` typing annotation.\n\n    Reasoning:\n        Literal[None] is just the same as None.\n        There's no need to use the first version.\n        It is not type related, it is a consistency rule.\n\n    Solution:\n        Replace ``Literal[None]`` with ``None``.\n\n    Example::\n\n        # Correct:\n        def func(empty: None):\n            '''Empty function.'''\n\n        # Wrong:\n        NONE_ALIAS = Literal[None]\n\n        def func(empty: Literal[None]):\n            '''Empty function.'''\n\n    .. versionadded:: 0.13.0\n\n    \"\"\"\n\n    code = 700\n    error_template = 'Found useless `Literal[None]` typing annotation'\n\n\n@final\nclass NestedAnnotationsViolation(ASTViolation):\n    \"\"\"\n    Forbids use of nested Literal and Union Annotation.\n\n    Reasoning:\n        There is no need to nest certain annotations of the same type.\n        They are exactly equivalent to the flattened version.\n        Use the flattened version for consistency.\n\n    Solution:\n        Flatten consecutively nested ``typing.Literal`` and ``typing.Union``.\n\n    Example::\n\n        # Correct:\n        Literal[1, 2, 3, \"foo\", 5, None]\n        Union[int, str, float]\n\n        # Wrong:\n        Literal[Literal[Literal[1, 2, 3], \"foo\"], 5, None]\n        Union[Union[int, str], float]\n\n    .. versionadded:: 0.13.0\n\n    \"\"\"\n\n    error_template = 'Found redundant nested typing annotation'\n    code = 701\n\n\n@final\nclass UnionNestedInOptionalViolation(ASTViolation):\n    \"\"\"\n    Forbids to use ``Optional[Union[int, str]]`` annotation.\n\n    Reasoning:\n        Optional[Union[int, str]] equals to Union[int, str, None].\n        Use Union[int, str, None] version for consistency.\n\n    Solution:\n        Replace ``Optional[Union[int, str]]`` with ``Union[int, str, None]``.\n\n    Example::\n\n        # Correct:\n        Union[int, str, None]\n\n        # Wrong:\n        Optional[Union[int, str]]\n\n    .. versionadded:: 0.13.0\n\n    \"\"\"\n\n    error_template = 'Found typing annotation with `Union` nested in `Optional`'\n    code = 702\n", "path": "wemake_python_styleguide/violations/annotations.py"}, {"content": "# -*- coding: utf-8 -*-\n\nimport ast\nimport re\nfrom typing import ClassVar, FrozenSet, Union\nfrom typing.re import Pattern\n\nfrom typing_extensions import final\n\nfrom wemake_python_styleguide.logic import source\nfrom wemake_python_styleguide.types import AnyFunctionDef\nfrom wemake_python_styleguide.violations.annotations import (\n    LiteralNoneViolation,\n    NestedAnnotationsViolation,\n    UnionNestedInOptionalViolation,\n)\nfrom wemake_python_styleguide.violations.consistency import (\n    MultilineFunctionAnnotationViolation,\n)\nfrom wemake_python_styleguide.visitors.base import BaseNodeVisitor\nfrom wemake_python_styleguide.visitors.decorators import alias\n\n\n@alias('visit_any_function', (\n    'visit_FunctionDef',\n    'visit_AsyncFunctionDef',\n))\nclass _GenericAnnotationVisitor(BaseNodeVisitor):\n    \"\"\"Base class for all annotations visitors.\"\"\"\n\n    _possible_prefixes: ClassVar[FrozenSet[str]] = frozenset((\n        'typing.',\n        'typing_extensions.',\n    ))\n\n    def visit_Assign(self, node: ast.Assign) -> None:\n        \"\"\"Checks assignment patterns.\"\"\"\n        self._check_annotation(node)\n        self.generic_visit(node)\n\n    @final\n    def visit_AnnAssign(self, node: ast.AnnAssign) -> None:\n        \"\"\"\n        Checks for assigned value annotation.\n\n        Raises:\n            LiteralNoneAnnotation\n\n        \"\"\"\n        self._check_annotation(node.annotation)\n        self.generic_visit(node)\n\n    @final\n    def visit_any_function(self, node: AnyFunctionDef) -> None:\n        \"\"\"\n        Checks return type annotations.\n\n        Raises:\n            LiteralNoneAnnotation\n\n        \"\"\"\n        self._check_annotation(node.returns)\n        self.generic_visit(node)\n\n    @final\n    def visit_arg(self, node: ast.arg) -> None:\n        \"\"\"\n        Checks arguments annotations.\n\n        Raises:\n            LiteralNoneAnnotation\n\n        \"\"\"\n        self._check_annotation(node.annotation)\n        self.generic_visit(node)\n\n    @final\n    def _get_annotation(self, node: ast.AST) -> str:\n        \"\"\"Smartly turns annotation node to string.\"\"\"\n        full_annotation = source.node_to_string(node)\n        for prefix in self._possible_prefixes:\n            full_annotation = full_annotation.replace(prefix, '')\n        return full_annotation\n\n    def _check_annotation(\n        self, annotation: Union[ast.expr, ast.Assign, None],\n    ) -> None:\n        \"\"\"The only method that need to me implemented in child visitors.\"\"\"\n\n\n@final\nclass SemanticAnnotationVisitor(_GenericAnnotationVisitor):\n    \"\"\"Ensures that nested annotations are used correctly.\"\"\"\n\n    # matches nested annotation like Literal[Literal[]],\n    # but not neighbors like Literal[], Literal[]\n    _flat_types: ClassVar[FrozenSet[Pattern]] = frozenset((\n        re.compile(r'^.*Literal\\[[^\\]]*Literal'),\n        re.compile(r'^.*Union\\[[^\\]]*Union'),\n        re.compile(r'^.*Annotated\\[[^\\]]*Annotated'),\n    ))\n\n    def _check_annotation(\n        self, annotation: Union[ast.expr, ast.Assign, None],\n    ) -> None:\n        if not annotation:\n            return\n\n        self._check_nested_annotations(annotation)\n        self._check_literal_none(annotation)\n        self._check_union_nested_in_optional(annotation)\n\n    def _check_nested_annotations(\n        self, annotation: Union[ast.expr, ast.Assign],\n    ) -> None:\n        annotation_string = self._get_annotation(annotation)\n        for flat_type in self._flat_types:\n            if flat_type.search(annotation_string):\n                self.add_violation(NestedAnnotationsViolation(annotation))\n\n    def _check_literal_none(\n        self, annotation: Union[ast.expr, ast.Assign],\n    ) -> None:\n        annotation_string = self._get_annotation(annotation)\n        assign_string = (\n            isinstance(annotation, ast.Assign) and\n            isinstance(annotation.value, ast.Str)\n        )\n        if not assign_string and 'Literal[None]' in annotation_string:\n            self.add_violation(LiteralNoneViolation(annotation))\n\n    def _check_union_nested_in_optional(\n        self, annotation: Union[ast.expr, ast.Assign],\n    ) -> None:\n        annotation_string = self._get_annotation(annotation)\n        if 'Optional[Union[' in annotation_string:\n            self.add_violation(UnionNestedInOptionalViolation(annotation))\n\n\n@final\n@alias('visit_any_function', (\n    'visit_FunctionDef',\n    'visit_AsyncFunctionDef',\n))\nclass WrongAnnotationVisitor(BaseNodeVisitor):\n    \"\"\"Ensures that annotations are used correctly.\"\"\"\n\n    def visit_any_function(self, node: AnyFunctionDef) -> None:\n        \"\"\"\n        Checks return type annotations.\n\n        Raises:\n            MultilineFunctionAnnotationViolation\n            LiteralNoneAnnotation\n\n        \"\"\"\n        self._check_return_annotation(node)\n        self.generic_visit(node)\n\n    def visit_arg(self, node: ast.arg) -> None:\n        \"\"\"\n        Checks arguments annotations.\n\n        Raises:\n            MultilineFunctionAnnotationViolation\n            LiteralNoneAnnotation\n\n        \"\"\"\n        self._check_arg_annotation(node)\n        self.generic_visit(node)\n\n    def _check_arg_annotation(self, node: ast.arg) -> None:\n        for sub_node in ast.walk(node):\n            lineno = getattr(sub_node, 'lineno', None)\n            if lineno and lineno != node.lineno:\n                self.add_violation(MultilineFunctionAnnotationViolation(node))\n                return\n\n    def _check_return_annotation(self, node: AnyFunctionDef) -> None:\n        if not node.returns:\n            return\n\n        for sub_node in ast.walk(node.returns):\n            lineno = getattr(sub_node, 'lineno', None)\n            if lineno and lineno != node.returns.lineno:\n                self.add_violation(MultilineFunctionAnnotationViolation(node))\n                return\n", "path": "wemake_python_styleguide/visitors/ast/annotations.py"}]}