python-constricter 0.4.5__py3-none-any.whl → 0.4.7__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 (38) hide show
  1. constricter/_version.py +1 -1
  2. constricter/cli/explain.py +15 -1
  3. constricter/cli/lsp/hints.py +14 -8
  4. constricter/cli/lsp/protocol.py +7 -3
  5. constricter/cli/lsp/stored.py +5 -1
  6. constricter/cli/options.py +2 -1
  7. constricter/cli/paths.py +3 -3
  8. constricter/cli/rounds.py +17 -6
  9. constricter/cli/workers.py +4 -4
  10. constricter/fix/core/known.py +13 -1
  11. constricter/fix/index/crossed.py +33 -10
  12. constricter/fix/index/modules.py +55 -13
  13. constricter/fix/index/offers.py +154 -15
  14. constricter/fix/index/spelling.py +4 -3
  15. constricter/fix/index/stubs/installed.py +10 -4
  16. constricter/fix/index/stubs/lone.py +100 -0
  17. constricter/fix/tables/source.json +1 -1
  18. constricter/fix/values/doubts.py +94 -2
  19. constricter/fix/values/echoed.py +67 -0
  20. constricter/fix/values/guesses.py +7 -2
  21. constricter/fix/values/hinted.py +18 -2
  22. constricter/fix/values/inference.py +3 -1
  23. constricter/fix/values/returned.py +72 -3
  24. constricter/offences.py +3 -1
  25. constricter/recording.py +43 -20
  26. constricter/rules/checker.py +5 -1
  27. constricter/rules/late.py +2 -2
  28. constricter/rules/scope.py +12 -4
  29. constricter/source/declarations.py +27 -15
  30. constricter/source/syntax.py +21 -0
  31. constricter/source/walked.py +4 -2
  32. constricter/trace.py +92 -23
  33. constricter/witness.py +795 -0
  34. {python_constricter-0.4.5.dist-info → python_constricter-0.4.7.dist-info}/METADATA +5 -2
  35. {python_constricter-0.4.5.dist-info → python_constricter-0.4.7.dist-info}/RECORD +38 -35
  36. {python_constricter-0.4.5.dist-info → python_constricter-0.4.7.dist-info}/WHEEL +0 -0
  37. {python_constricter-0.4.5.dist-info → python_constricter-0.4.7.dist-info}/entry_points.txt +0 -0
  38. {python_constricter-0.4.5.dist-info → python_constricter-0.4.7.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.5"
3
+ __version__ = "0.4.7"
@@ -12,6 +12,7 @@ from constricter.offences import (
12
12
  NESTED_TYPE,
13
13
  OPT_IN,
14
14
  REDUNDANT_TYPE,
15
+ TRACED,
15
16
  UNANNOTATED,
16
17
  UNANNOTATED_ATTRIBUTE,
17
18
  UNANNOTATED_MEMBER,
@@ -106,13 +107,26 @@ _WHY: Final = {
106
107
  }
107
108
 
108
109
 
110
+ # What a traced run reports (`python -m constricter.trace --check`), which no check does.
111
+ _TRACED_MESSAGE: Final = "an annotation a traced run's value differed from"
112
+ _TRACED_WHY: Final = (
113
+ "A run of the code (its tests, say) held each annotated parameter, local and return to what\n"
114
+ "it was bound to, and one value wasn't what the annotation says: `count: int` given a `str`.\n"
115
+ "Fix the annotation or the value. A cast narrowing a value on purpose to the part the code uses\n"
116
+ "(a JSON document read as a `TypedDict`) can say so: `# noqa: LVA016` on its line."
117
+ )
118
+ _TRACED_BY: Final = "reported by `python -m constricter.trace --check` alone"
119
+
120
+
109
121
  def explain(code: str) -> str:
110
122
  """Explain `code`.
111
123
 
112
124
  Returns:
113
- Its message, rationale and the levels that report it.
125
+ Its message, rationale and the levels that report it; for `TRACED`, what reports it.
114
126
 
115
127
  """
128
+ if code == TRACED:
129
+ return f"{code}: {_TRACED_MESSAGE}\n\n{_TRACED_WHY}\n\n{_TRACED_BY}\n"
116
130
  offence: Offence = Offence(1, 0, "name", code)
117
131
  levels: list[str] = [
118
132
  f"{level.name.lower()}: {'error' if offence.is_error(level) else 'warning'}"
@@ -1,7 +1,8 @@
1
1
  """`--infer-with`: ask a type checker's language server what type each untyped name has.
2
2
 
3
- Each checker's servers are started once (each round, asked in turn: see `Asking`), over standard
4
- input and output, with the project root as their workspace, and work at once (see `Session`); each
3
+ Each checker's servers are started once (each round, asked in turn, see `Asking`, or a stale
4
+ checker's, see `Server.stale`), over standard input and output, with the project root as their
5
+ workspace, and work at once (see `Session`); each
5
6
  file is opened with the text constricter read, and its inlay hints asked for over the whole file. A
6
7
  variable-type hint (`: int`) sits just after the name it types: that end is its key, as the line
7
8
  (from 1) and the UTF-8 byte column `ast` gives the name's end. What the hint says is
@@ -121,6 +122,9 @@ class Session:
121
122
  turns: list[list[Checker]] = [[checker] for checker in asking] if self.how.in_turn else [asking]
122
123
  turn: list[Checker]
123
124
  for turn in turns:
125
+ for checker in turn:
126
+ if checker.server.stale:
127
+ checker.stop()
124
128
  _asked(files, turn, found)
125
129
  for checker in turn if self.how.in_turn else ():
126
130
  checker.stop()
@@ -190,7 +194,7 @@ def _start(files: Mapping[Path, str], checkers: Sequence["Checker"]) -> None:
190
194
  for checker in checkers:
191
195
  # None for no files: its heap is set as its first server starts.
192
196
  if wanted := checker.wanted(files):
193
- checker.share(wanted)
197
+ checker.share(wanted, sum(len(text) for text in files.values()))
194
198
  starting += [checker] * (wanted - len(checker.servers))
195
199
  if not starting:
196
200
  return
@@ -252,15 +256,17 @@ class Checker: # pylint: disable=too-many-instance-attributes
252
256
  self.abandoned: set[Path] = set() # the files a server hung on twice: never asked about again
253
257
  self.environment: dict[str, str] | None = None # its servers', where their heap is capped (`share`)
254
258
 
255
- def share(self, servers: int) -> None:
259
+ def share(self, servers: int, size: int) -> None:
256
260
  """Cap each server's heap at its share of the memory, as the first starts, where they run on Node.
257
261
 
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`).
262
+ Of `servers`' share, a tenth is left for what isn't the heap; never under what one server
263
+ takes for files of `size` bytes together (`Server.memory`, and `per_byte` for each). Past
264
+ the cap, basedpyright empties its caches, and else exits: restarted then, its files asked
265
+ about alone (`_alone`).
261
266
  """
262
267
  if self.server.node and self.environment is None:
263
- heap: int = max(self.server.memory, self.memory // servers * _HEAP // _WHOLE) >> 20
268
+ one: int = self.server.memory + self.server.per_byte * size
269
+ heap: int = max(one, self.memory // servers * _HEAP // _WHOLE) >> 20
264
270
  given: str = os.environ.get(_NODE_OPTIONS, "")
265
271
  self.environment = {**os.environ, _NODE_OPTIONS: f"{given} --max-old-space-size={heap}".strip()}
266
272
 
@@ -35,7 +35,9 @@ class Server(NamedTuple):
35
35
  Its executable, the arguments that start it over stdio, and the most of it to run (up to
36
36
  `MAX_SERVERS`). And the memory its servers take, as measured: `memory` bytes each before the
37
37
  files, and `per_byte` more for each byte of them: each server's again where each holds the
38
- `whole` program, once among them all where each holds what it's asked about.
38
+ `whole` program, once among them all where each holds what it's asked about. A `stale` one goes
39
+ on answering from what it read of a file before its new text was sent: its servers are started
40
+ anew for each round of files after their first.
39
41
  """
40
42
 
41
43
  executable: str
@@ -45,6 +47,7 @@ class Server(NamedTuple):
45
47
  per_byte: int
46
48
  whole: bool = False
47
49
  node: bool = False # it runs on Node, whose heap its share of the memory caps (`--max-old-space-size`)
50
+ stale: bool = False
48
51
 
49
52
  def fitting(self, budget: int, size: int) -> int:
50
53
  """Count the servers that fit in `budget` bytes, for files of `size` bytes together.
@@ -75,8 +78,9 @@ SERVERS: Final = {
75
78
  # with two, 22s with three and 21s with four (1.2 GB with one, 1.7 with two, 2.5 with four).
76
79
  "ty": Server("ty", ("server",), MAX_SERVERS, 420 << 20, 38),
77
80
  # Parallel too: pandas's takes 132s with one, 58s with two and 32s with four (2.8 GB, 3.2, 4.2);
78
- # the standard library's 39 MB, 4.3 GB with one and 5.6 with four.
79
- "pyrefly": Server("pyrefly", ("lsp",), MAX_SERVERS, 480 << 20, 120),
81
+ # the standard library's 39 MB, 4.3 GB with one and 5.6 with four. Stale (1.3.2): a server kept
82
+ # from the round before gave pip 32 fewer fixes, which a second pass then made.
83
+ "pyrefly": Server("pyrefly", ("lsp",), MAX_SERVERS, 480 << 20, 120, stale=True),
80
84
  }
81
85
  _PROBE: Final = "--version" # quick for each; basedpyright-langserver's exits 1 all the same
82
86
  _PROBE_TIMEOUT: Final = 10.0 # seconds it may take
@@ -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)
@@ -32,6 +32,7 @@ from constricter.offences import (
32
32
  NESTING,
33
33
  OPT_IN,
34
34
  PLAIN_BASES,
35
+ TRACED,
35
36
  UNANNOTATED_ATTRIBUTE,
36
37
  UNANNOTATED_PARAMETER,
37
38
  UNANNOTATED_RETURN,
@@ -450,7 +451,7 @@ def _parser() -> argparse.ArgumentParser:
450
451
  )
451
452
  _ = parser.add_argument(
452
453
  "--explain",
453
- choices=list(MESSAGES),
454
+ choices=[*MESSAGES, TRACED],
454
455
  metavar="CODE",
455
456
  help="explain a code and exit",
456
457
  )
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
@@ -42,9 +42,11 @@ def settled(
42
42
  """Check every file, then again each one `--fix` changed in a way a second check would see.
43
43
 
44
44
  Until a round changes nothing, `HINT_ROUNDS` at most: a second pass is then left nothing. With
45
- `--likely` or `--unsafe-fixes` and no type checker's hints, the files a round changed are indexed
46
- again, and the others checked again too where that changes what they know from outside: what
47
- reads a guess another file declares (an attribute LVA013's declares) now knows its type.
45
+ `--likely` or `--unsafe-fixes`, the files a round changed are indexed again, and the others
46
+ checked again too where that changes what they know from outside: what reads a guess another
47
+ file declares (an attribute LVA013's declares) now knows its type. With a type checker's hints,
48
+ every file is asked about again then, and checked again where its hints changed: a checker can
49
+ type a name once another file's fix is written.
48
50
 
49
51
  Returns:
50
52
  What each file found, a file's rounds joined.
@@ -60,7 +62,7 @@ def settled(
60
62
  session,
61
63
  )
62
64
  fixing: bool = options.mode is Mode.FIX
63
- onward: bool = fixing and session is None and options.guesses is not Guesses.NONE
65
+ onward: bool = fixing and options.guesses is not Guesses.NONE
64
66
  # A signature written (LVA014, LVA015) changes what the other files know of the file whatever
65
67
  # the guesses: it's indexed again, and they're checked again where that reaches them.
66
68
  signing: bool = fixing and session is None and (options.checks.returns or options.checks.parameters)
@@ -106,7 +108,9 @@ def _imports_read(modules: project.Index, path: Path, run: FileRun) -> bool:
106
108
  """Check whether a round of `--fix` imported a checked file's class whose members the file reads.
107
109
 
108
110
  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`).
111
+ standard-library tables, then `f.encoding`, on a corpus that checks `typing.py`). Or a name only
112
+ the file's own stub imported, for type checking too: the stub's types naming it had none in the
113
+ file's own check till then (`crossed.binds_stubbed`).
110
114
 
111
115
  Returns:
112
116
  Whether it did.
@@ -114,7 +118,14 @@ def _imports_read(modules: project.Index, path: Path, run: FileRun) -> bool:
114
118
  """
115
119
  return _changed(path, run) and any(
116
120
  isinstance(made.offence.edit, Fix)
117
- and crossed.reads_imported(modules, path, made.offence.edit.imports)
121
+ and (
122
+ crossed.reads_imported(modules, path, made.offence.edit.imports)
123
+ or crossed.binds_stubbed(
124
+ modules,
125
+ path,
126
+ (*made.offence.edit.imports, *made.offence.edit.guarded),
127
+ )
128
+ )
118
129
  for made in cast("CheckRun", run).made
119
130
  )
120
131
 
@@ -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
 
@@ -386,6 +386,16 @@ class LibraryNames(NamedTuple):
386
386
  written: frozenset[str] = frozenset()
387
387
 
388
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
397
+
398
+
389
399
  class Returned(NamedTuple):
390
400
  """Return types read from unannotated functions' own `return` statements (see `returned`).
391
401
 
@@ -394,13 +404,15 @@ class Returned(NamedTuple):
394
404
  whose `return`s are themselves guesses, what they rest on (`FIX_KINDS`), which its calls do too.
395
405
  `attributes`: its classes' unannotated instance attributes typed by their every `self.x = value`,
396
406
  by class (guesses: a subclass or outside code may assign one too); a guessed value's origins are
397
- 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`).
398
409
  """
399
410
 
400
411
  calls: Mapping[str, str] = MappingProxyType({})
401
412
  methods: Mapping[str, Mapping[str, str]] = MappingProxyType({})
402
413
  guesses: Mapping[str, frozenset[str]] = MappingProxyType({})
403
414
  attributes: Mapping[str, Mapping[str, str]] = MappingProxyType({})
415
+ echoes: Mapping[str, Mapping[str, Echo]] = MappingProxyType({})
404
416
 
405
417
 
406
418
  class Partial(NamedTuple):
@@ -150,7 +150,7 @@ def guarded_classes(
150
150
  catalog: Index,
151
151
  path: Path,
152
152
  found: Imported,
153
- guarded: Mapping[str, Guarded],
153
+ guarded: dict[str, Guarded],
154
154
  spelled: frozenset[str],
155
155
  ) -> Classes:
156
156
  """Add the members of the classes `guarded` names that `found` hasn't taken, as the file names them.
@@ -160,7 +160,9 @@ def guarded_classes(
160
160
  that class's methods in the same pass, not only once the import is written. And those `spelled`
161
161
  names through a module the file imports, as the types those steps give write them
162
162
  (`trio.SocketListener`, which `trio` re-exports): the file reads no such attribute until a fix
163
- writes the type, so `found` took none of them.
163
+ writes the type, so `found` took none of them. What their members' types need imported is added
164
+ to `guarded`, and is a receiver's class in turn: `line, = ax.plot(...)`, `ax` an `Axes` by an
165
+ overload, is a `Line2D` the file imports for it, and `line.get_xdata()` one of its methods.
164
166
 
165
167
  Returns:
166
168
  `found`'s classes, with theirs.
@@ -169,11 +171,8 @@ def guarded_classes(
169
171
  target: Module | None
170
172
  if (target := module_at(catalog, path)) is None:
171
173
  return found.classes
172
- fresh: dict[str, Origin] = {
173
- name: each.origin
174
- for name, each in guarded.items()
175
- if name not in found.guarded and name not in target.names and name not in found.classes.methods
176
- }
174
+ known: set[str] = {*found.guarded, *target.names, *found.classes.methods}
175
+ fresh: dict[str, Origin] = {name: each.origin for name, each in guarded.items() if name not in known}
177
176
  through: dict[str, Origin] = {}
178
177
  attributes: set[str] = set()
179
178
  each: str
@@ -188,10 +187,12 @@ def guarded_classes(
188
187
  {key: dict(each) for key, each in found.classes.attributes.items()},
189
188
  {key: dict(each) for key, each in found.classes.methods.items()},
190
189
  )
191
- if fresh:
192
- _take(catalog, target, (fresh, None), taken, dict(guarded))
193
190
  if through:
194
- _take(catalog, target, (through, frozenset(attributes)), taken, dict(guarded))
191
+ _take(catalog, target, (through, frozenset(attributes)), taken, guarded)
192
+ for _ in range(HOPS): # as `imported` follows them: each hop's classes are receivers' too
193
+ fresh = {name: each.origin for name, each in guarded.items() if name not in known}
194
+ _take(catalog, target, (fresh, None), taken, guarded)
195
+ known.update(fresh)
195
196
  return Classes(taken.attributes, taken.methods)
196
197
 
197
198
 
@@ -281,6 +282,28 @@ def reads_imported(catalog: Index, path: Path, statements: Iterable[str]) -> boo
281
282
  return False
282
283
 
283
284
 
285
+ def binds_stubbed(catalog: Index, path: Path, statements: Iterable[str]) -> bool:
286
+ """Check whether `statements` import into a file a name only its own stub imported (`Module.stub_names`).
287
+
288
+ Its stub's types naming it had none in the file's own check while its source didn't bind it:
289
+ `aspect = self.get_aspect()`, declared `float | Literal["auto"]`, has one once `Literal` is imported.
290
+
291
+ Returns:
292
+ Whether they do; not for a file `catalog` doesn't have.
293
+
294
+ """
295
+ target: Module | None
296
+ if (target := module_at(catalog, path)) is None or not target.stub_names:
297
+ return False
298
+ statement: str
299
+ for statement in statements:
300
+ node: ast.stmt = ast.parse(statement).body[0]
301
+ names: list[ast.alias] = node.names if isinstance(node, ast.Import | ast.ImportFrom) else []
302
+ if any((alias.asname or alias.name).partition(".")[0] in target.stub_names for alias in names):
303
+ return True
304
+ return False
305
+
306
+
284
307
  def _written(spelled: str, attributes: frozenset[str]) -> bool:
285
308
  """Check whether a file can write a class as `spelled`: each part after its first an attribute it takes.
286
309
 
@@ -38,6 +38,7 @@ from constricter.source.declarations import (
38
38
  defaulted_type_vars,
39
39
  defined_type_vars,
40
40
  descriptors,
41
+ generic_alias_types,
41
42
  generic_classes,
42
43
  generic_members,
43
44
  generic_names,
@@ -214,6 +215,9 @@ class Module: # pylint: disable=too-many-instance-attributes
214
215
  # Those they leave bare (see `constricter.fix.index.consistent`).
215
216
  annotated: Mapping[str, tuple[str, ...]] = field(default_factory=dict[str, tuple[str, ...]])
216
217
  bare: frozenset[str] = frozenset()
218
+ # Those of `guarded` only its own stub imports (see `_own`): its stub's types are written with
219
+ # them, but its source binds none, so a fix there imports each one it writes.
220
+ stub_names: frozenset[str] = frozenset()
217
221
 
218
222
  @override
219
223
  def __getstate__(self) -> dict[str, object]:
@@ -495,11 +499,11 @@ def read(path: Path, name: str | None = None) -> Module | None:
495
499
  assigned: Counter[str] = _assigned(tree.body)
496
500
  rebound: frozenset[str] = frozenset(bound for bound, count in assigned.items() if count > 1)
497
501
  named: str = name or module_name(path)
498
- is_package: bool = path.stem == PACKAGE
499
502
  own: Tables
500
503
  names: dict[str, Origin]
501
504
  guarded: dict[str, Origin]
502
- own, names, guarded = _own(path, (source, tree), named, installed=installed)
505
+ stub_names: frozenset[str]
506
+ own, names, guarded, stub_names = _own(path, (source, tree), named, installed=installed)
503
507
  aliases: dict[str, bool] = _aliases(tree)
504
508
  defaulted: frozenset[str] = defaulted_type_vars(tree)
505
509
  type_vars: frozenset[str] = defined_type_vars(tree)
@@ -511,7 +515,7 @@ def read(path: Path, name: str | None = None) -> Module | None:
511
515
  methods=own.order.flattened(own.methods),
512
516
  type_vars=type_vars,
513
517
  guarded=guarded,
514
- stars=starred(tree, named, is_package=is_package),
518
+ stars=starred(tree, named, is_package=path.stem == PACKAGE),
515
519
  unannotated=unannotated(tree.body, passing(tree, type_vars)),
516
520
  decorated=held_back(tree.body),
517
521
  called=used.called(tree, names),
@@ -536,7 +540,7 @@ def read(path: Path, name: str | None = None) -> Module | None:
536
540
  passes=own.passes,
537
541
  aliases={alias: generic for alias, generic in aliases.items() if alias not in rebound},
538
542
  rebound=rebound,
539
- inner={} if installed else inner_origins(tree, named, is_package=is_package),
543
+ inner={} if installed else inner_origins(tree, named, is_package=path.stem == PACKAGE),
540
544
  variables=_variables(tree.body).difference(own.classes.keys()), # a frozenset: `- keys()` is a `set`
541
545
  assigned=frozenset(assigned).difference(aliases.keys(), type_vars),
542
546
  shadowed=frozenset() if installed else frozenset(names) & taken_names(tree)[1],
@@ -563,6 +567,7 @@ def read(path: Path, name: str | None = None) -> Module | None:
563
567
  annotated={} if installed else annotated.annotations(tree),
564
568
  bare=frozenset() if installed else annotated.bare(tree),
565
569
  kinds=None if installed else kinds(tree, aliases.keys() - rebound),
570
+ stub_names=stub_names,
566
571
  unawaited=frozenset(
567
572
  stmt.name
568
573
  for stmt in tree.body
@@ -577,15 +582,15 @@ def _own(
577
582
  named: str,
578
583
  *,
579
584
  installed: bool,
580
- ) -> tuple[Tables, dict[str, Origin], dict[str, Origin]]:
585
+ ) -> tuple[Tables, dict[str, Origin], dict[str, Origin], frozenset[str]]:
581
586
  """Read a module's own tables and names, a checked one's kept for its check (see `parsed.keep`).
582
587
 
583
588
  With its own stub's, where it has one (see `own_stubs.beside`): its importers read every type the stub
584
589
  declares, its check only those it can write as they are (its names', and the builtins').
585
590
 
586
591
  Returns:
587
- Its tables; what each name it binds refers to; and each name it imports for type checking
588
- alone, its stub's imports among them.
592
+ Its tables; what each name it binds refers to; each name it imports for type checking alone,
593
+ its stub's imports among them; and those of them only its stub imports.
589
594
 
590
595
  """
591
596
  source: str
@@ -597,16 +602,52 @@ def _own(
597
602
  names.update(skipped(tree, names)) # `pa = pytest.importorskip("pyarrow")`, as `import pyarrow as pa`
598
603
  guarded: dict[str, Origin] = guarded_origins(tree, named, is_package=is_package)
599
604
  if installed:
600
- return own, names, guarded
605
+ return own, names, guarded, frozenset()
601
606
  kept: Tables = own
607
+ only: frozenset[str] = frozenset()
602
608
  beside: tuple[Tables, dict[str, Origin]] | None
603
609
  if (beside := own_stubs.beside(path, named, is_package=is_package)) is not None: # `mod.pyi`, read first
604
- writable: frozenset[str] = frozenset(names).union(guarded, own.classes, BUILTINS)
605
- kept = own_stubs.stubbed(own, beside[0], lambda each: roots(each) <= writable)
610
+ kept = _spelled(own, beside[0], frozenset(names).union(guarded))
606
611
  own = own_stubs.stubbed(own, beside[0])
612
+ only = frozenset(each for each in beside[1] if each not in names and each not in guarded)
607
613
  guarded = {**{each: at for each, at in beside[1].items() if each not in names}, **guarded}
608
614
  parsed.keep(source, (tree, kept)) # for the check to take, rather than parse it and read it again
609
- return own, names, guarded
615
+ return own, names, guarded, only
616
+
617
+
618
+ def _spelled(own: Tables, stub: Tables, names: frozenset[str]) -> Tables:
619
+ """Take a stub's types a module can write as they are: by `names`, its classes and the builtins.
620
+
621
+ Returns:
622
+ The module's tables, with those (see `own_stubs.stubbed`).
623
+
624
+ """
625
+ writable: frozenset[str] = names.union(own.classes, BUILTINS)
626
+ return own_stubs.stubbed(own, stub, lambda each: roots(each) <= writable)
627
+
628
+
629
+ def checkable(path: Path, tree: ast.Module) -> Tables | None:
630
+ """Read what a module with its own stub is checked with, from a tree the index kept no tables for.
631
+
632
+ The index keeps them for the text it read (`_own`): a file checked as any other text, `--fix`'s
633
+ since, or once more as the same, would know none of its stub's types.
634
+
635
+ Returns:
636
+ Its tables with its stub's, as `_own` keeps them; `None` where it has no stub
637
+ (see `own_stubs.beside`).
638
+
639
+ """
640
+ if path.suffix != SUFFIX: # a notebook, standard input, a text with no file
641
+ return None
642
+ is_package: bool = path.stem == PACKAGE
643
+ named: str = module_name(path)
644
+ beside: tuple[Tables, dict[str, Origin]] | None
645
+ if (beside := own_stubs.beside(path, named, is_package=is_package)) is None:
646
+ return None
647
+ names: dict[str, Origin] = origins_of(tree, named, is_package=is_package)
648
+ names.update(skipped(tree, names))
649
+ guarded: dict[str, Origin] = guarded_origins(tree, named, is_package=is_package)
650
+ return _spelled(module_tables(tree), beside[0], frozenset(names).union(guarded))
610
651
 
611
652
 
612
653
  def _loose(body: Sequence[ast.stmt]) -> frozenset[str]:
@@ -770,7 +811,8 @@ def _aliases(tree: ast.Module) -> dict[str, bool]:
770
811
  """Find a module's type aliases, at its top level or under an `if` or `try` there.
771
812
 
772
813
  A name annotated `TypeAlias`, bound to a subscript or a union (`Json = dict[str, "Json"] | str`),
773
- or a `type` statement's.
814
+ a `type` statement's, or one `TypeAliasType` makes with type parameters
815
+ (`Result = TypeAliasType("Result", Accepted[T] | Declined, type_params=(T,))`), which is generic.
774
816
 
775
817
  Returns:
776
818
  Each one's name, and whether it takes type arguments: its value names one of the module's type
@@ -798,7 +840,7 @@ def _aliases(tree: ast.Module) -> dict[str, bool]:
798
840
  found[named.id] = bool(cast("object", getattr(stmt, "type_params", ())))
799
841
  case _:
800
842
  pass
801
- return found
843
+ return found | dict.fromkeys(generic_alias_types(tree), True)
802
844
 
803
845
 
804
846
  def _assigned(body: Sequence[ast.stmt]) -> Counter[str]: