python-constricter 0.4.4__py3-none-any.whl → 0.4.6__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. constricter/_version.py +1 -1
  2. constricter/cli/lsp/hints.py +8 -6
  3. constricter/cli/lsp/stored.py +5 -1
  4. constricter/cli/paths.py +3 -3
  5. constricter/cli/rounds.py +43 -5
  6. constricter/cli/workers.py +4 -4
  7. constricter/fix/core/imports.py +32 -4
  8. constricter/fix/core/known.py +89 -11
  9. constricter/fix/index/across.py +33 -5
  10. constricter/fix/index/crossed.py +120 -14
  11. constricter/fix/index/linked.py +10 -5
  12. constricter/fix/index/modules.py +319 -126
  13. constricter/fix/index/offers.py +223 -10
  14. constricter/fix/index/origins.py +28 -0
  15. constricter/fix/index/own_methods.py +56 -8
  16. constricter/fix/index/own_overloads.py +25 -6
  17. constricter/fix/index/own_stubs.py +95 -0
  18. constricter/fix/index/own_types.py +21 -0
  19. constricter/fix/index/plain.py +136 -24
  20. constricter/fix/index/project.py +85 -2
  21. constricter/fix/index/spelling.py +21 -24
  22. constricter/fix/index/stubs/atoms.py +6 -2
  23. constricter/fix/index/stubs/classnames.py +6 -2
  24. constricter/fix/index/stubs/declared.py +55 -4
  25. constricter/fix/index/stubs/installed.py +177 -9
  26. constricter/fix/index/stubs/lone.py +100 -0
  27. constricter/fix/index/stubs/signatures.py +52 -8
  28. constricter/fix/index/used.py +130 -0
  29. constricter/fix/libraries/stdlib.py +28 -0
  30. constricter/fix/tables/attributes.json +151 -56
  31. constricter/fix/tables/awaited.json +1 -0
  32. constricter/fix/tables/classes.json +4 -0
  33. constricter/fix/tables/method_overloads.json +7 -6
  34. constricter/fix/tables/method_signatures.json +14 -0
  35. constricter/fix/tables/methods.json +68 -58
  36. constricter/fix/tables/returns.json +3 -0
  37. constricter/fix/tables/source.json +1 -1
  38. constricter/fix/values/classvars.py +333 -15
  39. constricter/fix/values/documented.py +440 -0
  40. constricter/fix/values/doubts.py +63 -7
  41. constricter/fix/values/echoed.py +67 -0
  42. constricter/fix/values/guesses.py +88 -6
  43. constricter/fix/values/inference.py +70 -7
  44. constricter/fix/values/members.py +96 -8
  45. constricter/fix/values/reads.py +15 -0
  46. constricter/fix/values/refused.py +2 -1
  47. constricter/fix/values/returned.py +182 -16
  48. constricter/fix/values/returns.py +133 -4
  49. constricter/fix/values/tables.py +64 -17
  50. constricter/offences.py +5 -0
  51. constricter/recording.py +14 -10
  52. constricter/rules/attributes.py +17 -1
  53. constricter/rules/checker.py +41 -5
  54. constricter/rules/scope.py +49 -14
  55. constricter/rules/scoping.py +6 -3
  56. constricter/rules/settings.py +6 -4
  57. constricter/source/annotations.py +32 -8
  58. constricter/source/concrete.py +247 -0
  59. constricter/source/declarations.py +199 -86
  60. constricter/source/inert.py +194 -0
  61. constricter/source/syntax.py +84 -0
  62. constricter/source/usable.py +63 -0
  63. constricter/source/walked.py +4 -2
  64. constricter/trace.py +92 -23
  65. constricter/traced.py +33 -7
  66. constricter/witness.py +636 -0
  67. {python_constricter-0.4.4.dist-info → python_constricter-0.4.6.dist-info}/METADATA +4 -2
  68. {python_constricter-0.4.4.dist-info → python_constricter-0.4.6.dist-info}/RECORD +71 -62
  69. {python_constricter-0.4.4.dist-info → python_constricter-0.4.6.dist-info}/WHEEL +0 -0
  70. {python_constricter-0.4.4.dist-info → python_constricter-0.4.6.dist-info}/entry_points.txt +0 -0
  71. {python_constricter-0.4.4.dist-info → python_constricter-0.4.6.dist-info}/licenses/LICENSE.md +0 -0
constricter/_version.py CHANGED
@@ -1,3 +1,3 @@
1
1
  """The version this was built as, from its git tag (written by the build, not tracked)."""
2
2
 
3
- __version__ = "0.4.4"
3
+ __version__ = "0.4.6"
@@ -190,7 +190,7 @@ def _start(files: Mapping[Path, str], checkers: Sequence["Checker"]) -> None:
190
190
  for checker in checkers:
191
191
  # None for no files: its heap is set as its first server starts.
192
192
  if wanted := checker.wanted(files):
193
- checker.share(wanted)
193
+ checker.share(wanted, sum(len(text) for text in files.values()))
194
194
  starting += [checker] * (wanted - len(checker.servers))
195
195
  if not starting:
196
196
  return
@@ -252,15 +252,17 @@ class Checker: # pylint: disable=too-many-instance-attributes
252
252
  self.abandoned: set[Path] = set() # the files a server hung on twice: never asked about again
253
253
  self.environment: dict[str, str] | None = None # its servers', where their heap is capped (`share`)
254
254
 
255
- def share(self, servers: int) -> None:
255
+ def share(self, servers: int, size: int) -> None:
256
256
  """Cap each server's heap at its share of the memory, as the first starts, where they run on Node.
257
257
 
258
- Of `servers`' share, a tenth is left for what isn't the heap; never under a server's own
259
- (`Server.memory`). Past the cap, basedpyright empties its caches, and else exits: restarted
260
- then, its files asked about alone (`_alone`).
258
+ Of `servers`' share, a tenth is left for what isn't the heap; never under what one server
259
+ takes for files of `size` bytes together (`Server.memory`, and `per_byte` for each). Past
260
+ the cap, basedpyright empties its caches, and else exits: restarted then, its files asked
261
+ about alone (`_alone`).
261
262
  """
262
263
  if self.server.node and self.environment is None:
