Repository: python/mypy

Issue:
Crash when `(Mutable)Sequence` is imported from `collections.abc` in `typeshed/stdlib/builtins.pyi`
**Crash Report**

Mypy crashes if one or both of `Sequence` and `MutableSequence` is imported from `collections.abc` instead of `typing` in the typeshed stub for `builtins`.

**Traceback**

```
stdlib\builtins.pyi:1506: error: Unexpected "..."
C:\Users\Alex\Desktop\Code dump\typeshed\stdlib\collections\__init__.pyi: error: INTERNAL ERROR -- Please try using mypy master on Github:
https://mypy.readthedocs.io/en/stable/common_issues.html#using-a-development-mypy-build
Please report a bug at https://github.com/python/mypy/issues
version: 0.930
Traceback (most recent call last):
  File "C:\Program Files\Python310\lib\runpy.py", line 196, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "C:\Program Files\Python310\lib\runpy.py", line 86, in _run_code
    exec(code, run_globals)
  File "C:\Users\Alex\Desktop\Code dump\typeshed\.venv3\Scripts\mypy.exe\__main__.py", line 7, in <module>
    sys.exit(console_entry())
  File "mypy\build.py", line 1972, in wrap_context
  File "mypy\semanal_main.py", line 326, in semantic_analyze_target
  File "mypy\semanal.py", line 405, in refresh_partial
  File "mypy\semanal.py", line 414, in refresh_top_level
  File "mypy\semanal.py", line 444, in add_implicit_module_attrs
AssertionError:
C:\Users\Alex\Desktop\Code dump\typeshed\stdlib\collections\__init__.pyi: : note: use --pdb to drop into pdb
```

**To Reproduce**

1. Clone typeshed
2. Change one or both of `Sequence` and `MutableSequence` in `typeshed/stdlib/builtins.pyi` so that they are imported from `collections.abc` rather than `typing`.
3. cd into the typeshed repo.
4. Run `mypy stdlib/functools.py --show-traceback` (the file you run mypy on is irrelevant).

[Using the typeshed CI, I have reproduced this issue](https://github.com/python/typeshed/pull/6724):

- On MacOS, Windows and Ubuntu
- On Python versions 3.6-3.10 inclusive.
- Importing just `Sequence` from `collections.abc`; importing just `MutableSequence` from `collections.abc`; and importing both `Sequence` and `MutableSequence` from `collections.abc`.

**Mypy version used**
0.930



Discussion:
Cc. @JukkaL, @sobolevn, as requested in https://github.com/python/typeshed/issues/4820 🙂
@JelleZijlstra, could you add the "topic-pep-585" label to this? :)

Resolving patch:
diff --git a/mypy/semanal.py b/mypy/semanal.py
--- a/mypy/semanal.py
+++ b/mypy/semanal.py
@@ -597,9 +597,12 @@ def refresh_top_level(self, file_node: MypyFile) -> None:
 
     def add_implicit_module_attrs(self, file_node: MypyFile) -> None:
         """Manually add implicit definitions of module '__name__' etc."""
+        str_type: Type | None = self.named_type_or_none("builtins.str")
+        if str_type is None:
+            str_type = UnboundType("builtins.str")
         for name, t in implicit_module_attrs.items():
             if name == "__doc__":
-                typ: Type = UnboundType("__builtins__.str")
+                typ: Type = str_type
             elif name == "__path__":
                 if not file_node.is_package_init_file():
                     continue
@@ -612,7 +615,7 @@ def add_implicit_module_attrs(self, file_node: MypyFile) -> None:
                 if not isinstance(node, TypeInfo):
                     self.defer(node)
                     return
-                typ = Instance(node, [self.str_type()])
+                typ = Instance(node, [str_type])
             elif name == "__annotations__":
                 sym = self.lookup_qualified("__builtins__.dict", Context(), suppress_errors=True)
                 if not sym:
@@ -621,7 +624,7 @@ def add_implicit_module_attrs(self, file_node: MypyFile) -> None:
                 if not isinstance(node, TypeInfo):
                     self.defer(node)
                     return
-                typ = Instance(node, [self.str_type(), AnyType(TypeOfAny.special_form)])
+                typ = Instance(node, [str_type, AnyType(TypeOfAny.special_form)])
             else:
                 assert t is not None, f"type should be specified for {name}"
                 typ = UnboundType(t)
diff --git a/mypy/semanal_main.py b/mypy/semanal_main.py
--- a/mypy/semanal_main.py
+++ b/mypy/semanal_main.py
@@ -66,7 +66,14 @@
 
 # Number of passes over core modules before going on to the rest of the builtin SCC.
 CORE_WARMUP: Final = 2
-core_modules: Final = ["typing", "builtins", "abc", "collections"]
+core_modules: Final = [
+    "typing",
+    "_collections_abc",
+    "builtins",
+    "abc",
+    "collections",
+    "collections.abc",
+]
 
 
 def semantic_analysis_for_scc(graph: Graph, scc: list[str], errors: Errors) -> None:


Test patch: