File size: 10,744 Bytes
1600cd6
 
 
 
 
 
 
 
 
2a9dc4c
1600cd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a9dc4c
1600cd6
 
 
2a9dc4c
1600cd6
2a9dc4c
 
1600cd6
 
 
 
 
 
 
 
 
 
 
f4952b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1600cd6
 
 
f4952b6
 
 
 
 
 
1600cd6
 
 
 
 
f4952b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1600cd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
"""Generate the pattern corpus and its coverage table for this bundle.

Run from inside the folder:

    python tools/build_patterns.py            # write the two generated files
    python tools/build_patterns.py --check    # rebuild and compare bytes, change nothing

Both files under `patterns/` are generated here and nowhere else. A row is not written by hand and
then checked against the rules; it is the plan a rule produced for one named function of
`fixtures/pattern_lab`, handed to `lingologos_codex.casecorpus` for validation before it reaches the file.
That is what makes the corpus more than a description of the code beside it: if a rule changes and
the plan it produces changes with it, the file changes because the plan changed, and if the corpus
is edited by hand the `--check` mode stops, because rebuilding no longer reproduces the bytes.

A positive row is a plan that applied. A negative row is a refusal the rule itself named, with the
reason code the rule gave, and an empty `edits`. The pairs are declared below: each pattern has one
function of the fixture written in the shape it claims and one function beside it written so that
the claim does not hold. The gate runner re-derives both halves from the fixture on every run, so
the pairs below are checked, not trusted.
"""

from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path
from typing import Dict, List, Sequence, Tuple

ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
    sys.path.insert(0, str(ROOT))
sys.dont_write_bytecode = True

from lingologos_python._codex_bridge import ensure_codex_on_path  # noqa: E402

ensure_codex_on_path(ROOT)

from lingologos_codex.casecorpus import read_rows, validate_case_rows, write_rows  # noqa: E402

from lingologos_python.ast_graph import discover_python_files  # noqa: E402
from lingologos_python.patterns import (  # noqa: E402
    PATTERNS,
    module_level_functions,
    plan_pattern,
    scan_pattern,
)

LAB = ROOT / "fixtures" / "pattern_lab"
CASES_PATH = ROOT / "patterns" / "pattern_cases.jsonl"
COVERAGE_PATH = ROOT / "patterns" / "coverage.json"
COVERAGE_SCHEMA = "lingologos-python-pattern-coverage-1"

# One or more pairs per card: a function of the fixture in the shape, and a function beside it that
# is not. The right column states the reason code the rule is expected to give, so a rule that stops
# refusing for the reason the card claims is caught here rather than in a reader's session. A pair
# with the tag "coroutine" states the same claim again over an async def: the card that vouches for
# coroutines carries its own pair, and the card that does not is recorded refusing one.
Pair = Tuple[str, str, str, str]

PAIRS: Dict[str, List[Pair]] = {
    "annotate-literal-defaults": [
        ("src/tokens.py::count_words", "src/tokens.py::count_lines", "ALREADY_ANNOTATED", ""),
        ("src/asyncops.py::render_page", "src/asyncops.py::sized", "ALREADY_ANNOTATED", "coroutine"),
    ],
    "bare-assert-to-explicit-raise": [
        ("src/guards.py::open_ticket", "src/guards.py::close_ticket", "NOT_THE_FIRST_STATEMENT", ""),
        ("src/asyncops.py::check_name", "src/asyncops.py::check_after", "NOT_THE_FIRST_STATEMENT", "coroutine"),
    ],
    "bare-except-to-narrow-exception": [
        ("src/retries.py::call_or_none", "src/retries.py::call_or_note", "NO_BARE_EXCEPT", ""),
    ],
    "chain-to-registry": [
        ("src/registry.py::render", "src/registry.py::render_pair", "BRANCH_SHAPE_MISMATCH", ""),
    ],
    "drop-unused-imports": [
        ("src/legacy.py::read_size", "src/tokens.py::count_words", "NO_UNUSED_IMPORT", ""),
    ],
    "empty-len-to-truthiness": [
        ("src/baskets.py::describe", "src/baskets.py::first_or_none", "NO_EMPTY_LEN_CHECK", ""),
        ("src/asyncops.py::word_total", "src/asyncops.py::item_count", "NO_EMPTY_LEN_CHECK", "coroutine"),
    ],
    "init-missing-super": [
        ("src/widgets.py::Box.__init__", "src/widgets.py::Shutter.__init__", "SUPER_CALL_ALREADY_FIRST", ""),
    ],
    "mutable-default-to-none": [
        ("src/slugify.py::add_tag", "src/slugify.py::join_parts", "NOT_A_MUTABLE_DEFAULT", ""),
        ("src/asyncops.py::gather", "src/asyncops.py::plain", "NOT_A_MUTABLE_DEFAULT", "coroutine"),
    ],
    "none-comparison-to-identity": [
        ("src/labels.py::label_for", "src/labels.py::is_missing", "NO_NONE_COMPARISON", ""),
        ("src/asyncops.py::describe", "src/asyncops.py::present", "NO_NONE_COMPARISON", "coroutine"),
    ],
    "open-to-context-manager": [
        ("src/notes.py::read_note", "src/notes.py::write_note", "ALREADY_SCOPED", ""),
    ],
}


def _case_id(pattern_id: str, tag: str, half: str) -> str:
    if tag:
        return "pat-%s-%s-%s" % (pattern_id, tag, half)
    return "pat-%s-%s" % (pattern_id, half)


def build_rows() -> List[Dict[str, object]]:
    """Every row of the corpus, in the order it belongs in the file."""

    rows: List[Dict[str, object]] = []
    for pattern_id in sorted(PATTERNS):
        for positive_target, negative_target, expected_code, tag in PAIRS[pattern_id]:
            applied = plan_pattern(LAB, pattern_id, positive_target)
            if applied.refused:
                raise SystemExit(
                    "the card '%s' refuses the target built for it: %s (%s)"
                    % (pattern_id, applied.detail, applied.reason_code)
                )
            if len(applied.edits) < 2:
                raise SystemExit(
                    "the card '%s' planned %d edits, and a card without its lock test does not belong "
                    "in this corpus" % (pattern_id, len(applied.edits))
                )
            rows.append(applied.to_row(_case_id(pattern_id, tag, "positive")))

            refusal = plan_pattern(LAB, pattern_id, negative_target)
            if not refusal.refused:
                raise SystemExit(
                    "the card '%s' applied to the target built to be refused: %s"
                    % (pattern_id, negative_target)
                )
            if refusal.reason_code != expected_code:
                raise SystemExit(
                    "the card '%s' refused '%s' with '%s', this tool expects '%s'"
                    % (pattern_id, negative_target, refusal.reason_code, expected_code)
                )
            rows.append(refusal.to_row(_case_id(pattern_id, tag, "negative")))

    problems = validate_case_rows(rows)
    if problems:
        raise SystemExit("casecorpus rejected the generated corpus: " + "; ".join(problems))
    return rows


def build_coverage(rows: Sequence[Dict[str, object]]) -> Dict[str, object]:
    """The table that states what the corpus covers, and over what."""

    source_files = [name for name in discover_python_files(LAB) if not name.startswith("tests/")]
    functions: Dict[str, int] = {}
    for rel in source_files:
        text = (LAB / Path(*rel.split("/"))).read_text(encoding="utf-8", newline="")
        functions[rel] = len(module_level_functions(text))
    per_pattern: List[Dict[str, object]] = []
    for pattern_id in sorted(PATTERNS):
        spec = PATTERNS[pattern_id]
        shapes = [label for label, _hit in scan_pattern(LAB, pattern_id)]
        positive = [row for row in rows if row["pattern_id"] == pattern_id and row["expect"] == "VERIFIED"]
        negative = [row for row in rows if row["pattern_id"] == pattern_id and row["expect"] == "REFUSED"]
        per_pattern.append(
            {
                "pattern_id": pattern_id,
                "family": spec.family,
                "min_assurance": spec.min_assurance,
                "positive_rows": len(positive),
                "negative_rows": len(negative),
                "targets_planted_in_shape": len(shapes),
                "targets_in_shape": shapes,
                "refusals_recorded": sorted(str(row.get("reason_code", "")) for row in negative),
            }
        )
    return {
        "schema": COVERAGE_SCHEMA,
        "fixture": "fixtures/pattern_lab",
        "denominator": (
            "the counts below are over one fixture of this bundle, not over Python. They say how many "
            "of the functions this bundle planted are in a shape the catalog claims, so a reader can "
            "see that the catalog is a set of verified cards and not a claim about arbitrary code."
        ),
        "source_files": source_files,
        "module_level_functions_by_file": functions,
        "module_level_functions": sum(functions.values()),
        "patterns": per_pattern,
        "rows": len(rows),
    }


def _render_coverage(payload: Dict[str, object]) -> str:
    return json.dumps(payload, indent=2, sort_keys=True, ensure_ascii=True) + "\n"


def main(argv: Sequence[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument(
        "--check",
        action="store_true",
        help="rebuild both files, compare them with what is on disk, and write nothing",
    )
    args = parser.parse_args(argv)

    rows = build_rows()
    coverage = build_coverage(rows)
    cases_text = "".join(
        json.dumps(row, sort_keys=True, ensure_ascii=True) + "\n" for row in rows
    )
    coverage_text = _render_coverage(coverage)

    if args.check:
        drift: List[str] = []
        for path, text in ((CASES_PATH, cases_text), (COVERAGE_PATH, coverage_text)):
            if not path.is_file():
                drift.append("%s is missing" % path.relative_to(ROOT))
            elif path.read_text(encoding="utf-8", newline="") != text:
                drift.append("%s is not what the rules produce" % path.relative_to(ROOT))
        on_disk = read_rows(CASES_PATH) if CASES_PATH.is_file() else []
        if on_disk:
            bad = validate_case_rows(on_disk)
            if bad:
                drift.append("patterns/pattern_cases.jsonl is not a valid case-1 corpus: " + "; ".join(bad))
        if drift:
            print("PATTERNS: REJECTED (%s)" % "; ".join(drift))
            return 1
        print(
            "PATTERNS: CONFIRMED (%d rows over %d cards, %d module level functions in the fixture)"
            % (len(rows), len(PATTERNS), coverage["module_level_functions"])
        )
        return 0

    CASES_PATH.parent.mkdir(parents=True, exist_ok=True)
    write_rows(CASES_PATH, rows)
    COVERAGE_PATH.write_text(coverage_text, encoding="utf-8", newline="\n")
    print(
        "wrote %s (%d rows) and %s (%d cards)"
        % (
            CASES_PATH.relative_to(ROOT),
            len(rows),
            COVERAGE_PATH.relative_to(ROOT),
            len(PATTERNS),
        )
    )
    return 0


if __name__ == "__main__":
    raise SystemExit(main())