263
- heap: int = max(self.server.memory, self.memory // servers * _HEAP // _WHOLE) >> 20
264
+ one: int = self.server.memory + self.server.per_byte * size
265
+ heap: int = max(one, self.memory // servers * _HEAP // _WHOLE) >> 20
264
266
  given: str = os.environ.get(_NODE_OPTIONS, "")
265
267
  self.environment = {**os.environ, _NODE_OPTIONS: f"{given} --max-old-space-size={heap}".strip()}
266
268
 
@@ -4,7 +4,8 @@ A file's hints rest on the whole program the checker reads, so a round's are kep
4
4
  they rest on (`key`): the checker and its build (see `remembered.build`), the text of every file
5
5
  asked about, the workspace's settings files (`pyproject.toml`, `pyrightconfig.json`, ...), the
6
6
  installed distributions of the environments a checker may read (the interpreter's, `VIRTUAL_ENV`'s
7
- and the workspace's own `.venv`), and the code here that asks and reads. Not a file of the
7
+ and the workspace's own `.venv`), the interpreters first on `PATH` (the one basedpyright asks for
8
+ its packages), and the code here that asks and reads. Not a file of the
8
9
  workspace's that isn't asked about: walking a tree costs as much as a round can save, and a
9
10
  project's files are asked about together. The first round of a project at the
10
11
  same commit asks again only when one of those changed; a later round's texts are `--fix`'s, so it's
@@ -19,6 +20,7 @@ import contextlib
19
20
  import hashlib
20
21
  import json
21
22
  import os
23
+ import shutil
22
24
  import time
23
25
  from collections.abc import Iterable, Mapping, Sequence
24
26
  from pathlib import Path
@@ -36,6 +38,7 @@ _SETTINGS: Final = frozenset(
36
38
  )
37
39
  _LOCAL_ENVIRONMENT: Final = ".venv"
38
40
  _VARIABLES: Final = ("VIRTUAL_ENV", "CONDA_PREFIX", "PYTHONPATH")
41
+ _INTERPRETERS: Final = ("python3", "python") # what a checker with none named starts, to ask for its packages
39
42
  _SUFFIX: Final = ".json"
40
43
  _WHERE: Final = ":" # between a hint's line and column, in an entry
41
44
  # One file's hints as an entry holds them: by `line:column`, the text and the edits' text and imports.
@@ -58,6 +61,7 @@ def key(checker: str, command: Sequence[str], root: Path, files: Mapping[Path, s
58
61
  """
59
62
  build: str = remembered.build(checker, Path(command[0]))
60
63
  texts: list[str] = [checker, *command, build, *(os.environ.get(name, "") for name in _VARIABLES)]
64
+ texts += [shutil.which(name) or "" for name in _INTERPRETERS]
61
65
  # The code that asks and reads them, `edits` the one that writes what the store keeps.
62
66
  parts: list[bytes] = [
63
67
  Path(cast("str", code.__file__)).read_bytes() for code in (connection, protocol, edits)
constricter/cli/paths.py CHANGED
@@ -12,7 +12,7 @@ from constricter import notebook
12
12
 
13
13
  # Skipped in a directory walk unless `--exclude` says otherwise: hidden directories, and common
14
14
  # tool/vendor ones. Merged with `exclude`'s globs (matched per directory name), not replaced by them.
15
- _DEFAULT_EXCLUDES: Final = (".*", "__pycache__", "node_modules", "venv", "site-packages", "build", "dist")
15
+ DEFAULT_EXCLUDES: Final = (".*", "__pycache__", "node_modules", "venv", "site-packages", "build", "dist")
16
16
  STDIN: Final = Path("-")
17
17
  _KINDS: Final = ("*.py", f"*{notebook.SUFFIX}") # the files a directory walk finds
18
18
 
@@ -36,7 +36,7 @@ def python_files(
36
36
  ) -> Iterator[Path]:
37
37
  """Find the files to check.
38
38
 
39
- A directory walk skips `_DEFAULT_EXCLUDES` and `exclude`'s globs by directory name, and `exclude`
39
+ A directory walk skips `DEFAULT_EXCLUDES` and `exclude`'s globs by directory name, and `exclude`
40
40
  by whole path or file name; a file named directly is checked regardless. With `tracked`, a
41
41
  directory in a git checkout has only what git tracks there or would (`_listed`), so nothing its
42
42
  `.gitignore` files name.
@@ -45,7 +45,7 @@ def python_files(
45
45
  Each file given, and each `*.py` under each directory given.
46
46
 
47
47
  """
48
- globs: tuple[str, ...] = (*_DEFAULT_EXCLUDES, *exclude)
48
+ globs: tuple[str, ...] = (*DEFAULT_EXCLUDES, *exclude)
49
49
  path: Path
50
50
  found: Path
51
51
  for path in paths:
constricter/cli/rounds.py CHANGED
@@ -18,7 +18,7 @@ from constricter.cli.runs import CheckRun, FileRun, merged
18
18
  from constricter.cli.workers import Workers, running, started
19
19
  from constricter.empty import Empty
20
20
  from constricter.fix.core.known import Callee, Hints, Outside
21
- from constricter.fix.index import callers, decorated, loose, plain, project
21
+ from constricter.fix.index import callers, crossed, decorated, loose, plain, project
22
22
  from constricter.fix.index.stubs import installed
23
23
  from constricter.offences import UNANNOTATED_ATTRIBUTE, UNANNOTATED_PARAMETER, Edit, Fix
24
24
 
@@ -67,10 +67,15 @@ def settled(
67
67
  again: list[int] = [
68
68
  index
69
69
  for index, run in enumerate(runs)
70
- if fixing and paths[index] != STDIN and _unsettled(run, session, options.guesses)
70
+ if fixing
71
+ and paths[index] != STDIN
72
+ and (_unsettled(run, session, options.guesses) or _imports_read(modules, paths[index], run))
71
73
  ]
72
74
  changed: list[int] = [
73
- at for at in range(len(runs)) if _reaching(paths[at], runs[at], onward=onward, signing=signing)
75
+ at
76
+ for at in range(len(runs))
77
+ if _reaching(paths[at], runs[at], onward=onward, signing=signing)
78
+ or (fixing and _imports_read(modules, paths[at], runs[at]))
74
79
  ]
75
80
  for _ in range(HINT_ROUNDS - 1):
76
81
  held: dict[int, FileRun] = {}
@@ -83,13 +88,46 @@ def settled(
83
88
  latest: project.Index
84
89
  fresh, latest = _round(paths, runs, (again, held), _How(check, options, session), modules)
85
90
  modules = latest if onward or signing else modules
86
- again = [index for index, run in fresh if _unsettled(run, session, options.guesses)]
91
+ again = [
92
+ index
93
+ for index, run in fresh
94
+ if _unsettled(run, session, options.guesses) or _imports_read(modules, paths[index], run)
95
+ ]
87
96
  changed = [
88
- index for index, run in fresh if _reaching(paths[index], run, onward=onward, signing=signing)
97
+ index
98
+ for index, run in fresh
99
+ if _reaching(paths[index], run, onward=onward, signing=signing)
100
+ or _imports_read(modules, paths[index], run)
89
101
  ]
90
102
  return runs
91
103
 
92
104
 
105
+ def _imports_read(modules: project.Index, path: Path, run: FileRun) -> bool:
106
+ """Check whether a round of `--fix` imported a checked file's class whose members the file reads.
107
+
108
+ What's read of them had no type while the file didn't spell the class (`f: TextIO`, from the
109
+ standard-library tables, then `f.encoding`, on a corpus that checks `typing.py`). Or a name only
110
+ the file's own stub imported, for type checking too: the stub's types naming it had none in the
111
+ file's own check till then (`crossed.binds_stubbed`).
112
+
113
+ Returns:
114
+ Whether it did.
115
+
116
+ """
117
+ return _changed(path, run) and any(
118
+ isinstance(made.offence.edit, Fix)
119
+ and (
120
+ crossed.reads_imported(modules, path, made.offence.edit.imports)
121
+ or crossed.binds_stubbed(
122
+ modules,
123
+ path,
124
+ (*made.offence.edit.imports, *made.offence.edit.guarded),
125
+ )
126
+ )
127
+ for made in cast("CheckRun", run).made
128
+ )
129
+
130
+
93
131
  def _reaching(path: Path, run: FileRun, *, onward: bool, signing: bool) -> bool:
94
132
  """Check whether a round of `--fix` changed a file in a way the other files may see.
95
133
 
@@ -21,7 +21,7 @@ from constricter.source import parsed
21
21
 
22
22
  if TYPE_CHECKING: # slow to import, and only needed for many files
23
23
  from concurrent.futures import Future, ProcessPoolExecutor
24
- from multiprocessing.context import DefaultContext
24
+ from multiprocessing.context import BaseContext
25
25
 
26
26
  # A worker's answers, one per file of its share: what it read (to index), and what it found.
27
27
  _Reading: TypeAlias = "Future[list[project.Module | None]]"
@@ -237,11 +237,11 @@ def _preload() -> None:
237
237
  would import constricter itself as it starts. Once the server runs, this changes nothing; a
238
238
  forked worker has the parent's imports, and a spawned one imports its own whatever this says.
239
239
  """
240
- get_context: Callable[[], DefaultContext] = cast(
241
- "Callable[[], DefaultContext]",
240
+ get_context: Callable[[], BaseContext] = cast(
241
+ "Callable[[], BaseContext]",
242
242
  importlib.import_module("multiprocessing").get_context,
243
243
  )
244
- context: DefaultContext = get_context()
244
+ context: BaseContext = get_context()
245
245
  if context.get_start_method() == _FORKSERVER:
246
246
  context.set_forkserver_preload(_PRELOADED)
247
247
 
@@ -2,6 +2,7 @@
2
2
 
3
3
  import ast
4
4
  import bisect
5
+ import builtins
5
6
  import re
6
7
  import sys
7
8
  from collections.abc import Callable, Iterator, Mapping, Sequence
@@ -11,7 +12,7 @@ from weakref import WeakKeyDictionary
11
12
 
12
13
  from constricter.fix.core.known import Checking, Guarded, ImportPlan, Origin, Returns
13
14
  from constricter.source.annotations import dotted, roots
14
- from constricter.source.syntax import FunctionDef, Start, import_bindings
15
+ from constricter.source.syntax import FunctionDef, Start, generic_named, import_bindings
15
16
  from constricter.source.walked import classes, of_type
16
17
 
17
18
  _TYPE_CHECKING: Final = "TYPE_CHECKING"
@@ -22,6 +23,8 @@ _FUTURE: Final = "__future__"
22
23
  _IMPORTORSKIP: Final = "pytest.importorskip" # a module it names may be missing
23
24
  _MODNAME: Final = "modname" # its parameter
24
25
  _DOT: Final = "."
26
+ BUILTINS: Final = frozenset(dir(builtins))
27
+ _NONE: Final[frozenset[str]] = frozenset()
25
28
  _ANNOTATIONS: Final = "annotations" # `from __future__ import annotations` postpones them all
26
29
  # Each module's names, for as long as its tree lives: the index reads them, then the check.
27
30
  _Taken: TypeAlias = tuple[frozenset[str], frozenset[str]]
@@ -43,12 +46,14 @@ _BINDERS: Final = (
43
46
  )
44
47
 
45
48
 
46
- def plan(tree: ast.Module) -> ImportPlan:
49
+ def plan(tree: ast.Module, imported_values: frozenset[str] = _NONE) -> ImportPlan:
47
50
  """Read what `tree` already imports, every name it binds, and where its imports end.
48
51
 
49
52
  Only imports that run count as binding a name to use (not those under `if TYPE_CHECKING:`: a
50
53
  module's own annotations are evaluated when it's imported); every name bound anywhere in the
51
- file is taken, so an added import never shadows one (nor a builtin).
54
+ file is taken, so an added import never shadows one (nor a builtin). `imported_values`: the
55
+ names it imports that another module binds as a value (`linked.values`), which with its own
56
+ functions and assignments say which builtins it shadows.
52
57
 
53
58
  Returns:
54
59
  A fresh plan for the module's fixes.
@@ -64,6 +69,7 @@ def plan(tree: ast.Module) -> ImportPlan:
64
69
  taken,
65
70
  _after(tree),
66
71
  defined,
72
+ shadowed=_shadowed(tree) | (imported_values & BUILTINS),
67
73
  checking=Checking(
68
74
  _block(tree),
69
75
  _lazy(tree, bound),
@@ -76,6 +82,7 @@ def plan(tree: ast.Module) -> ImportPlan:
76
82
  ),
77
83
  postponed=_postponed(tree),
78
84
  values=values,
85
+ generic=generic_named(tree),
79
86
  )
80
87
 
81
88
 
@@ -149,6 +156,8 @@ def unwritable(annotation: str, planned: ImportPlan, nested: Mapping[str, str])
149
156
  def added_origin(statement: str) -> Origin:
150
157
  """Read what an import `ImportPlan.spell` added binds: `from m import T`, or `import m`.
151
158
 
159
+ `import m.sub` binds `m`, as one in the source does (`syntax.import_bindings`).
160
+
152
161
  Returns:
153
162
  Its origin: `("m", "T")`, or `("m", None)`.
154
163
 
@@ -156,7 +165,7 @@ def added_origin(statement: str) -> Origin:
156
165
  module: str
157
166
  name: str
158
167
  module, _, name = statement.removeprefix("from ").removeprefix("import ").partition(" import ")
159
- return module, name or None
168
+ return (module, name) if name else (module.partition(_DOT)[0], None)
160
169
 
161
170
 
162
171
  def added_dotted(statement: str) -> str:
@@ -264,6 +273,25 @@ def _bound(tree: ast.Module) -> dict[str, str]:
264
273
  return {name: origin for name, origin, _ in import_bindings(_running(tree.body))}
265
274
 
266
275
 
276
+ def _shadowed(tree: ast.Module) -> frozenset[str]:
277
+ """Name the builtins the module binds at its top level to a function or a value of its own.
278
+
279
+ `def str(val)` (`locale`'s), `str = str` (a Python 2 shim): a type written with the name would
280
+ name those, which a type checker refuses ("Variable not allowed in type expression"). A class
281
+ of the name (`enum`'s `property`) is a class, named as any is.
282
+
283
+ Returns:
284
+ Them.
285
+
286
+ """
287
+ found: set[str] = set()
288
+ stmt: ast.stmt
289
+ for stmt in _running(tree.body):
290
+ if isinstance(stmt, ast.FunctionDef | ast.AsyncFunctionDef | ast.Assign | ast.AnnAssign):
291
+ found.update(name for name in _names(stmt) if name in BUILTINS)
292
+ return frozenset(found)
293
+
294
+
267
295
  def _defined(tree: ast.Module) -> dict[str, int]:
268
296
  """Map each name the module binds at its top level (or under a top-level `if`/`try`) to its line.
269
297
 
@@ -16,7 +16,7 @@ from constricter.fix.core.inherited import Beyond, Lineage
16
16
  from constricter.fix.core.signatures import Expansion, ReadSignature
17
17
  from constricter.offences import MAX_LENGTH, VAGUE
18
18
  from constricter.overrides import override
19
- from constricter.source.annotations import free_of, free_of_all, roots
19
+ from constricter.source.annotations import GENERIC_HOMES, free_of, free_of_all, roots
20
20
  from constricter.source.declarations import GenericClass
21
21
 
22
22
  if TYPE_CHECKING:
@@ -40,6 +40,7 @@ Origin: TypeAlias = tuple[str, str | None]
40
40
  SPELLED: Final = "="
41
41
  # After a fixture's `request` parameter's name: the key its `request.param` is typed under (see `Typed`).
42
42
  PARAM: Final = ".param"
43
+ OWN_SELF: Final = "self.own" # in a scope's types: the class whose method reads `self`, unannotated or not
43
44
 
44
45
 
45
46
  # A `dict` itself, not a `UserDict`: every inference reads it, as fast as a `dict` is read.
@@ -164,7 +165,9 @@ class ImportPlan: # pylint: disable=too-many-instance-attributes
164
165
  `bound`: each name its imports bind, and what that is (`io`, `io.BytesIO`); `taken`: every name
165
166
  bound anywhere in it; `after`: the line added imports go after; `defined`: each name it binds
166
167
  at its top level (an import, a class, a function, an assignment), and the line it's first bound
167
- on; `added`: each name an added import binds, and that import's statement, as `spell` chose them.
168
+ on; `shadowed`: the builtins it binds at its top level to what a checker reads as no class (a
169
+ function, an assignment, an import of a value), so no type is written with them; `added`: each
170
+ name an added import binds, and that import's statement, as `spell` chose them.
168
171
  `guarded`: the names other checked files' types and a type checker's hints are written with
169
172
  that the module imports (or is to import) under `if TYPE_CHECKING:` alone; `checking`: its own
170
173
  such imports, where one goes, and whose types need one (see `Checking`); `postponed`: whether
@@ -175,30 +178,72 @@ class ImportPlan: # pylint: disable=too-many-instance-attributes
175
178
  taken: frozenset[str]
176
179
  after: int
177
180
  defined: Mapping[str, int] = field(default_factory=dict[str, int])
181
+ shadowed: frozenset[str] = frozenset()
178
182
  added: dict[str, str] = field(default_factory=dict[str, str])
179
183
  guarded: Mapping[str, Guarded] = field(default_factory=dict[str, Guarded])
180
184
  checking: Checking = field(default_factory=Checking)
181
185
  postponed: bool = False
182
186
  values: frozenset[str] = frozenset() # names it binds as values somewhere (see `imports.taken_names`)
187
+ generic: frozenset[str] = (
188
+ frozenset()
189
+ ) # its classes of a generic's name, generic too (`syntax.generic_named`)
183
190
  # Names it imports from another checked file that re-exports a type's factory there (`Outside`).
184
191
  factories: frozenset[str] = frozenset()
185
192
 
193
+ def own_names(self) -> frozenset[str]:
194
+ """Name what the module binds, or is to import, other than from where typing's generics come.
195
+
196
+ Its own `class Generator`, `from numpy.random import Generator`, `import numpy as np`: a
197
+ generic's name written bare (`Generator`) or through one (`np.random.Generator`) is then
198
+ that, not the generic missing its arguments (see `annotations.is_vague`).
199
+
200
+ Returns:
201
+ Them.
202
+
203
+ """
204
+ found: set[str] = {
205
+ name
206
+ for name in self.defined.keys() - self.generic
207
+ if name not in self.bound
208
+ or not {self.bound[name], self.bound[name].rpartition(_DOT)[0]} & GENERIC_HOMES
209
+ }
210
+ name: str
211
+ statement: str
212
+ for name, statement in self.added.items():
213
+ if statement.split()[1] not in GENERIC_HOMES:
214
+ found.add(name)
215
+ each: Guarded
216
+ for name, each in self.guarded.items():
217
+ if each.origin[0] not in GENERIC_HOMES:
218
+ found.add(name)
219
+ return frozenset(found)
220
+
186
221
  def type_checking(self) -> str | None:
187
222
  """Name `typing.TYPE_CHECKING` for a new block, by an import that runs: the module reads it.
188
223
 
224
+ The block goes after `after`, so through an import the module has only where it binds the
225
+ name by then: an `import typing` below a `try:` of other imports isn't, and a new import
226
+ goes with the block.
227
+
189
228
  Returns:
190
229
  The name, or `None` if every way to write it is taken.
191
230
 
192
231
  """
193
- return self.spell("typing.TYPE_CHECKING", runs=True)
232
+ qualified: str = "typing.TYPE_CHECKING"
233
+ found: str | None = self.named(qualified)
234
+ if found is not None and self.defined.get(found.partition(_DOT)[0], self.after + 1) <= self.after:
235
+ return found
236
+ return self._added(qualified, runs=True)
194
237
 
195
238
  def spell(self, qualified: str, *, runs: bool = False) -> str | None:
196
239
  """Name `qualified` (`io.BufferedReader`) in this module, adding an import if it has to.
197
240
 
198
241
  Through an import it has (see `named`), for type checking alone too (`checking`, or one
199
- `guarded` already), else a new `from io import BufferedReader`, else a new `import io`, but
200
- only binding a name nothing in the module binds. Under `if TYPE_CHECKING:` for a module in
201
- `checking.lazy`, and not at all for one only some platforms have. With `runs`, only through
242
+ `guarded` already), else a new `from io import BufferedReader`, else a new `import io`
243
+ (`import collections.abc`, binding `collections`, unless the module imports the name or
244
+ defines a class of it), but only binding a name nothing in the module binds. Under
245
+ `if TYPE_CHECKING:` for a module in `checking.lazy`, and not at all for one only some
246
+ platforms have. With `runs`, only through
202
247
  an import that runs: the name is read as the module is imported (`TYPE_CHECKING` itself).
203
248
 
204
249
  Returns:
@@ -208,6 +253,15 @@ class ImportPlan: # pylint: disable=too-many-instance-attributes
208
253
  found: str | None
209
254
  if (found := self.named(qualified) or (None if runs else self._checked(qualified))) is not None:
210
255
  return found
256
+ return self._added(qualified, runs=runs)
257
+
258
+ def _added(self, qualified: str, *, runs: bool) -> str | None:
259
+ """Name `qualified` by an import to add, as `spell` does past the module's own.
260
+
261
+ Returns:
262
+ The name, or `None` if every way to write it is taken.
263
+
264
+ """
211
265
  module: str
212
266
  name: str
213
267
  module, _, name = qualified.rpartition(".")
@@ -220,9 +274,14 @@ class ImportPlan: # pylint: disable=too-many-instance-attributes
220
274
  if self._free(name, statement):
221
275
  self.added[name] = statement
222
276
  return name
223
- statement = f"import {module}"
224
- if _DOT not in module and self._free(module, statement):
225
- self.added[module] = statement
277
+ statement = f"import {module}" # `import collections.abc` binds `collections`
278
+ # What the module imports or defines a class of the name as, anywhere (`from distutils.core
279
+ # import Distribution`, `_collections_abc`'s own `Iterator`), is the one meant, or the same:
280
+ # no new import beside it, past a module of one name.
281
+ if _DOT in module and name in self.taken and name not in self.values:
282
+ return None
283
+ if self._free(top, statement):
284
+ self.added[top] = statement
226
285
  return qualified
227
286
  return None
228
287
 
@@ -310,7 +369,8 @@ class LibraryNames(NamedTuple):
310
369
  every Python the module runs on parses an unpacked tuple in a subscript (`tuple[int, *Ts]`,
311
370
  3.11's syntax), so an annotation may be written with one. `aliased`: whether `typing` has
312
371
  `TypeAlias` on every Python the module runs on (3.10's; yes where that isn't known), so a new
313
- import may name it.
372
+ import may name it. `written`: the installed and checked files' classes it names, none generic,
373
+ which a docstring's return may name (see `Lineages.written`).
314
374
  """
315
375
 
316
376
  casts: frozenset[str] = frozenset()
@@ -323,6 +383,17 @@ class LibraryNames(NamedTuple):
323
383
  aliases: Mapping[str, Expansion] = MappingProxyType({})
324
384
  starred: bool = False
325
385
  aliased: bool = True
386
+ written: frozenset[str] = frozenset()
387
+
388
+
389
+ class Echo(NamedTuple):
390
+ """The parameter a method returns as it's given: its call is what's passed for it (see `echoed`).
391
+
392
+ `position`: its place among a call's positional arguments, `None` for a keyword-only one.
393
+ """
394
+
395
+ position: int | None
396
+ name: str
326
397
 
327
398
 
328
399
  class Returned(NamedTuple):
@@ -333,13 +404,15 @@ class Returned(NamedTuple):
333
404
  whose `return`s are themselves guesses, what they rest on (`FIX_KINDS`), which its calls do too.
334
405
  `attributes`: its classes' unannotated instance attributes typed by their every `self.x = value`,
335
406
  by class (guesses: a subclass or outside code may assign one too); a guessed value's origins are
336
- in `guesses` as `C.x`.
407
+ in `guesses` as `C.x`. `echoes`: its classes' methods whose every `return` gives one parameter
408
+ as it's given, by class (see `Echo`).
337
409
  """
338
410
 
339
411
  calls: Mapping[str, str] = MappingProxyType({})
340
412
  methods: Mapping[str, Mapping[str, str]] = MappingProxyType({})
341
413
  guesses: Mapping[str, frozenset[str]] = MappingProxyType({})
342
414
  attributes: Mapping[str, Mapping[str, str]] = MappingProxyType({})
415
+ echoes: Mapping[str, Mapping[str, Echo]] = MappingProxyType({})
343
416
 
344
417
 
345
418
  class Partial(NamedTuple):
@@ -579,9 +652,12 @@ class Outside: # pylint: disable=too-many-instance-attributes
579
652
  classes: Classes | None = None
580
653
  hints: tuple[Hints, ...] = () # each checker's, in the order they were named
581
654
  type_vars: frozenset[str] = frozenset()
655
+ defaulted: frozenset[str] = frozenset() # those of them with a default (see `project.defaulted`)
582
656
  returned: Returns = field(default_factory=Returns)
583
657
  guarded: Mapping[str, Guarded] = field(default_factory=dict[str, Guarded])
584
658
  generics: frozenset[str] = frozenset() # other checked files' generic classes, as it spells them
659
+ # Those of theirs a type checker reads bare with their defaults (see `Module.defaulted_generics`).
660
+ defaulted_generics: frozenset[str] = frozenset()
585
661
  # Those classes' type parameters and the members it takes of them (see `GenericClass`).
586
662
  generic: Mapping[str, GenericClass] = field(default_factory=dict[str, GenericClass])
587
663
  # Their descriptors, as it spells them, each with what an instance's attribute of it gives.
@@ -610,6 +686,8 @@ class Outside: # pylint: disable=too-many-instance-attributes
610
686
  installed_aliases: Mapping[str, Expansion] = field(
611
687
  default_factory=dict[str, Expansion],
612
688
  )
689
+ # See `LibraryNames.written`
690
+ written: frozenset[str] = frozenset()
613
691
  # The classes it imports under `if TYPE_CHECKING:` alone, which an annotation can name (see `offers.own`).
614
692
  checking: Mapping[str, Guarded] = field(default_factory=dict[str, Guarded])
615
693
  plain: frozenset[str] | None = None
@@ -4,9 +4,11 @@ Each file is checked knowing what the files it imports declare and return, the h
4
4
  checker gave it, and what the index's other readers say of the names it imports (see `Outside`).
5
5
  """
6
6
 
7
+ import re
7
8
  from collections.abc import Mapping
9
+ from dataclasses import replace
8
10
  from pathlib import Path
9
- from typing import TYPE_CHECKING
11
+ from typing import TYPE_CHECKING, Final
10
12
 
11
13
  from constricter.fix.core.known import Guarded, Hints, Origin, Outside, Passed
12
14
  from constricter.fix.index import (
@@ -38,6 +40,10 @@ if TYPE_CHECKING:
38
40
  from constricter.fix.core.signatures import ReadSignature
39
41
 
40
42
 
43
+ # A dotted name in a type (`trio.SocketListener`): a class spelled through a module.
44
+ _DOTTED: Final = re.compile(r"\b[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)+")
45
+
46
+
41
47
  def outside(modules: project.Index, path: Path, hinted: Mapping[Path, tuple[Hints, ...]]) -> Outside:
42
48
  """Find what's known of a file from outside it: what it imports from the others, and its hints.
43
49
 
@@ -60,17 +66,17 @@ def outside(modules: project.Index, path: Path, hinted: Mapping[Path, tuple[Hint
60
66
  hints: tuple[Hints, ...] = offers.vetted(modules, path, hinted.get(path, ()))
61
67
  # What only a hint can name: the classes the file imports for type checking alone.
62
68
  own: offers.Own = offers.own(modules, path) if hints else offers.Own()
69
+ lineage: own_types.Lineages = own_types.lineages(modules, path, guarded, methods.lineage)
63
70
  overloaded: dict[str, tuple[ReadSignature, ...]] = {
64
71
  **stubbed.overloaded(modules, path, guarded),
65
72
  **methods.signatures,
66
73
  **own_methods.overloaded(modules, path, guarded),
67
74
  }
68
- return Outside(
75
+ found: Outside = Outside(
69
76
  calls={**imported.calls, **side_calls, **decorated.own(modules, path)},
70
- # With those of the classes the overloaded methods' returns import.
71
- classes=crossed.guarded_classes(modules, path, imported, guarded),
72
77
  hints=hints,
73
78
  type_vars=project.type_vars(modules, path),
79
+ defaulted=project.defaulted(modules, path),
74
80
  returned=awaits.returned(
75
81
  modules,
76
82
  path,
@@ -79,6 +85,7 @@ def outside(modules: project.Index, path: Path, hinted: Mapping[Path, tuple[Hint
79
85
  ),
80
86
  guarded=guarded,
81
87
  generics=imported.generics | own.generics,
88
+ defaulted_generics=imported.defaulted_generics,
82
89
  generic=dict(imported.generic),
83
90
  descriptors=dict(imported.descriptors),
84
91
  callees=callers.callees(modules, path),
@@ -88,7 +95,8 @@ def outside(modules: project.Index, path: Path, hinted: Mapping[Path, tuple[Hint
88
95
  installed_classes=stubbed.classes(modules, path),
89
96
  read_members=crossed.member_names(modules, path),
90
97
  installed_parameters=methods.parameters,
91
- installed_lineage=own_types.lineages(modules, path, guarded, methods.lineage),
98
+ installed_lineage=lineage,
99
+ written=lineage.written(),
92
100
  installed_aliases=methods.aliases,
93
101
  checking=own.guarded,
94
102
  plain=plain.classes(modules, path),
@@ -109,6 +117,26 @@ def outside(modules: project.Index, path: Path, hinted: Mapping[Path, tuple[Hint
109
117
  emptied=beyond.emptied(modules, path),
110
118
  factories=factories(modules, path),
111
119
  )
120
+ # With those of the classes the types above import for type checking (an overloaded method's
121
+ # return, an awaited call's, an item's): read last, as each of them adds to `guarded`.
122
+ return replace(found, classes=crossed.guarded_classes(modules, path, imported, guarded, _spelled(found)))
123
+
124
+
125
+ def _spelled(found: Outside) -> frozenset[str]:
126
+ """Find the dotted names in the types found of a file from outside it: `trio.SocketListener`.
127
+
128
+ Returns:
129
+ Them.
130
+
131
+ """
132
+ types: list[str] = [
133
+ *found.calls.values(),
134
+ *found.awaits.values(),
135
+ *found.tuples.values(),
136
+ *found.unions.values(),
137
+ *found.returned.calls.values(),
138
+ ]
139
+ return frozenset(match.group() for each in types for match in _DOTTED.finditer(each))
112
140
 
113
141
 
114
142
  def factories(modules: project.Index, path: Path) -> frozenset[str]: