Repository: psf/black

Issue:
Internal error on type hinted comment with trailing space
**Describe the bug**

Black is encountering an `INTERNAL ERROR` when a type hinted comment has a trailing space.

**To Reproduce**


For example, take this code:
With the trailing space after `# type: dict[str, str]  ` black encounters an internal error
```python
d = {}  # type: dict[str, str] 
```
remove the white space character like `# type: dict[str, str]` and the file is formatted.

And run it with these arguments:

```sh
$ black t.py 

```

The resulting error is:

> error: cannot format t.py: INTERNAL ERROR: Black produced code that is not equivalent to the source.  Please report a bug on https://github.com/psf/black/issues.  This diff might be helpful: /tmp/blk_66snb7vb.log

**Expected behavior**

<!-- A clear and concise description of what you expected to happen. -->

**Environment**

- Black's version: black==22.12.0
- OS and Python version: WSL Ubuntu 22.04 Python 3.10.6

**Additional context**
here's the log
```
--- src
+++ dst
@@ -8,11 +8,11 @@
             )  # /Store
           id=
             'd',  # str
         )  # /Name
       type_comment=
-        'dict[str, str] ',  # str
+        'dict[str, str]',  # str
       value=
         Dict(
           keys=
           values=
         )  # /Dict

```



Discussion:
Thank you for submitting this! Here's a [playground link](https://black.vercel.app/?version=main&state=_Td6WFoAAATm1rRGAgAhARYAAAB0L-Wj4AB2AE1dAD2IimZxl1N_Wh88hfShWGZNuaJB6TNIg7Q8-VGqOX07--io0XTzpI6Zaq1VG-jCDvzLVQzjOmeqYMXcMNdm3Jp3nVxt6WWyAW6sQqkAAAAAAImowJ09G07kAAFpd1qB2FoftvN9AQAAAAAEWVo=) for convenience
In case additional datapoints are useful:
I ran into this same issue with the trailing space here:
https://github.com/ietf-tools/datatracker/blob/ce374acc78d9ad8bd5b120b3992a44c432150029/ietf/utils/fields.py#L203

with
```
$ black --version
black, 23.1.0 (compiled: no)
Python (CPython) 3.9.16
```


Resolving patch:
diff --git a/src/black/parsing.py b/src/black/parsing.py
--- a/src/black/parsing.py
+++ b/src/black/parsing.py
@@ -208,15 +208,18 @@ def stringify_ast(node: ast.AST, depth: int = 0) -> Iterator[str]:
 
         else:
             normalized: object
-            # Constant strings may be indented across newlines, if they are
-            # docstrings; fold spaces after newlines when comparing. Similarly,
-            # trailing and leading space may be removed.
             if (
                 isinstance(node, ast.Constant)
                 and field == "value"
                 and isinstance(value, str)
             ):
+                # Constant strings may be indented across newlines, if they are
+                # docstrings; fold spaces after newlines when comparing. Similarly,
+                # trailing and leading space may be removed.
                 normalized = _normalize("\n", value)
+            elif field == "type_comment" and isinstance(value, str):
+                # Trailing whitespace in type comments is removed.
+                normalized = value.rstrip()
             else:
                 normalized = value
             yield f"{'  ' * (depth+2)}{normalized!r},  # {value.__class__.__name__}"


Test patch:
diff --git a/tests/data/simple_cases/comments2.py b/tests/data/simple_cases/comments2.py
--- a/tests/data/simple_cases/comments2.py
+++ b/tests/data/simple_cases/comments2.py
@@ -154,6 +154,9 @@ def _init_host(self, parsed) -> None:
                 not parsed.hostname.strip()):
             pass
 
+
+a = "type comment with trailing space"  # type: str   
+
 #######################
 ### SECTION COMMENT ###
 #######################
@@ -332,6 +335,8 @@ def _init_host(self, parsed) -> None:
             pass
 
 
+a = "type comment with trailing space"  # type: str
+
 #######################
 ### SECTION COMMENT ###
 #######################