From 032d4a735399eeba68a269c88a49adca979b838d Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 6 Dec 2026 06:05:03 +0000 Subject: [PATCH 01/16] A class-body member line or a prototype is placed on the class and the function it declares A C++ member line of a class body (a member, a static constant, a method prototype) and a Python class attribute are placed on the class that holds them, and a C++ prototype also on the function it declares when the diff's files hold one definition of it. The placed definitions join code.impact's touched symbols and seed the radius, so the review brief claims their coverage instead of answering unsettled on unmapped_changes. Braces, class heads, access specifiers, using, friend, namespace and preprocessor lines, includes, file-scope constants and lines a macro continues stay unmapped. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- docs/features/code-index/history-and-prs.md | 50 +++- docs/features/code-index/operations.md | 4 +- docs/reference/operations/code.md | 2 +- server/code/api/models_symbol.py | 20 +- server/code/app/index/review_brief_build.py | 2 +- server/code/app/symbol/cpp_members.py | 70 ++++++ server/code/app/symbol/diff.py | 232 ++++++++++++++++-- server/code/app/symbol/impact.py | 15 +- server/code/domain/index/epistemic.py | 7 +- tests/unit/test_code_diff_sides.py | 229 +++++++++++++++-- tests/unit/test_code_epistemic_envelope.py | 10 +- tests/unit/test_code_review_brief_sections.py | 158 ++++++++---- 12 files changed, 679 insertions(+), 120 deletions(-) create mode 100644 server/code/app/symbol/cpp_members.py diff --git a/docs/features/code-index/history-and-prs.md b/docs/features/code-index/history-and-prs.md index 8794a107f1e..ffb50a217d1 100644 --- a/docs/features/code-index/history-and-prs.md +++ b/docs/features/code-index/history-and-prs.md @@ -376,13 +376,49 @@ line there is exempt, so the comment below it is what keeps such a change visibl brace, a namespace line, an access specifier and an `#include` are code: each can move unchanged code into another scope or change which overload it calls. A comment in another language is a change, since the compiler reads some (a Go build constraint, a -cgo preamble, a TypeScript reference). A prototype or a call in a class body can change -what the class holds. A registration above a changed signature, or a member below a -function's closing line, is in no function at the side that holds it. The rule reads the -changed lines and the line above each run alone, so a blank line inside a multi-line -string or a heredoc, a comment-like line inside a C++ raw string or a macro argument, or -a declarator line whose macro is not spelled in capitals or with `_` (`* buf unused`, -`* NonNull ptr`), reads as blank or as a comment. +cgo preamble, a TypeScript reference). A registration above a changed signature is in +no function at the side that holds it. The rule reads the changed lines and the line +above each run alone, so a blank line inside a multi-line string or a heredoc, a +comment-like line inside a C++ raw string or a macro argument, or a declarator line +whose macro is not spelled in capitals or with `_` (`* buf unused`, `* NonNull ptr`), +reads as blank or as a comment. + +A changed line outside every function is placed on a definition, and adds no +`unmapped_changes`, where the language says which definition it belongs to. That +definition is then a touched symbol: it seeds the radius, and the tests section claims +its coverage, so the brief settles only when that claim says `covered_by`, and an +uncovered one answers `gaps`. + +- A line of a class body is placed on the class, on the side that holds it: a line the + diff removes on the index's class, a line it adds that no function of the new side + holds on the class that holds the run's lines and the line on each side of it in the + index. In C++ that is a member line: a member, a static constant, a method prototype, + a macro call. A brace, a class head, an access specifier, a `using` or `friend` + declaration, a namespace or preprocessor line, a line holding `/*` or `*/` and a + statement (`return x;`, a line of a method the parser did not read) stay changes: they + shape a scope or belong to a function nobody parsed. In Python every line of a class + body outside its methods (an attribute, a docstring) is placed, but a `class`, `def` + or decorator line, which opens a scope of its own. +- A C++ prototype is placed also on the function it declares, when the diff's files hold + one definition of that name: in a class body the function named for the class and the + prototype, at file scope the function of its name in the same file or a file of the + same stem (`widget.h` and `widget.cpp`), or a registration function by the index's + registration rule (`registerWidgets`), which is often declared beside the call that + runs it. Two definitions of the name under different qualified names leave it a + change. A registration statement inside a registration function's body is that + function's line already. +- The rules read the changed line, the line above it and the index's rows. A line of a + method the parser did not read as one (a head spelled with a macro it cannot expand) + sits in the class body by the rows, so a declaration in its body reads as a member + line and is placed on the class that holds the method. +- No line is placed that a macro or a statement continues (the line above it ends with + `\` or `??/`), that starts a run the hunk shows no line above (a diff with no context), + or that sits in a function the new side pairs with no row, or on a side nobody read. + +A constant or a static at file scope stays a change: the index links a C++ or Python +variable to none of its readers, so no claim could decide it. So do an `#include`, a +`using` line, a namespace line and a brace. Shell scripts have no class and no +prototype, and the other languages' lines in no function stay changes as before. The symbols section lists the wiring the PR adds as counts in `collapsed`, not as rows. The fold is how the section shows them: their coverage claims and regression records diff --git a/docs/features/code-index/operations.md b/docs/features/code-index/operations.md index 8b9d512440d..294031628db 100644 --- a/docs/features/code-index/operations.md +++ b/docs/features/code-index/operations.md @@ -646,7 +646,9 @@ line the diff adds that the unmapped-line rule does not exempt (a blank line or `//`, prose or doxygen comment line, with the limits in [history and PRs](history-and-prs.md)) sits in no function, and so does each line of a hunk sent with its header alone that replaces lines: `causes` holds `unmapped_changes` and `epistemic` -is `lower_bound`. +is `lower_bound`. A member line of a C++ or Python class body and a C++ prototype are +placed on the class and the function they declare instead, which join `touched_symbols` +and seed the radius ([history and PRs](history-and-prs.md) lists the rules). `impacted_tests` holds the rows `code.test_gate` lists for the same change at its default depth, whatever `depth` the radius is walked at, with the same `why` kinds, so the two ops name the same tests; test-map rows of the impacted paths ride as `test_map` rows. At diff --git a/docs/reference/operations/code.md b/docs/reference/operations/code.md index d271d547248..43ed4de13fb 100644 --- a/docs/reference/operations/code.md +++ b/docs/reference/operations/code.md @@ -896,7 +896,7 @@ Symbol-shaped (name/symbol_id) or diff-shaped (files/diff) blast radius. | `impacted_tests` | `list[dict[str, Any]]` | The test files code.test_gate lists for the same change at its default depth (2, whatever `depth` the radius is walked at), at most 30, strongest evidence first: each row as a code.test_gate `tests` row ({test_path, why, evidence, run… | | `co_change_files` | `list[dict[str, Any]]` | Files changed in the same merged PRs as the seed paths, most often first ({path, prs}, at most 20): the last 10 PRs for the symbol shape, 50 for the diff shape. | | `blast_radius_score` | `float` | impacted/50 + test-map rows/40, capped at 1. | -| `touched_symbols` | `list[dict[str, Any]]` | Diff shape only: the symbols the change touches (the functions its changed lines sit in when a diff was given, else every function in the files), and the files that historically co-change with the touched set but are absent from it — the… | +| `touched_symbols` | `list[dict[str, Any]]` | Diff shape only: the symbols the change touches (the functions its changed lines sit in when a diff was given, and the class or function a C++ or Python member line or a C++ prototype outside every function is placed on; else every… | | `co_change_missing` | `list[dict[str, Any]]` | Diff shape: co-change files absent from the change ({path, prs, of}, at most 5, support at least 4 PRs and 15%); empty for the symbol shape. | | `owners` | `list[dict[str, Any]]` | Who to ask: {author, share, prs, reviews, last_merged_at} from merged PRs over the seed paths — the PRs a person AUTHORED (`prs`) and the ones they REVIEWED (`reviews`, inline comments), recency-decayed (120-day half-life), share floor, at… | | `reverts` | `list[dict[str, Any]]` | Merged PRs over the seed paths that were REVERTS ({pr_number, title, merged_at}, newest first, <=5): the one kind of history that says what not to do, invisible to symbol lookups (the code is back) and to co-change (same files as the… | diff --git a/server/code/api/models_symbol.py b/server/code/api/models_symbol.py index a93c9ce7e6c..2c8f72ca423 100644 --- a/server/code/api/models_symbol.py +++ b/server/code/api/models_symbol.py @@ -670,10 +670,11 @@ def _drop_unset(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]: # predictor of a revert or fix PR it is weak (within noise in a # calibration replay). blast_radius_score: float = 0.0 - # Diff shape only: the symbols the change touches (the functions its changed - # lines sit in when a diff was given, else every function in the files), and the files that - # historically co-change with the touched set but are absent from it — - # the "did you forget to update X?" list. + # Diff shape only: the symbols the change touches (the functions its changed lines + # sit in when a diff was given, and the class or function a C++ or Python member + # line or a C++ prototype outside every function is placed on; else every function + # in the files), and the files that historically co-change with the touched set but + # are absent from it — the "did you forget to update X?" list. touched_symbols: list[dict[str, Any]] = Field(default_factory=list) # Diff shape: co-change files absent from the change ({path, prs, of}, at most 5, # support at least 4 PRs and 15%); empty for the symbol shape. @@ -710,11 +711,12 @@ def _drop_unset(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]: # constructor seed with no edge in an index that predates constructor # calls through factories), truncated (the walk or its page stopped short # of the graph), unmapped_changes (diff shape: a changed source line sits in - # no function, such as module-level code, a class body, a file with no - # definition, or a line the diff adds with no new side read or in a function the - # index holds no row of), new_side_unread (diff shape: the new side of a changed - # source file was asked for and not read), new_side_failed (with new_side_sha: a read - # of it failed, and a later call may read it)}. + # no function and is placed on no definition, such as module-level code, a class + # body line that is no member line, a file with no definition, or a line the diff + # adds with no new side read or in a function the index holds no row of), + # new_side_unread (diff shape: the new side of a changed source file was asked for + # and not read), new_side_failed (with new_side_sha: a read of it failed, and a later + # call may read it)}. epistemic: str = "lower_bound" # Why `epistemic` is `lower_bound`, from the set above; empty when it is `exact`. causes: list[str] = Field(default_factory=list) diff --git a/server/code/app/index/review_brief_build.py b/server/code/app/index/review_brief_build.py index 56ea5fea290..a7c4c10915e 100644 --- a/server/code/app/index/review_brief_build.py +++ b/server/code/app/index/review_brief_build.py @@ -476,7 +476,7 @@ def _unmapped(diff: str, inp: BriefInputs, kinds: dict[str, str]) -> bool: is not blank (`diff.is_blank`) of a source file the call graph is not built for, any change to one the diff carries no text of, and a line that is not blank of a source file an open PR deletes, which impact's parse of its diff leaves out. Impact maps - every other source line (`diff.unmapped_lines`).""" + every other source line (`diff.place_lines`).""" from server.code.domain.index.verdicts import is_graphed_path # ponytail: a blank line inside a multi-line string or a heredoc in no function reads diff --git a/server/code/app/symbol/cpp_members.py b/server/code/app/symbol/cpp_members.py new file mode 100644 index 00000000000..4b6dd822e66 --- /dev/null +++ b/server/code/app/symbol/cpp_members.py @@ -0,0 +1,70 @@ +"""What a changed C++ line outside every function declares, read off its text: a member of +the class whose body holds it, and the function a prototype declares. + +`diff.place_lines` places such a line on the class, and a prototype on the function the +index holds too, so a claim about that definition decides the line. A line that only +shapes a scope (a brace, a class head, an access specifier, `using`, `friend`, a +namespace or preprocessor line), one holding a comment delimiter and one a macro +continues stay changes in no definition: they can move unchanged code into another scope +or change what an unchanged line means, which no claim about one definition shows. +""" + +from __future__ import annotations + +import re + +# A line that shapes a scope rather than declare a member of it. +_SCOPE_LINE = re.compile( + r"\s*(?:#|[{};,\s]*$|(?:public|protected|private)\s*:|(?:using|friend|namespace)\b" + r"|(?:template\s*<.*>\s*)?(?:class|struct|union|enum)\b[^;]*$)" +) +# The head of a function declaration: the declarator's name and the `(` after it, with +# the words before it (the return type and specifiers) spelled as names, `::`, `<>`, `*`, +# `&` and `[]` only, so an assignment, a call's object or a cast is no head. +_HEAD = re.compile( + r"\s*(?P(?:[\w:<>,*&\[\]]+\s+)*?)[*&]*(?P~?[A-Za-z_]\w*)\s*\((?P.*)" +) +# A line that starts a statement of a function body. +_STATEMENT = re.compile( + r"\s*(?:(?:return|throw|co_return|co_yield|co_await|if|else|for|while|do|switch|case" + r"|break|continue|goto|try|catch)\b|default\s*:)" +) +# Words that open a statement, which a declaration's type cannot hold. +_STATEMENT_WORDS = frozenset( + "return throw co_return co_yield co_await new delete case else goto do if for while " + "switch sizeof alignof decltype typeid static_assert operator".split() +) + + +def member_line(text: str) -> bool: + """Whether a changed line of a class body, outside every function, declares a member + of the class: it shapes no scope (`_SCOPE_LINE`), starts no statement (`return x;` + is a line of a method the parser did not read), holds no comment delimiter, does not + end with `\\` or `??/`, and opens and closes as many braces as it holds, so it + neither starts nor ends a scope (`void f() { g(); }` does neither).""" + s = text.rstrip() + if _SCOPE_LINE.match(s) or "/*" in s or "*/" in s or s.endswith(("\\", "??/")): + return False + if _STATEMENT.match(s): + return False + return s.count("{") == s.count("}") + + +def declared_name(text: str, *, in_class: bool) -> str: + """The name a line declares as a function, '' when it declares none: a prototype on one + line (`bool isEmpty(const Rows & rows) const;`, `static T f(X x);`), and in a class + body also the first line of one the next lines continue (`void setRange(`) and a + constructor, which names no type. Outside a class the line must name a return type. + A name spelled in capitals is a macro (`DECLARE(...)`), and one after a word that + opens a statement (`return f(x);`) is a call.""" + m = _HEAD.match(text) + if m is None: + return "" + name, words, rest = m["name"], m["type"].split(), m["rest"].rstrip() + if name.isupper() or name in _STATEMENT_WORDS or _STATEMENT_WORDS.intersection(words): + return "" + if "{" in rest: + return "" + if rest.endswith(";"): + return name if in_class or words else "" + return name if in_class and (rest == "" or rest.endswith(",")) else "" diff --git a/server/code/app/symbol/diff.py b/server/code/app/symbol/diff.py index 1dd0dfbfb5b..0c1c092788e 100644 --- a/server/code/app/symbol/diff.py +++ b/server/code/app/symbol/diff.py @@ -18,7 +18,7 @@ # outside every method (an attribute, a decorator), and a line of its body is not the # method's below it. DEFINITION_KINDS = ("function", "method", "fixture", "class") -# Where a line `unmapped_lines` names sits: an old line the diff removes or replaces, the +# Where a line `place_lines` leaves unmapped sits: an old line the diff removes or replaces, the # old line a run of added lines with no text in the diff follows, or a new line it adds Side = Literal["removed", "inserted", "added"] # A diff's new side, per path: the extents of its functions there, `(start_line, @@ -29,6 +29,12 @@ NewSide = dict[str, list[tuple[int, int, str]]] +# A changed line `_place_member` must not place: in a function that pairs with no row, on a +# side nobody read, added by a hunk sent without its lines, or in a run whose enclosing +# definition is not known (`_FileSpans.around`). +_HELD: dict[str, Any] = {"kind": "held"} + + _ASCII_SPACE = " \t\f\v\r" @@ -530,6 +536,28 @@ def inserted_in(self, ins: Insertion) -> dict[str, Any] | None: return self.ends[ins.after] return self.holders.get(ins.after) + def around(self, blocks: list[Block]) -> dict[int, dict[str, Any] | None]: + """By the first new line of each run (`Block.new`), the innermost definition that + holds the run's old lines and the old line on each side of it (`after` and the line + below the last it removes): a run there is inside that definition on both sides of + the diff. None when no definition holds both lines, `_HELD` when their innermost rows + differ and neither holds both (an outer one may). + The two lines' innermost rows are found by bisection, once for the file.""" + bounds = {b.new: (b.after, b.after + len(b.removed) + 1) for b in blocks} + inner = _innermost(self.rows, sorted({n for pair in bounds.values() for n in pair})) + out: dict[int, dict[str, Any] | None] = {} + for key, (top, below) in bounds.items(): + up, down = inner.get(top), inner.get(below) + if up is None or down is None: + out[key] = None + elif _span(up)[1] >= below: + out[key] = up + elif _span(down)[0] <= top: + out[key] = down + else: + out[key] = _HELD + return out + def holds(self, hunk: Hunk) -> bool: """Whether a changed line of the hunk sits in a definition.""" for a, b in hunk.removed: @@ -555,7 +583,7 @@ def edited( self, hunks: list[Hunk], placed: _Placed | None = None ) -> tuple[list[dict[str, Any]], int]: """(the rows the hunks edit, the changed lines the old side places in none, which - code.test_gate counts; `unmapped_lines` places each side's lines). The edited + code.test_gate counts; `place_lines` places each side's lines). The edited definition is the innermost one whose span holds a changed line. The removed ranges are merged before the walk, so its cost follows the file's extent and not what the hunk headers claim. With the file's new side read (`placed`), a line a @@ -617,7 +645,7 @@ def _touched_rows_for_diff( ) -> tuple[list[dict[str, Any]], list[str], int]: """(the touched definition rows in seed order, the ids the walk seeds, the changed lines the old side places in no definition, counted in the files `symbol_rows` has a - row of: code.test_gate's count, where `unmapped_lines` places each side's; in a file + row of: code.test_gate's count, where `place_lines` places each side's; in a file `new_side` holds, only the removed lines and the runs of hunks sent without their lines, which code.impact drops). A file with hunks touches the definitions its changed lines sit in, a line it adds on the diff's `new_side` where that was read @@ -670,12 +698,51 @@ def _touched_rows_for_diff( return out, list(dict.fromkeys(sid for r in out for sid in r["tier_ids"])), unmapped -def unmapped_lines( +def touched_by_diff( definitions: list[dict[str, Any]], changes: dict[str, list[Hunk]], *, new_side: NewSide | None = None, -) -> dict[str, list[tuple[int, int, Side]]]: +) -> tuple[list[dict[str, Any]], list[dict[str, Any]], bool]: + """(the definitions a diff touches, which seed code.impact's walk and are the subjects + of its claims; the ones code.test_gate reads, every class a changed line of a body + sits in included; whether a changed line is placed on no definition). A function is + touched by a line it holds (`_touched_rows_for_diff`), a class or a function by a + C++ member line or prototype placed on it (`place_lines`); a class that holds only + lines that stay changes in no definition is the test gate's alone.""" + rows, _, _ = _touched_rows_for_diff(definitions, changes, new_side=new_side) + placement = place_lines(definitions, changes, new_side=new_side) + held = {(str(r["path"]), str(r["symbol_id"])) for r in rows} + rows += [ + {**r, "via": "hunk", "tier_ids": list(r.get("tier_ids") or [r["symbol_id"]])} + for r in placement.rows + if (str(r["path"]), str(r["symbol_id"])) not in held + ] + placed = {(str(r["path"]), str(r["symbol_id"])) for r in placement.rows} + seeds = [ + r + for r in rows + if str(r.get("kind")) != "class" or (str(r["path"]), str(r["symbol_id"])) in placed + ] + return seeds, rows, bool(placement.unmapped) + + +class Placement(NamedTuple): + """Where `place_lines` puts a diff's changed lines outside every function.""" + + # Per source file, the changed lines placed on no definition, as `(first, last, side)`. + unmapped: dict[str, list[tuple[int, int, Side]]] + # The definition rows a C++ line outside every function is placed on: the class whose + # body holds a member line, and the function a prototype declares. + rows: list[dict[str, Any]] + + +def place_lines( + definitions: list[dict[str, Any]], + changes: dict[str, list[Hunk]], + *, + new_side: NewSide | None = None, +) -> Placement: """Per source file, the changed lines that are not inert (`inert_lines`) and sit in no function, each placed on its own side: a line the diff removes or replaces against the definitions the index holds (`definitions`, the old side), a line it adds against @@ -690,17 +757,24 @@ def unmapped_lines( the hunk's header credits it to a definition the index holds no body extent for: no line number says the definition holds it. A hunk sent without its lines that replaces lines adds the lines of its header's new range, which nothing places. A line the diff - carries no text of is never inert. Any of these makes code.impact's - `unmapped_changes`, and its touched functions a floor; code.test_gate counts its own - from `_touched_rows_for_diff`, where a line of a class body touches the class. A test - file's lines are not counted: its functions are leaves of the graph. Lines outside - every definition are walked as ranges, the definitions that hold the rest are found - once per file and the lines the diff adds by bisection, so the cost follows the - file's extent and the diff's lines, not what the hunk headers claim.""" + carries no text of is never inert. + + A line outside every function is placed on a definition instead where the language + says which (`_place_member`): a member line of a class body on the class, and a C++ + prototype on the function it declares as well. Those rows are `rows`. + + Any line left makes code.impact's `unmapped_changes`, and its touched functions a + floor; code.test_gate counts its own from `_touched_rows_for_diff`, where a line of a + class body touches the class. A test file's lines are not counted: its functions are + leaves of the graph. Lines outside every definition are walked as ranges, the + definitions that hold the rest are found once per file and the lines the diff adds by + bisection, so the cost follows the file's extent and the diff's lines, not what the + hunk headers claim.""" by_path: dict[str, list[dict[str, Any]]] = {} for r in definitions: by_path.setdefault(str(r["path"]), []).append(r) out: dict[str, list[tuple[int, int, Side]]] = {} + placed: dict[str, dict[str, Any]] = {} for p, hunks in changes.items(): if not hunks or not is_graphed_path(p) or is_test_path(p): continue @@ -713,11 +787,12 @@ def unmapped_lines( else None ) text = _removed_lines(hunks) + added = dict(_added_lines(hunks)) keys = sorted(text) - cont, unseen = _run_context(hunks, removed=True) - inert_old = inert_lines(text, p, continued=cont, unseen=unseen) - cont, unseen = _run_context(hunks, removed=False) - inert_new = inert_lines(dict(_added_lines(hunks)), p, continued=cont, unseen=unseen) + cont_old, unseen_old = _run_context(hunks, removed=True) + inert_old = inert_lines(text, p, continued=cont_old, unseen=unseen_old) + cont_new, unseen_new = _run_context(hunks, removed=False) + inert_new = inert_lines(added, p, continued=cont_new, unseen=unseen_new) missed: list[tuple[int, int, Side]] = [] by_lines: list[Hunk] = [] for hunk in hunks: @@ -729,19 +804,134 @@ def unmapped_lines( missed += _added(hunk, seeds, inert_new) removed = cr.merge_ranges(r for h in by_lines for r in h.removed) inside = _clip(removed, spans.covered) - missed += _changed(_outside(removed, inside), keys, inert_old) + # A changed line outside every function, with the class that holds it or None at + # file scope: `_place_member` may place it + loose: list[tuple[tuple[int, int, Side], dict[str, Any] | None]] = [ + (m, None) for m in _changed(_outside(removed, inside), keys, inert_old) + ] lines = [n for a, b in inside for n in range(a, b + 1)] owners = spans.owners(lines) - missed += [ - (n, n, "removed") + loose += [ + ((n, n, "removed"), owners[n]) for n in lines if str(owners[n].get("kind")) == "class" and n not in inert_old ] + # A line no function holds on the new side sits where its run sits on the old side + # (`around`); a line of a function that pairs with no row stays a change, and so + # does one of a side nobody read + around = spans.around([b for h in by_lines for b in h.blocks if b.added]) + run_of = {b.new + k: b.new for h in by_lines for b in h.blocks for k in range(len(b.added))} for hunk in by_lines: - missed += _added(hunk, seeds, inert_new) + loose += [ + (m, around[run_of[m[0]]]) + if seeds is not None and hunk.blocks and m[0] not in seeds + else (m, _HELD) + for m in _added(hunk, seeds, inert_new) + ] + context = { + "removed": (text, cont_old, unseen_old), + "added": (added, cont_new, unseen_new), + } + for m, holder in loose: + lines_of, cont, unseen = context.get(m[2], ({}, frozenset(), frozenset())) + rows = ( + _place_member(m[0], holder, p, by_path, lines_of, cont, unseen) + if holder is not _HELD and m[0] == m[1] + else [] + ) + if rows: + placed.update((str(r["symbol_id"]), r) for r in rows) + else: + missed.append(m) if missed: out[p] = missed - return out + return Placement(out, list(placed.values())) + + +def _place_member( + n: int, + holder: dict[str, Any] | None, + path: str, + by_path: dict[str, list[dict[str, Any]]], + lines: dict[int, str], + continued: frozenset[int], + unseen: frozenset[int], +) -> list[dict[str, Any]]: + """The definition rows changed line `n` of one side (`lines`) outside every function + is placed on, none when it stays a change in no definition. A line a macro or a + statement continues (`_CONTINUES`: the line above it on its side, or the context line + above its run, `continued`), or that starts a run the hunk shows no line above + (`unseen`), is never placed: it may be a macro's body or another line's end. + + In C++ a member line of a class body (`cpp_members.member_line`) is placed on the + class (`holder`), and a prototype there also on the function it declares + (`cpp_members.declared_name`): the definitions of the diff's files named for the + class and the prototype. A prototype at file scope (`holder` None) is placed on the + function of its name in the diff's files that sits in the same file or one of the + same stem (`widget.h` and `widget.cpp`), or that is a registration function + (`is_registration_caller`, often declared beside the call that runs it): only when + they name one definition. In Python a class body is one scope its indentation + keeps, and a line of it outside every method (an attribute, a docstring) is placed + on the class, but a `class`, `def` or decorator line (`_PY_HEAD`), which opens a + scope of its own; a module line is placed on nothing, as a shell line is: a shell script + has no class and no prototype.""" + from server.code.app.symbol.cpp_members import declared_name, member_line + from server.code.domain.extract.registration import is_registration_caller + + lang = lang_for_path(path) + t = lines.get(n) + if t is None or n in continued or n in unseen or lang not in ("cpp", "python"): + return [] + if lines.get(n - 1, "").rstrip().endswith(_CONTINUES): + return [] + is_class = holder is not None and str(holder.get("kind")) == "class" + if lang == "python": + # a `class` or `def` head opens a scope of its own, and a decorator heads one + head = _PY_HEAD.match(t) + return [holder] if holder is not None and is_class and head is None else [] + if holder is not None and is_class: + if not member_line(t): + return [] + name = declared_name(t, in_class=True) + owner = _bare(str(holder["qualified_name"])) + return [holder, *_named(by_path, lambda q: q[-2:] == [owner, name])] if name else [holder] + name = declared_name(t, in_class=False) if holder is None else "" + if not name: + return [] + stem = _stem(path) + return _named( + by_path, + lambda q: q[-1] == name, + lambda p: p == path or _stem(p) == stem or is_registration_caller(name), + ) + + +# A Python line that opens a scope: a class or function head, or a decorator. +_PY_HEAD = re.compile(r"\s*(?:class\s|def\s|async\s+def\s|@)") + + +def _named( + by_path: dict[str, list[dict[str, Any]]], + name_ok: Any, + path_ok: Any = None, +) -> list[dict[str, Any]]: + """The function rows whose qualified name (`::` parts, parameters dropped) `name_ok` + accepts, in files `path_ok` accepts, when they share one qualified name (overloads + are one subject of a claim), else none.""" + rows = [ + r + for p, rs in by_path.items() + if path_ok is None or path_ok(p) + for r in rs + if str(r.get("kind")) != "class" + and name_ok(str(r["qualified_name"]).split("(", 1)[0].strip().split("::")) + ] + return rows if len({str(r["qualified_name"]) for r in rows}) == 1 else [] + + +def _stem(path: str) -> str: + """A file's name without its extension: `src/ui/widget.h` is `widget`.""" + return path.rsplit("/", 1)[-1].split(".", 1)[0] def _run_context(hunks: list[Hunk], *, removed: bool) -> tuple[frozenset[int], frozenset[int]]: diff --git a/server/code/app/symbol/impact.py b/server/code/app/symbol/impact.py index 5b97486bc36..a197cac93ef 100644 --- a/server/code/app/symbol/impact.py +++ b/server/code/app/symbol/impact.py @@ -33,9 +33,8 @@ DEFINITION_KINDS, NewSide, _parse_unified_diff_full, - _touched_rows_for_diff, paired_extents, - unmapped_lines, + touched_by_diff, ) from server.code.app.symbol.dispatch import _dispatch_missing, _dispatch_seeds from server.code.app.symbol.edges import ( @@ -192,23 +191,21 @@ async def _diff_seeds( new_side, unread, failed = await _new_side( repo, org, ns, changes, definitions, overlay, new_side_sha ) - # Classes are read so that a line of a class body is not taken for the method below it; - # the radius is seeded by functions only. - touched_rows, _, _ = _touched_rows_for_diff(definitions, changes, new_side=new_side) + touched_rows, gate_touched, unmapped = touched_by_diff(definitions, changes, new_side=new_side) added_rows = _overlay_added_rows(overlay) causes = [CAUSE_NEW_SIDE_UNREAD] if unread else [] if failed: causes.append(CAUSE_NEW_SIDE_FAILED) - # a changed line in no function: the touched functions are then a floor - if unmapped_lines(definitions, changes, new_side=new_side): + # a changed line in no function and on no definition its text names: the touched + # functions are then a floor + if unmapped: causes.append(CAUSE_UNMAPPED) # The radius is seeded by a changed test function too. The test links are not: a # changed test file is a row on its own evidence, as in code.test_gate. gate_rows = ( - [r for r in touched_rows if not is_test_path(str(r["path"]))], + [r for r in gate_touched if not is_test_path(str(r["path"]))], [r for r in definitions if not is_test_path(str(r["path"]))], ) - touched_rows = [r for r in touched_rows if str(r.get("kind")) != "class"] seed_ids = list(dict.fromkeys(sid for r in touched_rows for sid in r["tier_ids"])) symbol_rows = [r for r in definitions if str(r.get("kind")) != "class"] if added_rows: diff --git a/server/code/domain/index/epistemic.py b/server/code/domain/index/epistemic.py index 0ad04b03e78..d154ff4671d 100644 --- a/server/code/domain/index/epistemic.py +++ b/server/code/domain/index/epistemic.py @@ -58,9 +58,10 @@ # code.test_gate and code.impact's diff shape. A changed source line sits in no # definition the index holds (module-level code, text added above a definition, a file # with no definition or one the index does not hold), so no definition answers for it. -# Each op counts its own: code.impact places a line the diff adds on the diff's new side -# and counts a line of a class body outside its methods too (`symbol.diff.unmapped_lines`), -# where code.test_gate's line touches the class. +# Each op counts its own: code.impact places a line the diff adds on the diff's new side, +# and a C++ member line of a class body or a prototype on the class and the function it +# declares, and counts any other line of a class body outside its methods too +# (`symbol.diff.place_lines`), where code.test_gate's line touches the class. CAUSE_UNMAPPED = "unmapped_changes" # code.impact's diff shape. The new side of a changed source file was asked for (an open # PR's overlay, `new_side_sha`) and not read: the lines the diff adds there are placed on diff --git a/tests/unit/test_code_diff_sides.py b/tests/unit/test_code_diff_sides.py index 4d493ed7381..561a18ebbf0 100644 --- a/tests/unit/test_code_diff_sides.py +++ b/tests/unit/test_code_diff_sides.py @@ -18,7 +18,7 @@ _parse_unified_diff_full, _touched_rows_for_diff, inert_lines, - unmapped_lines, + place_lines, ) from server.code.store.index.symbol_rank import _prefer_scip @@ -120,7 +120,7 @@ async def _placed( ) assert (unread, failed) == ([], False) touched, _, _ = _touched_rows_for_diff(definitions, changes, new_side=new_side) - missed = unmapped_lines(definitions, changes, new_side=new_side) + missed = place_lines(definitions, changes, new_side=new_side).unmapped return missed.get(path, []), [t[key] for t in touched] @@ -289,7 +289,7 @@ async def raises(*a: Any, **k: Any) -> bytes: monkeypatch.setattr(gitrepo, "show_file", raises) failed = ({}, ["src/m.py"], True) assert await impact._new_side(repo, ORG, NS, changes, rows, None, parent) == failed - missed = unmapped_lines(rows, changes, new_side={}) + missed = place_lines(rows, changes, new_side={}).unmapped assert missed["src/m.py"] == [(6, 6, "added"), (9, 9, "added")] @@ -299,7 +299,7 @@ async def test_with_a_new_side_read_the_count_holds_no_run_of_a_hunk_with_lines( """code.test_gate's count of changed lines in no definition reads the old side: a constant an open PR inserts between two module-level functions counts 1. With the new side read, the count holds only the removed lines in no definition and the runs of - hunks sent without their lines, so it is 0, and nothing reads it: `unmapped_lines` + hunks sent without their lines, so it is 0, and nothing reads it: `place_lines` places the constant in no function, its blank lines aside.""" base = "def f():\n return 1\n\n\ndef g():\n return 2\n" head = "def f():\n return 1\n\n\nX = 1\n\n\ndef g():\n return 2\n" @@ -311,7 +311,7 @@ async def test_with_a_new_side_read_the_count_holds_no_run_of_a_hunk_with_lines( assert (unread, failed) == ([], False) assert _touched_rows_for_diff(rows, changes) == ([], [], 1) assert _touched_rows_for_diff(rows, changes, new_side=side) == ([], [], 0) - assert unmapped_lines(rows, changes, new_side=side)["src/m.py"] == [(5, 5, "added")] + assert place_lines(rows, changes, new_side=side).unmapped["src/m.py"] == [(5, 5, "added")] async def test_a_parse_past_its_window_is_a_failed_read( @@ -493,7 +493,9 @@ def test_a_replacing_hunk_sent_without_its_lines_adds_its_new_range() -> None: _, _, changes = _parse_unified_diff_full(diff) rows = _rows("src/a.cpp", CPP_LONG) for new_side in (None, {"src/a.cpp": [(1, 5, "s-f@1")]}): - assert unmapped_lines(rows, changes, new_side=new_side) == {"src/a.cpp": [(3, 6, "added")]} + assert place_lines(rows, changes, new_side=new_side).unmapped == { + "src/a.cpp": [(3, 6, "added")] + } def test_placing_a_run_of_alternating_lines_costs_time_linear_in_it() -> None: @@ -505,7 +507,10 @@ def run(n: int) -> None: body = "".join(" x\n+y\n" for _ in range(n // 2)) diff = f"--- a/src/a.cpp\n+++ b/src/a.cpp\n@@ -1,{n // 2} +1,{n} @@\n{body}" _, _, changes = _parse_unified_diff_full(diff) - assert len(unmapped_lines([], changes, new_side={"src/a.cpp": []})["src/a.cpp"]) == n // 2 + assert ( + len(place_lines([], changes, new_side={"src/a.cpp": []}).unmapped["src/a.cpp"]) + == n // 2 + ) grows_linearly(run, 7_500, 30_000) @@ -649,22 +654,22 @@ def test_a_comment_below_a_line_that_continues_is_a_change() -> None: ) for path, hunk, line in cases: _, _, changes = _parse_unified_diff_full(f"--- a/{path}\n+++ b/{path}\n{hunk}") - assert unmapped_lines([], changes)[path] == [line] + assert place_lines([], changes).unmapped[path] == [line] # a changed `\\` line directly above a changed comment or blank line, on either side for sign, head, side in (("+", "-1 +1,3", "added"), ("-", "-1,3 +1", "removed")): for end, below in (("\\", "// note"), ("\\", ""), ("\\ ", "// note")): hunk = f"@@ {head} @@\n int a;\n{sign}#define LIST(M) {end}\n{sign}{below}\n" _, _, changes = _parse_unified_diff_full(f"--- a/src/l.cpp\n+++ b/src/l.cpp\n{hunk}") want = [(2, 2, side), (3, 3, side)] - assert unmapped_lines([], changes)["src/l.cpp"] == want, (sign, end, below) + assert place_lines([], changes).unmapped["src/l.cpp"] == want, (sign, end, below) # with no `\\` above, a comment is no change shown = "@@ -1,2 +1,3 @@\n int a;\n+// note\n int b;\n" _, _, changes = _parse_unified_diff_full(f"--- a/src/l.cpp\n+++ b/src/l.cpp\n{shown}") - assert unmapped_lines([], changes) == {} + assert place_lines([], changes).unmapped == {} # at the top of the file no line is above the run for top in ("@@ -0,0 +1,2 @@\n+\n+// note\n", "@@ -1 +0,0 @@\n-// note\n"): _, _, changes = _parse_unified_diff_full(f"--- a/src/l.cpp\n+++ b/src/l.cpp\n{top}") - assert unmapped_lines([], changes) == {}, top + assert place_lines([], changes).unmapped == {}, top def test_a_line_comment_removed_from_a_class_body_is_no_change_and_a_block_one_is() -> None: @@ -677,7 +682,7 @@ def test_a_line_comment_removed_from_a_class_body_is_no_change_and_a_block_one_i source = f"class S\n{{\n {comment}\n int a;\n}};\n" hunk = f"@@ -2,2 +2 @@\n {{\n- {comment}\n" _, _, changes = _parse_unified_diff_full(f"--- a/src/s.h\n+++ b/src/s.h\n{hunk}") - assert unmapped_lines(_rows("src/s.h", source), changes) == want, comment + assert place_lines(_rows("src/s.h", source), changes).unmapped == want, comment def test_a_blank_shell_line_on_the_first_line_is_a_change() -> None: @@ -688,7 +693,7 @@ def test_a_blank_shell_line_on_the_first_line_is_a_change() -> None: ("@@ -1 +0,0 @@\n-\n", (1, 1, "removed")), ): _, _, changes = _parse_unified_diff_full(f"--- a/src/run.sh\n+++ b/src/run.sh\n{hunk}") - assert unmapped_lines([], changes) == {"src/run.sh": [line]}, hunk + assert place_lines([], changes).unmapped == {"src/run.sh": [line]}, hunk def test_a_python_blank_line_on_the_first_two_lines_is_a_change() -> None: @@ -708,7 +713,7 @@ def test_a_python_blank_line_on_the_first_two_lines_is_a_change() -> None: ) for hunk, want in cases: _, _, changes = _parse_unified_diff_full(f"--- a/src/m.py\n+++ b/src/m.py\n{hunk}") - assert unmapped_lines([], changes).get("src/m.py") == want + assert place_lines([], changes).unmapped.get("src/m.py") == want def test_a_line_holding_a_comment_delimiter_is_a_change() -> None: @@ -729,4 +734,198 @@ def test_a_line_holding_a_comment_delimiter_is_a_change() -> None: ) for hunk, want in cases: _, _, changes = _parse_unified_diff_full(f"--- a/src/w.cpp\n+++ b/src/w.cpp\n{hunk}") - assert unmapped_lines([], changes).get("src/w.cpp") == want, hunk + assert place_lines([], changes).unmapped.get("src/w.cpp") == want, hunk + + +WIDGET_H = ( + "#pragma once\n\nnamespace ui\n{\n\nclass Widget\n{\npublic:\n int width() const;\n" + " void resize(int w);\n\nprivate:\n int w = 0;\n};\n\nint area(const Widget & x);\n\n}\n" +) +WIDGET_CPP = ( + '#include "widget.h"\n\nnamespace ui\n{\n\nint Widget::width() const\n{\n return w;\n}\n\n' + "void Widget::resize(int value)\n{\n w = value;\n}\n\n" + "int area(const Widget & x)\n{\n return x.width();\n}\n\n}\n" +) +# a registration function, declared in a header of its own name and defined in the file +# of what it registers +REGISTER_H = "#pragma once\n\nnamespace ui\n{\nvoid registerWidgets();\n}\n" +REGISTER_CPP = "namespace ui\n{\nvoid registerWidgets()\n{\n add();\n}\n}\n" + + +def _widget_rows() -> list[dict[str, Any]]: + return [ + *_rows("src/ui/widget.h", WIDGET_H), + *_rows("src/ui/widget.cpp", WIDGET_CPP), + *_rows("src/ui/register.h", REGISTER_H), + *_rows("src/ui/widgets.cpp", REGISTER_CPP), + ] + + +def _place_header( + tmp: Path, path: str, before: str, after: str, rows: list[dict[str, Any]] | None = None +) -> tuple[list[tuple[int, int, str]] | None, list[str]]: + """(the lines git's diff of `path` from `before` to `after` leaves unmapped, the + qualified names of the rows its other lines are placed on), the index holding the + widget files (`rows`) and the new side parsed from `after`.""" + from server.code.app.symbol.diff import paired_extents + + *_, diff = _commits(tmp, path, before, after) + _, _, changes = _parse_unified_diff_full(diff) + rows = _widget_rows() if rows is None else rows + head = _rows(path, after) + functions = [ + (r["start_line"], r["end_line"], r["qualified_name"], "") + for r in head + if r["kind"] != "class" + ] + here = [r for r in rows if r["path"] == path] + side = {path: paired_extents(functions, [r for r in here if r["kind"] != "class"], here)} + placement = place_lines(rows, changes, new_side=side) + return placement.unmapped.get(path), sorted(r["qualified_name"] for r in placement.rows) + + +@pytest.mark.parametrize( + ("old", "new", "placed"), + [ + # a member, a changed default, a prototype the index holds no definition of + (" int w = 0;\n", " int w = 0;\n int h = 0;\n", ["ui::Widget"]), + (" int w = 0;\n", " int w = 1;\n", ["ui::Widget"]), + (" int w = 0;\n", " int w = 0;\n bool empty() const;\n", ["ui::Widget"]), + # a prototype of a function the index holds, and one spread over two lines + ( + " void resize(int w);\n", + " void resize(int w, int h);\n", + ["ui::Widget", "ui::Widget::resize"], + ), + ( + " void resize(int w);\n", + " void resize(\n int w);\n", + ["ui::Widget", "ui::Widget::resize"], + ), + # a prototype at file scope, of the function the file of the same stem defines + ( + "int area(const Widget & x);\n", + "int area(const Widget & x, int scale = 1);\n", + ["ui::area"], + ), + ], +) +def test_a_member_line_or_a_prototype_is_placed_on_what_it_declares( + tmp_path: Path, old: str, new: str, placed: list[str] +) -> None: + """A C++ line of a class body outside every method is placed on the class, and a + prototype also on the function it declares when the diff's files hold it; a + prototype at file scope on the function of its name in the same file or one of the + same stem. Each side of the diff is placed: the old line on the index's class, the + new line where its run sits there. No line is left unmapped.""" + path = "src/ui/widget.h" + assert old in WIDGET_H + assert _place_header(tmp_path, path, WIDGET_H, WIDGET_H.replace(old, new)) == (None, placed) + + +@pytest.mark.parametrize( + ("old", "new"), + [ + # lines that shape a scope: an access specifier, a `using` and a `friend` + # declaration, a nested class's head, braces, a preprocessor line + (" int w = 0;\n", " int w = 0;\nprotected:\n"), + (" int w = 0;\n", " int w = 0;\n using Base::resize;\n"), + (" int w = 0;\n", " int w = 0;\n friend class Painter;\n"), + (" int w = 0;\n", " int w = 0;\n struct Size\n {\n };\n"), + (" int w = 0;\n", " int w = 0;\n#if WITH_HEIGHT\n int h = 0;\n#endif\n"), + # a statement of a method the parser did not read, a comment delimiter, a member + # a macro continues + (" int w = 0;\n", " int w = 0;\n return w;\n"), + (" int w = 0;\n", " int w = 0; /* px */\n"), + (" int w = 0;\n", " int w = 0;\n#define FIELD(x) \\\n int x;\n"), + # at file scope: a constant, which the index links to no reader, an include, and + # a prototype of a function no file of the diff of its stem defines + ("int area(const Widget & x);\n", "int area(const Widget & x);\nconst int limit = 4;\n"), + ("#pragma once\n", "#pragma once\n#include \n"), + ("int area(const Widget & x);\n", "int area(const Widget & x);\nint perimeter(int w);\n"), + ], +) +def test_a_line_that_shapes_a_scope_or_names_no_definition_stays_unmapped( + tmp_path: Path, old: str, new: str +) -> None: + """A changed line outside every function that shapes a scope, or whose text names + no definition the diff's files hold, stays a change in no definition, so the brief + cannot settle on it.""" + path = "src/ui/widget.h" + unmapped, _ = _place_header(tmp_path, path, WIDGET_H, WIDGET_H.replace(old, new)) + assert unmapped + + +def test_a_file_scope_prototype_is_placed_only_on_one_definition(tmp_path: Path) -> None: + """A prototype at file scope whose name two definitions of the diff's files share + under different qualified names (in two files of its stem) is ambiguous and stays + unmapped; a registration + function's is placed on it in whichever file defines it.""" + other = _rows("src/ui/impl/widget.cpp", "namespace ui::impl\n{\nint area(int x)\n{\n}\n}\n") + path = "src/ui/widget.h" + changed = WIDGET_H.replace("x);\n", "x, int scale);\n") + unmapped, placed = _place_header(tmp_path, path, WIDGET_H, changed, [*_widget_rows(), *other]) + assert (unmapped, placed) == ([(16, 16, "removed"), (16, 16, "added")], []) + path = "src/ui/register.h" + changed = REGISTER_H.replace("();", "(int flags);") + (tmp_path / "r").mkdir() + assert _place_header(tmp_path / "r", path, REGISTER_H, changed) == ( + None, + ["ui::registerWidgets"], + ) + + +def test_a_python_class_attribute_is_placed_on_the_class(tmp_path: Path) -> None: + """A Python class body is one scope its indentation keeps: an attribute or docstring + line outside every method is placed on the class, a module line on nothing, and a + `def` head whose function pairs with no row stays a change.""" + path = "src/app/conf.py" + before = 'class Conf:\n """Run settings."""\n retries = 3\n\n def run(self):\n return 1\n' + for old, new, want in ( + ("retries = 3", "retries = 5", (None, ["src.app.conf::Conf"])), + ("Run settings.", "Settings of a run.", (None, ["src.app.conf::Conf"])), + ( + " retries = 3\n", + " retries = 3\n def stop(self): pass\n", + ([(4, 4, "added")], []), + ), + # line 2 is blank, where an encoding cookie is read + ("class Conf:", "LIMIT = 2\n\n\nclass Conf:", ([(1, 1, "added"), (2, 2, "added")], [])), + ): + (tmp_path / str(len(old) + len(new))).mkdir() + after = before.replace(old, new) + rows = _rows(path, before) + got = _place_header(tmp_path / str(len(old) + len(new)), path, before, after, rows) + assert got == want, new + + +def test_a_line_in_an_unpaired_function_stays_unmapped(tmp_path: Path) -> None: + """A line the diff adds inside a function its new side pairs with no row is not + placed on the class around it.""" + # `resize` is renamed at the head: its body pairs with no row + path = "src/ui/widget.h" + inline = WIDGET_H.replace(" void resize(int w);\n", " void resize(int w) { w_ = w; }\n") + renamed = inline.replace("resize(int w) { w_ = w; }", "grow(int w) { w_ += w; }") + (tmp_path / "i").mkdir() + unmapped, placed = _place_header(tmp_path / "i", path, inline, renamed, _rows(path, inline)) + assert (unmapped, placed) == ([(10, 10, "added")], []) + + +def test_a_class_seeds_the_walk_only_through_a_line_placed_on_it(tmp_path: Path) -> None: + """`touched_by_diff`: a member line puts the class among the seeds and the subjects; + an access specifier, which stays unmapped, leaves it the test gate's alone.""" + from server.code.app.symbol.diff import touched_by_diff + + path = "src/ui/widget.h" + for sub, (case, change) in enumerate( + (("member", " int h = 0;\n"), ("access", "protected:\n")) + ): + (tmp_path / case).mkdir() + after = WIDGET_H.replace(" int w = 0;\n", f" int w = 0;\n{change}") + *_, diff = _commits(tmp_path / case, path, WIDGET_H, after) + _, _, changes = _parse_unified_diff_full(diff) + rows = _rows(path, WIDGET_H) + seeds, gate, unmapped = touched_by_diff(rows, changes, new_side={path: []}) + names = ([r["qualified_name"] for r in seeds], [r["qualified_name"] for r in gate]) + want = ((["ui::Widget"], ["ui::Widget"], False), ([], ["ui::Widget"], True))[sub] + assert (*names, unmapped) == want, case diff --git a/tests/unit/test_code_epistemic_envelope.py b/tests/unit/test_code_epistemic_envelope.py index 1fe70d1e574..ca28c0578a0 100644 --- a/tests/unit/test_code_epistemic_envelope.py +++ b/tests/unit/test_code_epistemic_envelope.py @@ -361,7 +361,7 @@ async def test_impact_names_a_changed_source_line_no_function_holds( """A changed line outside every function, or in a class body, is `unmapped_changes` and the answer a floor; a change inside the touched function on both of the diff's sides names none. With no new side to read, a line the diff adds is in no function.""" - from server.code.app.symbol.diff import _parse_unified_diff_full, unmapped_lines + from server.code.app.symbol.diff import _parse_unified_diff_full, place_lines async def parsed_at(org: str, ns: str, sha: str, paths: list[str]) -> Any: return {p: [(10, 20, "DB::A::insert", "")] for p in paths}, False @@ -381,7 +381,7 @@ async def parsed_at(org: str, ns: str, sha: str, paths: list[str]) -> Any: seed = _Repo().seed cls = {**_sym("DB::A", "cA", "src/A.cpp"), "kind": "class", "start_line": 1, "end_line": 60} _, _, changes = _parse_unified_diff_full(inside.replace("-12,1 +12,1", "-40,1 +40,1")) - assert unmapped_lines([cls, seed], changes) + assert place_lines([cls, seed], changes).unmapped def test_a_hunk_credited_to_a_row_with_no_body_extent_is_a_change_in_no_function() -> None: @@ -392,7 +392,7 @@ def test_a_hunk_credited_to_a_row_with_no_body_extent_is_a_change_in_no_function from server.code.app.symbol.diff import ( _parse_unified_diff_full, _touched_rows_for_diff, - unmapped_lines, + place_lines, ) f = {**_sym("DB::f", "sf", "src/R.cpp"), "kind": "function", "start_line": 10, "end_line": 10} @@ -402,8 +402,8 @@ def test_a_hunk_credited_to_a_row_with_no_body_extent_is_a_change_in_no_function touched, _, _ = _touched_rows_for_diff([f], changes) assert [(t["qualified_name"], t["via"]) for t in touched] == [("DB::f", "header")] side = {"src/R.cpp": [(10, 30, "sf")]} - assert unmapped_lines([f], changes, new_side=side) == {"src/R.cpp": [(20, 20, "removed")]} - assert unmapped_lines([f], changes, new_side={}) == { + assert place_lines([f], changes, new_side=side).unmapped == {"src/R.cpp": [(20, 20, "removed")]} + assert place_lines([f], changes, new_side={}).unmapped == { "src/R.cpp": [(20, 20, "removed"), (20, 20, "added")] } diff --git a/tests/unit/test_code_review_brief_sections.py b/tests/unit/test_code_review_brief_sections.py index ca28bdc2b54..d1586735d9b 100644 --- a/tests/unit/test_code_review_brief_sections.py +++ b/tests/unit/test_code_review_brief_sections.py @@ -1386,11 +1386,7 @@ def __init__( self.new_side = new_side async def __call__(self, op: str, body: dict[str, Any]) -> dict[str, Any]: - from server.code.app.symbol.diff import ( - _parse_unified_diff_full, - _touched_rows_for_diff, - unmapped_lines, - ) + from server.code.app.symbol.diff import _parse_unified_diff_full, touched_by_diff from server.code.domain.index.verdicts import paths_seen if op == "code.coverage_claim" and self.covered: @@ -1407,9 +1403,9 @@ async def __call__(self, op: str, body: dict[str, Any]) -> dict[str, Any]: if side is None: side = self.repo.parent_side if "new_side_sha" in body else self.repo.head_side side = self._paired(side, fns) - touched, _, _ = _touched_rows_for_diff(fns, changes, new_side=side) + touched, _, unmapped = touched_by_diff(fns, changes, new_side=side) keys = ("qualified_name", "path", "start_line", "tier") - rows = [{k: t[k] for k in keys} for t in touched if t["kind"] != "class"] + rows = [{k: t[k] for k in keys} for t in touched] if self.overlay: new = [f for f in fns if f["path"] in _NEW_FILES and f["kind"] != "class"] rows += [ @@ -1421,7 +1417,7 @@ async def __call__(self, op: str, body: dict[str, Any]) -> dict[str, Any]: "by_hop_counts": {1: 7}, "verdict": "" if rows else "no_seeds_in_hunks", "epistemic": "lower_bound", - "causes": ["unmapped_changes"] if unmapped_lines(fns, changes, new_side=side) else [], + "causes": ["unmapped_changes"] if unmapped else [], "paths_seen": paths_seen(body["files"], limit=len(body["files"])), **({"overlay": True} if self.overlay else {}), } @@ -1555,9 +1551,11 @@ async def test_the_symbols_section_collapses_the_wiring_the_pr_adds_and_nothing_ "DB::FunctionGetMacro::executeImpl", "DB::FunctionGetMacro::useDefaultImplementationForConstants", "DB::FunctionFactory::isDeterministic", + "DB::FunctionGetMacro", "DB::FunctionGetMacro::getName", "DB::FunctionGetMacro::getName", "DB::FunctionGetMacro::getReturnTypeImpl", + "DB::FunctionGetSetting", "DB::FunctionGetSettingOrDefault::isDeterministic", "DB::create", "DB::registerStorageFoo", @@ -1565,7 +1563,7 @@ async def test_the_symbols_section_collapses_the_wiring_the_pr_adds_and_nothing_ assert [r["qualified_name"] for r in sym["rows"]] == kept assert not any("via" in r for r in sym["rows"]) assert sym["collapsed"] == {"registration": 2, "factory": 1, "constructor": 1, "one_line": 1} - assert sym["note"].startswith("12 touched functions and 5 collapsed;") + assert sym["note"].startswith("14 touched functions and 5 collapsed;") # the callers are read once, in both tiers, for the factories and constructors with # outside sites: the constructor's one site is in the parser's edges assert repo.asked == [["s-ctor", "s-ctor-ts"]] @@ -1585,10 +1583,11 @@ async def test_the_symbols_section_collapses_the_wiring_the_pr_adds_and_nothing_ history = [b["name"] for op, b in calls.calls if op == "code.symbol_history"] files = [_FACTORY, _SETTING, _SETTING, _MACRO, _MACRO, _MACRO] assert history == [f"{p}:{n}" for p, n in zip(files, first, strict=True)] - # a record is read per definition: the two files' registrations are two + # a record is read per definition: the two files' registrations are two; the two classes + # whose member lines the PR adds are two more assert (secs["tests"]["causes"], secs["history"]["causes"]) == ( - ["not_claimed:9"], - ["not_read:10"], + ["not_claimed:11"], + ["not_read:12"], ) # the files the PR adds hold lines outside every function (the fixture's lines 1-9 # of `getMacro.cpp`, its includes and namespace lines): those changes were checked by @@ -1615,20 +1614,22 @@ async def test_the_symbols_section_collapses_the_wiring_the_pr_adds_and_nothing_ assert payload["sections"]["symbols"]["failed"] == ["edges_for_symbols:RuntimeError"] assert "edges_for_symbols:RuntimeError" not in payload["sections"]["symbols"]["causes"] # call sites uncounted, or an open PR (its diff is its head's, which the index rows - # are not at; its added functions are the overlay's): nothing folds - for inp, repo, calls in ( - (_wiring_inputs(), _WiringRepo(counts_fail=True), _WiringCalls()), + # are not at; its added functions are the overlay's): nothing folds. The open PR adds + # its classes too, which the index does not hold, so their member lines touch none + for inp, repo, calls, n in ( + (_wiring_inputs(), _WiringRepo(counts_fail=True), _WiringCalls(), 19), ( dataclasses.replace(_wiring_inputs(), open=True), _WiringRepo(), _WiringCalls(overlay=True), + 17, ), ): payload = await review_brief_build.build_brief( inp, call=calls, repo=repo, tracker_rows=_tracker_not_bound, now=_fixed_now ) sym = payload["sections"]["symbols"] - assert "collapsed" not in sym and len(sym["rows"]) == 17 + assert "collapsed" not in sym and len(sym["rows"]) == n # A registration the PR adds to `getSetting.cpp` after line 68, behind a blank line @@ -1815,10 +1816,10 @@ async def functions_for_paths(self, *a: Any, **kw: Any) -> list[dict[str, Any]]: @pytest.mark.asyncio async def test_a_pr_that_adds_a_whole_file_holds_every_line_outside_a_function() -> None: """Of the file's lines outside a function only the blank ones have no behaviour of - their own: its include, namespace lines, braces, access specifier, class head and the - `name` constant whose value `getName` returns keep `unmapped_changes`, though the - wiring folds.""" - from server.code.app.symbol.diff import _parse_unified_diff_full, unmapped_lines + their own: its include, namespace lines, braces, access specifier and class head keep + `unmapped_changes`, though the wiring folds. The `name` constant whose value + `getName` returns is a member line: it touches the class.""" + from server.code.app.symbol.diff import _parse_unified_diff_full, place_lines lines = _GET_FOO_TEXT.splitlines() diff = ( @@ -1826,7 +1827,7 @@ async def test_a_pr_that_adds_a_whole_file_holds_every_line_outside_a_function() f"@@ -0,0 +1,{len(lines)} @@\n" + "".join(f"+{ln}\n" for ln in lines) ) _, _, changes = _parse_unified_diff_full(rb.reversed_diff(diff)) - missed = unmapped_lines(await _GetFooRepo().functions_for_paths(), changes)[_GET_FOO] + missed = place_lines(await _GetFooRepo().functions_for_paths(), changes).unmapped[_GET_FOO] outside = [lines[n - 1] for a, b, _ in missed for n in range(a, b + 1)] assert "public:" in outside and "#include " in outside repo = _GetFooRepo() @@ -1840,7 +1841,10 @@ async def test_a_pr_that_adds_a_whole_file_holds_every_line_outside_a_function() ) secs = payload["sections"] sym = secs["symbols"] - assert [r["qualified_name"] for r in sym["rows"]] == ["DB::FunctionGetFoo::executeImpl"] + assert [r["qualified_name"] for r in sym["rows"]] == [ + "DB::FunctionGetFoo", + "DB::FunctionGetFoo::executeImpl", + ] assert sym["collapsed"] == {"registration": 1, "factory": 1, "one_line": 1} with_rationale = {**secs, "rationale": {"verdict": "none"}} assert rb.brief_verdict(with_rationale) == ("unsettled", ["symbols:unmapped_changes"]) @@ -1850,22 +1854,23 @@ async def test_a_pr_that_adds_a_whole_file_holds_every_line_outside_a_function() async def test_an_open_brief_maps_the_lines_of_a_function_its_overlay_adds() -> None: """An open PR inserts a function into `Shift`: at its head that function holds the lines it adds, the blank above it has no behaviour, and the covered new function - settles the brief. A head whose functions lack it leaves the lines in no function.""" + settles the brief. A head whose functions lack it leaves its braces and body in no + function, and its head line is a member line of the class.""" body = "+\n+ int h() const\n+ {\n+ return 3;\n+ }\n" diff = _file_diff(_SHIFT, f"@@ -18,0 +19,5 @@\n{body}") inp = dataclasses.replace(_inputs(), diff=diff, changed_paths=[_SHIFT], open=True) h = _fn("o-h", _SHIFT, "DB::Shift::h", 20, 23, "overlay") head = [(12, 16, "DB::Shift::g"), (26, 29, "DB::Shift::k")] - for side, verdict in ( - ([*head, (20, 23, "DB::Shift::h")], ("covered_no_gaps", [])), - (head, ("unsettled", ["symbols:unmapped_changes"])), + for side, rows, verdict in ( + ([*head, (20, 23, "DB::Shift::h")], ["DB::Shift::h"], ("covered_no_gaps", [])), + (head, ["DB::Shift", "DB::Shift::h"], ("unsettled", ["symbols:unmapped_changes"])), ): calls = _WiringCalls(covered=True, repo=_ShiftRepo(), added=[h], new_side={_SHIFT: side}) payload = await review_brief_build.build_brief( inp, call=calls, repo=_ShiftRepo(), tracker_rows=_tracker_not_bound, now=_fixed_now ) secs = {**payload["sections"], "rationale": {"verdict": "none"}} - assert [r["qualified_name"] for r in secs["symbols"]["rows"]] == ["DB::Shift::h"] + assert [r["qualified_name"] for r in secs["symbols"]["rows"]] == rows assert rb.brief_verdict(secs) == verdict @@ -1895,10 +1900,10 @@ def _file_diff(path: str, hunks: str) -> str: @pytest.mark.asyncio -async def test_a_member_the_pr_adds_in_no_function_is_a_change() -> None: - """`step` is in the class body, in no function: inserted with no value, it still - changes the class (its layout, what a constructor initializes), so it stays - `unmapped_changes` beside the listed `k`.""" +async def test_a_member_the_pr_adds_where_the_hunk_shows_no_line_above_is_a_change() -> None: + """`step` is in the class body, in no function, and the hunk shows no line above it: + a macro the hunk does not show may continue onto it, so it stays `unmapped_changes` + beside the listed `k`, and the class is no subject.""" sym = await _shift_symbols(_SHIFT_DIFF + _STEP, _ShiftRepo()) assert ([r["qualified_name"] for r in sym["rows"]], sym["causes"]) == ( ["DB::Shift::k"], @@ -1906,6 +1911,59 @@ async def test_a_member_the_pr_adds_in_no_function_is_a_change() -> None: ) +class _ClassUncovered(_WiringCalls): + """`_WiringCalls` whose claims all say `covered_by` but the class `DB::Shift`'s.""" + + async def __call__(self, op: str, body: dict[str, Any]) -> dict[str, Any]: + if op == "code.coverage_claim" and body.get("symbol") == "DB::Shift": + self.calls.append((op, body)) + return {"verdict": "uncovered", "strongest_tier": "", "tests": []} + return await super().__call__(op, body) + + +@pytest.mark.parametrize( + ("line", "rows"), + [ + # a member, a changed default, a static constant, a call a macro may expand to a + # member: the class + (" int step = 0;", ["DB::Shift"]), + (" static constexpr int limit = 8;", ["DB::Shift"]), + (" check(table);", ["DB::Shift"]), + # prototypes: of a function the index does not hold, and of `k`, which the + # brief lists for its body too + (" int other() const;", ["DB::Shift"]), + (" int k(int step) const;", ["DB::Shift::k", "DB::Shift"]), + ], +) +@pytest.mark.parametrize("open_pr", [False, True]) +@pytest.mark.asyncio +async def test_a_member_line_of_a_class_body_is_claimed_on_the_class( + line: str, rows: list[str], open_pr: bool +) -> None: + """A member line the PR adds to `Shift`'s body below an unchanged member, merged or + open, touches the class (and a prototype the function it declares): no cause is + left, the class is a claim's subject, and the brief settles only when that claim + says `covered_by`. An uncovered class answers `gaps`.""" + diff = _SHIFT_DIFF + _file_diff(_SHIFT, f"@@ -17 +28,2 @@\n int base = 1;\n+{line}\n") + diff = diff.replace(f"{_file_diff(_SHIFT, '')}@@ -17", "@@ -17") + for calls, verdict in ( + (_WiringCalls(covered=True, repo=_ShiftRepo()), ("covered_no_gaps", [])), + (_ClassUncovered(covered=True, repo=_ShiftRepo()), ("gaps", ["uncovered_symbol"])), + ): + inp = dataclasses.replace( + _inputs(), diff=diff, changed_paths=rb.parse_diff(diff).paths, open=open_pr + ) + payload = await review_brief_build.build_brief( + inp, call=calls, repo=_ShiftRepo(), tracker_rows=_tracker_not_bound, now=_fixed_now + ) + secs = {**payload["sections"], "rationale": {"verdict": "none"}} + sym = secs["symbols"] + assert set(rows) <= {r["qualified_name"] for r in sym["rows"]} and sym["causes"] == [] + claimed = [b.get("symbol") for op, b in calls.calls if op == "code.coverage_claim"] + assert "DB::Shift" in claimed + assert rb.brief_verdict(secs) == verdict + + @pytest.mark.parametrize( "change", [ @@ -1923,9 +1981,10 @@ async def test_a_member_the_pr_adds_in_no_function_is_a_change() -> None: _file_diff(_CONF, "@@ -1 +1 @@\n-from json import loads\n+from orjson import loads\n"), # a shell script's environment _file_diff(_RUN, "@@ -1,0 +2 @@\n+export PATH=/opt/bin:$PATH\n"), - # an access specifier, a member with no value, a static with one, a value behind a - # block comment, an initializer's continuation, a block comment, which can end one - # the diff leaves as it was + # an access specifier, a member with no value in a hunk that shows no line above + # it (a macro may continue onto it), a static with one, a value behind a block + # comment, an initializer's continuation, a block comment, which can end one the + # diff leaves as it was _file_diff(_SHIFT, "@@ -17,0 +28 @@\n+ private:\n"), _file_diff(_SHIFT, "@@ -17,0 +28 @@\n+ int b;\n"), _file_diff(_SHIFT, "@@ -17,0 +28 @@\n+static Int64 counter(0);\n"), @@ -1934,15 +1993,14 @@ async def test_a_member_the_pr_adds_in_no_function_is_a_change() -> None: ), _file_diff(_SHIFT, "@@ -18 +28 @@\n- * 1024 * 1024;\n+ * 1024;\n"), _file_diff(_SHIFT, "@@ -17,0 +28,2 @@\n+ /* the step\n+ * per call */\n"), - # prototypes: of a function the brief does not list, of the listed `k` in its - # class, outside it, made virtual, and in another class - _file_diff(_SHIFT, "@@ -17,0 +28 @@\n+ int other() const;\n"), + # prototypes the hunk shows no line above: in the class, outside it, made + # virtual, and in another class _file_diff(_SHIFT, "@@ -17,0 +28 @@\n+ int k() const;\n"), _file_diff(_SHIFT, "@@ -20,0 +31 @@\n+int k();\n"), _file_diff(_SHIFT, "@@ -18 +28 @@\n- void f() const;\n+ virtual void f() const;\n"), _file_diff(_SHIFT, "@@ -33,0 +34 @@\n+ int k();\n"), - # a call in a class body, which a macro can expand to a member - _file_diff(_SHIFT, "@@ -17,0 +28 @@\n+ check(table);\n"), + # below a line a macro continues, a class body line is the macro's + _file_diff(_SHIFT, "@@ -17 +28,2 @@\n #define STEP(x) \\\n+ int x;\n"), # whole-line comments outside C++: one the compiler reads (a Go build constraint, # an export, a cgo preamble, a TypeScript reference), a shell one, and a Python one, # which may sit inside a module's string @@ -1962,9 +2020,11 @@ async def test_a_member_the_pr_adds_in_no_function_is_a_change() -> None: @pytest.mark.asyncio async def test_a_line_in_no_function_that_carries_a_value_is_a_change(change: str) -> None: """A line in no function that is neither blank nor a C++ `//`, prose or doxygen - comment line stays `unmapped_changes`, and the brief cannot settle: a comment in - another language can be one the compiler reads or sit inside a string, and a - prototype or a call in a class body can change what the class holds.""" + comment line, and that no definition is named by, stays `unmapped_changes`, and the + brief cannot settle: a comment in another language can be one the compiler reads or + sit inside a string, a line that shapes a scope can move unchanged code, and a class + body line below a line the hunk does not show, or below one a macro continues, may + be the macro's body.""" sym = await _shift_symbols(_SHIFT_DIFF + change, _LaneRepo(ts_rows=True)) assert sym["causes"] == ["unmapped_changes"] @@ -2543,13 +2603,14 @@ def deletes(*lines: str) -> str: ["DB::Shift::k"], ["unmapped_changes"], ), - # open: a member below `k`'s closing line, which git writes as a run after it + # open: a member below `k`'s closing line, which git writes as a run after it: + # the class holds it ( True, _file_diff(_SHIFT, "@@ -24,0 +25,2 @@\n+\n+ int counter = 0;\n"), [_G, (21, 24, "DB::Shift::k")], + ["DB::Shift"], [], - ["unmapped_changes"], ), # open: a module line below the last line of a Python function ( @@ -2588,8 +2649,9 @@ async def test_a_block_that_replaces_a_functions_first_line_places_what_it_adds_ ) -> None: """A block that replaces `k`'s first line edits `k`, by that old line. A line it adds is in `k` only where `k` spans it on the diff's new side: a registration above the - signature, a member below the closing line and a module line below a Python function - are in no function and keep `unmapped_changes`; the changed signature alone is `k`'s.""" + signature and a module line below a Python function are in no function and keep + `unmapped_changes`, a member below the closing line is the class's; the changed + signature alone is `k`'s.""" repo = _ShiftRepo() inp = dataclasses.replace(_inputs(), diff=diff, changed_paths=[], open=open_pr) path = _CONF if _CONF in diff else _SHIFT @@ -2842,7 +2904,7 @@ def test_a_form_feed_in_a_line_is_no_line_break() -> None: def test_mapping_many_hunks_onto_many_functions_costs_time_linear_in_both() -> None: """A file of n one-line hunks, each in its own one of n functions: the functions that hold the changed lines are found once for the file, not once per hunk.""" - from server.code.app.symbol.diff import _parse_unified_diff_full, unmapped_lines + from server.code.app.symbol.diff import _parse_unified_diff_full, place_lines from tests.unit.code_fixtures import grows_linearly def run(n: int) -> None: @@ -2850,7 +2912,7 @@ def run(n: int) -> None: _, _, changes = _parse_unified_diff_full(_file_diff(_SHIFT, hunks)) rows = [_fn(f"s{i}", _SHIFT, f"DB::f{i}", 4 * i + 1, 4 * i + 3) for i in range(n)] side = {_SHIFT: [(r["start_line"], r["end_line"], r["symbol_id"]) for r in rows]} - assert unmapped_lines(rows, changes, new_side=side) == {} + assert place_lines(rows, changes, new_side=side).unmapped == {} grows_linearly(run, 1_000, 4_000) From e20ece32c169189710d40a864198ad3b7e0b6a74 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 6 Dec 2026 06:05:58 +0000 Subject: [PATCH 02/16] Wrap the placement comments and import the member rules at module level Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- server/code/app/symbol/diff.py | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/server/code/app/symbol/diff.py b/server/code/app/symbol/diff.py index 0c1c092788e..0245fdd1eb7 100644 --- a/server/code/app/symbol/diff.py +++ b/server/code/app/symbol/diff.py @@ -9,6 +9,8 @@ from bisect import bisect_left, bisect_right from typing import Any, Literal, NamedTuple +from server.code.app.symbol.cpp_members import declared_name, member_line +from server.code.domain.extract.registration import is_registration_caller from server.code.domain.extract.treesitter import lang_for_path from server.code.domain.index import coverage_runs as cr from server.code.domain.index.test_gate import is_test_path @@ -18,8 +20,9 @@ # outside every method (an attribute, a decorator), and a line of its body is not the # method's below it. DEFINITION_KINDS = ("function", "method", "fixture", "class") -# Where a line `place_lines` leaves unmapped sits: an old line the diff removes or replaces, the -# old line a run of added lines with no text in the diff follows, or a new line it adds +# Where a line `place_lines` leaves unmapped sits: an old line the diff removes or +# replaces, the old line a run of added lines with no text in the diff follows, or a new +# line it adds Side = Literal["removed", "inserted", "added"] # A diff's new side, per path: the extents of its functions there, `(start_line, # end_line, seed)`, where `seed` is the id of the definition row a line the diff adds there @@ -540,9 +543,9 @@ def around(self, blocks: list[Block]) -> dict[int, dict[str, Any] | None]: """By the first new line of each run (`Block.new`), the innermost definition that holds the run's old lines and the old line on each side of it (`after` and the line below the last it removes): a run there is inside that definition on both sides of - the diff. None when no definition holds both lines, `_HELD` when their innermost rows - differ and neither holds both (an outer one may). - The two lines' innermost rows are found by bisection, once for the file.""" + the diff. None when no definition holds both lines, `_HELD` when their innermost + rows differ and neither holds both (an outer one may). The two lines' innermost + rows are found by bisection, once for the file.""" bounds = {b.new: (b.after, b.after + len(b.removed) + 1) for b in blocks} inner = _innermost(self.rows, sorted({n for pair in bounds.values() for n in pair})) out: dict[int, dict[str, Any] | None] = {} @@ -708,7 +711,7 @@ def touched_by_diff( of its claims; the ones code.test_gate reads, every class a changed line of a body sits in included; whether a changed line is placed on no definition). A function is touched by a line it holds (`_touched_rows_for_diff`), a class or a function by a - C++ member line or prototype placed on it (`place_lines`); a class that holds only + member line or a C++ prototype placed on it (`place_lines`); a class that holds only lines that stay changes in no definition is the test gate's alone.""" rows, _, _ = _touched_rows_for_diff(definitions, changes, new_side=new_side) placement = place_lines(definitions, changes, new_side=new_side) @@ -732,8 +735,8 @@ class Placement(NamedTuple): # Per source file, the changed lines placed on no definition, as `(first, last, side)`. unmapped: dict[str, list[tuple[int, int, Side]]] - # The definition rows a C++ line outside every function is placed on: the class whose - # body holds a member line, and the function a prototype declares. + # The definition rows a line outside every function is placed on: the class whose + # body holds a member line, and the function a C++ prototype declares. rows: list[dict[str, Any]] @@ -873,11 +876,8 @@ class and the prototype. A prototype at file scope (`holder` None) is placed on they name one definition. In Python a class body is one scope its indentation keeps, and a line of it outside every method (an attribute, a docstring) is placed on the class, but a `class`, `def` or decorator line (`_PY_HEAD`), which opens a - scope of its own; a module line is placed on nothing, as a shell line is: a shell script - has no class and no prototype.""" - from server.code.app.symbol.cpp_members import declared_name, member_line - from server.code.domain.extract.registration import is_registration_caller - + scope of its own; a module line is placed on nothing, as a shell line is: a shell + script has no class and no prototype.""" lang = lang_for_path(path) t = lines.get(n) if t is None or n in continued or n in unseen or lang not in ("cpp", "python"): From 2bf7011f0ca22d5a46082cc61cce2bdf7a0641c0 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 6 Dec 2026 06:30:42 +0000 Subject: [PATCH 03/16] A class-body line is placed only when it is shaped as a declaration A C++ member line now has to read as a declaration and hold no scope word, macro call, raw string or unclosed quote anywhere on it; a Python class-body line that opens a compound statement or an odd number of triple quotes stays a change. A file-scope line whose parentheses start with a literal is a constant, not a prototype. Prototypes are matched by the class's full qualified name through one index of the function names built per diff, never against a test file. A run whose two bounding lines sit in different rows is placed on the innermost row that holds both. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- docs/features/code-index/history-and-prs.md | 36 ++-- server/code/app/symbol/cpp_members.py | 108 ++++++++---- server/code/app/symbol/diff.py | 155 ++++++++++-------- tests/unit/test_code_diff_sides.py | 87 +++++++++- tests/unit/test_code_review_brief_sections.py | 31 ++-- 5 files changed, 283 insertions(+), 134 deletions(-) diff --git a/docs/features/code-index/history-and-prs.md b/docs/features/code-index/history-and-prs.md index ffb50a217d1..bb2a75917ed 100644 --- a/docs/features/code-index/history-and-prs.md +++ b/docs/features/code-index/history-and-prs.md @@ -392,21 +392,27 @@ uncovered one answers `gaps`. - A line of a class body is placed on the class, on the side that holds it: a line the diff removes on the index's class, a line it adds that no function of the new side holds on the class that holds the run's lines and the line on each side of it in the - index. In C++ that is a member line: a member, a static constant, a method prototype, - a macro call. A brace, a class head, an access specifier, a `using` or `friend` - declaration, a namespace or preprocessor line, a line holding `/*` or `*/` and a - statement (`return x;`, a line of a method the parser did not read) stay changes: they - shape a scope or belong to a function nobody parsed. In Python every line of a class - body outside its methods (an attribute, a docstring) is placed, but a `class`, `def` - or decorator line, which opens a scope of its own. -- A C++ prototype is placed also on the function it declares, when the diff's files hold - one definition of that name: in a class body the function named for the class and the - prototype, at file scope the function of its name in the same file or a file of the - same stem (`widget.h` and `widget.cpp`), or a registration function by the index's - registration rule (`registerWidgets`), which is often declared beside the call that - runs it. Two definitions of the name under different qualified names leave it a - change. A registration statement inside a registration function's body is that - function's line already. + index. In C++ that is a member line, one shaped as a declaration: a member, a static + constant, a method prototype or one of its parameter lines, a constructor. Any other + line stays a change: a brace, a class head or its base clause, an access specifier, a + `using` or `friend` declaration, a namespace or preprocessor line, a macro call, a + statement (`return x;`, a line of a method the parser did not read), a line that + holds one of those words after a member, `/*`, `*/`, a raw string's opener or a quote + no literal closes. They shape a scope, may expand to anything, or belong to a function + nobody parsed. In Python a line of a class body outside its methods (an attribute, a + docstring) is placed, but a `class` or `def` head, a decorator, a compound + statement's head (`if`, `try`, `for`, `with` and the rest) and a line with an odd + count of `"""` or `'''`, which opens or closes a string around lines the diff leaves. +- A C++ prototype is placed also on the function it declares, when the diff's files + outside tests hold one definition of it: in a class body the function whose + qualified name is the class's and the prototype's, at file scope the function of its + name in the same file or a file of the same stem (`widget.h` and `widget.cpp`), or a + registration function by the index's registration rule (`registerWidgets`), which is + often declared beside the call that runs it. Two definitions of the name under + different qualified names leave it a change, and so does a file-scope line whose + parentheses start with a literal (`static const std::regex re("a+");`), a constant + built by a constructor. A registration statement inside a registration function's + body is that function's line already. - The rules read the changed line, the line above it and the index's rows. A line of a method the parser did not read as one (a head spelled with a macro it cannot expand) sits in the class body by the rows, so a declaration in its body reads as a member diff --git a/server/code/app/symbol/cpp_members.py b/server/code/app/symbol/cpp_members.py index 4b6dd822e66..d6c3544fae2 100644 --- a/server/code/app/symbol/cpp_members.py +++ b/server/code/app/symbol/cpp_members.py @@ -1,22 +1,42 @@ -"""What a changed C++ line outside every function declares, read off its text: a member of -the class whose body holds it, and the function a prototype declares. +"""What a changed line outside every function declares, read off its text: a member of the +class whose body holds it, and in C++ the function a prototype declares. `diff.place_lines` places such a line on the class, and a prototype on the function the -index holds too, so a claim about that definition decides the line. A line that only -shapes a scope (a brace, a class head, an access specifier, `using`, `friend`, a -namespace or preprocessor line), one holding a comment delimiter and one a macro -continues stay changes in no definition: they can move unchanged code into another scope -or change what an unchanged line means, which no claim about one definition shows. +index holds too, so a claim about that definition decides the line. Only a line shaped +as a declaration is a member line. A line that shapes a scope (a brace, a class head or +its base clause, an access specifier, `using`, `friend`, a namespace, preprocessor or +compound statement line), one that may open or close a comment or a string the diff +leaves as it was, a statement and a macro call stay changes in no definition: they can +move unchanged code into another scope or change what an unchanged line means, which no +claim about one definition shows. """ from __future__ import annotations import re -# A line that shapes a scope rather than declare a member of it. -_SCOPE_LINE = re.compile( - r"\s*(?:#|[{};,\s]*$|(?:public|protected|private)\s*:|(?:using|friend|namespace)\b" - r"|(?:template\s*<.*>\s*)?(?:class|struct|union|enum)\b[^;]*$)" +# A C++ member declaration: one word or more of its type and specifiers (names, `::`, +# `<>`, `,`, `*`, `&`, `[]`), then its declarator's name, then what may follow a name in +# a declaration (`;`, `=`, `(`, `{`, `[`, `,`, `)` closing a parameter list, `:` of a +# bit-field, or the line's end). +_DECLARATION = re.compile( + r"\s*(?:[A-Za-z_][\w:<>,*&\[\]]*[\s*&]+)+~?[A-Za-z_]\w*\s*(?:[;=({\[,:)]|$)" +) +# A special member's head, which names no type: `explicit Widget(int w);`, `~Widget();`. +_SPECIAL = r"\s*(?:(?:explicit|constexpr|inline|virtual)\s+)*~?{name}\s*\(" +# What ends a prototype without a body: `= default;`, `= delete;`, `= 0;`. +_NO_BODY = re.compile(r"=\s*(?:default|delete|0)\s*;\s*$") +# Words that shape a scope or open a statement wherever they sit on a C++ line. +_CPP_SCOPE_WORDS = re.compile( + r"\b(?:using|friend|namespace|public|protected|private|class|struct|union|enum" + r"|template|typedef|return|throw|co_return|co_yield|co_await|if|else|for|while|do" + r"|switch|case|default|break|continue|goto|try|catch|operator)\b" +) +# A Python line of a class body that shapes a scope: a class or function head, a +# decorator, or a compound statement, which decides which of the lines below it exist. +_PY_SCOPE = re.compile( + r"\s*(?:@|(?:class|def|if|elif|else|try|except|finally|for|while|with|match|case" + r"|async)\b)" ) # The head of a function declaration: the declarator's name and the `(` after it, with # the words before it (the return type and specifiers) spelled as names, `::`, `<>`, `*`, @@ -24,39 +44,61 @@ _HEAD = re.compile( r"\s*(?P(?:[\w:<>,*&\[\]]+\s+)*?)[*&]*(?P~?[A-Za-z_]\w*)\s*\((?P.*)" ) -# A line that starts a statement of a function body. -_STATEMENT = re.compile( - r"\s*(?:(?:return|throw|co_return|co_yield|co_await|if|else|for|while|do|switch|case" - r"|break|continue|goto|try|catch)\b|default\s*:)" -) -# Words that open a statement, which a declaration's type cannot hold. +# Words a declaration's type cannot hold. _STATEMENT_WORDS = frozenset( "return throw co_return co_yield co_await new delete case else goto do if for while " "switch sizeof alignof decltype typeid static_assert operator".split() ) +# A string or character literal, whose text says nothing about the line's shape, and the +# opener of a raw string, which may span lines. +_STRING = re.compile(r"\"(?:[^\"\\]|\\.)*\"|'(?:[^'\\]|\\.)*'") +_RAW_STRING = re.compile(r'R"') +# What a constant's direct initializer may start with, which a parameter cannot. +_LITERAL_START = (*"\"'0123456789-+.{", 'R"', 'u8"', 'L"') -def member_line(text: str) -> bool: +def member_line(text: str, *, python: bool = False, owner: str = "") -> bool: """Whether a changed line of a class body, outside every function, declares a member - of the class: it shapes no scope (`_SCOPE_LINE`), starts no statement (`return x;` - is a line of a method the parser did not read), holds no comment delimiter, does not - end with `\\` or `??/`, and opens and closes as many braces as it holds, so it - neither starts nor ends a scope (`void f() { g(); }` does neither).""" + of the class. In C++ it is shaped as a declaration (`_DECLARATION`: `int width = 0;`, + `bool empty() const;`, a parameter line of a prototype spread over lines) or as the + head of a special member of class `owner` (`Widget(int w);`); outside its string + literals it holds no word that shapes a scope or opens a statement + (`_CPP_SCOPE_WORDS`), no `#`, `/*` or `*/`, no raw string (it may span lines) and no + quote a literal does not close, and no brace closes what the line did not open. In + Python it is any line but one that shapes a scope (`_PY_SCOPE`) or holds an odd count + of three quotes, which opens or closes a string around unchanged lines. In either, a + line ending with `\\` or `??/` continues onto the next one and is no member line.""" s = text.rstrip() - if _SCOPE_LINE.match(s) or "/*" in s or "*/" in s or s.endswith(("\\", "??/")): + if s.endswith(("\\", "??/")): + return False + if python: + return _PY_SCOPE.match(s) is None and not (s.count('"""') % 2 or s.count("'''") % 2) + if _RAW_STRING.search(s): + return False + s = _STRING.sub('""', s) + if "/*" in s or "*/" in s or "#" in s or s.count('"') % 2: return False - if _STATEMENT.match(s): + code = _NO_BODY.sub(";", s.split("//", 1)[0]) + special = owner != "" and re.match(_SPECIAL.format(name=re.escape(owner)), code) + if not (special or _DECLARATION.match(code)) or _CPP_SCOPE_WORDS.search(code): return False - return s.count("{") == s.count("}") + depth = 0 + for c in code: + depth += {"{": 1, "}": -1}.get(c, 0) + if depth < 0: + return False + return depth == 0 def declared_name(text: str, *, in_class: bool) -> str: - """The name a line declares as a function, '' when it declares none: a prototype on one - line (`bool isEmpty(const Rows & rows) const;`, `static T f(X x);`), and in a class - body also the first line of one the next lines continue (`void setRange(`) and a - constructor, which names no type. Outside a class the line must name a return type. - A name spelled in capitals is a macro (`DECLARE(...)`), and one after a word that - opens a statement (`return f(x);`) is a call.""" + """The name a C++ line declares as a function, '' when it declares none: a prototype on + one line (`bool isEmpty(const Rows & rows) const;`, `static T f(X x);`), and in a + class body also the first line of one the next lines continue (`void setRange(`) and + a constructor, which names no type. Outside a class the line must name a return type, + and what follows the `(` must not start with a literal, which makes the line a + constant built by a constructor (`static const std::regex re("a+");`). A name spelled + in capitals is a macro (`DECLARE(...)`), and one after a word that opens a statement + (`return f(x);`) is a call.""" m = _HEAD.match(text) if m is None: return "" @@ -66,5 +108,7 @@ def declared_name(text: str, *, in_class: bool) -> str: if "{" in rest: return "" if rest.endswith(";"): - return name if in_class or words else "" + if not in_class and (not words or rest.lstrip().startswith(_LITERAL_START)): + return "" + return name return name if in_class and (rest == "" or rest.endswith(",")) else "" diff --git a/server/code/app/symbol/diff.py b/server/code/app/symbol/diff.py index 0245fdd1eb7..fa3733c92ea 100644 --- a/server/code/app/symbol/diff.py +++ b/server/code/app/symbol/diff.py @@ -7,6 +7,7 @@ import re from bisect import bisect_left, bisect_right +from collections.abc import Callable from typing import Any, Literal, NamedTuple from server.code.app.symbol.cpp_members import declared_name, member_line @@ -32,12 +33,6 @@ NewSide = dict[str, list[tuple[int, int, str]]] -# A changed line `_place_member` must not place: in a function that pairs with no row, on a -# side nobody read, added by a hunk sent without its lines, or in a run whose enclosing -# definition is not known (`_FileSpans.around`). -_HELD: dict[str, Any] = {"kind": "held"} - - _ASCII_SPACE = " \t\f\v\r" @@ -447,6 +442,20 @@ def _decorated_start(start: int, changed: dict[int, str]) -> int: return start +def _parents(rows: list[dict[str, Any]]) -> dict[int, dict[str, Any]]: + """By `id` of each row, the innermost other row whose span holds it, for rows whose + spans nest; one pass over the rows in line order with the open rows on a stack.""" + out: dict[int, dict[str, Any]] = {} + stack: list[dict[str, Any]] = [] + for r in sorted(rows, key=lambda r: (_span(r)[0], -_span(r)[1])): + while stack and _span(stack[-1])[1] < _span(r)[1]: + stack.pop() + if stack: + out[id(r)] = stack[-1] + stack.append(r) + return out + + def _widest_first(rows: list[dict[str, Any]]) -> list[dict[str, Any]]: """`rows` as `_innermost` reads them: the innermost is written last.""" return sorted(rows, key=lambda r: _span(r)[0] - _span(r)[1]) @@ -507,6 +516,7 @@ def __init__(self, rows: list[dict[str, Any]], hunks: list[Hunk], *, indented: b ) self.covered = cr.merge_ranges(_span(e) for e in self.extents) self.indented = indented + self.parents = _parents(self.rows) self.starts = {_span(r)[0]: r for r in self.rows} self.ends = {_span(r)[1]: r for r in self.rows} gaps = sorted({ins.after for h in hunks for ins in h.inserted}) @@ -543,22 +553,17 @@ def around(self, blocks: list[Block]) -> dict[int, dict[str, Any] | None]: """By the first new line of each run (`Block.new`), the innermost definition that holds the run's old lines and the old line on each side of it (`after` and the line below the last it removes): a run there is inside that definition on both sides of - the diff. None when no definition holds both lines, `_HELD` when their innermost - rows differ and neither holds both (an outer one may). The two lines' innermost - rows are found by bisection, once for the file.""" + the diff. None when no definition holds both lines. The upper line's innermost row + is found by bisection, once for the file, and the innermost that holds both is the + nearest row around it that reaches the lower line (`parents`).""" bounds = {b.new: (b.after, b.after + len(b.removed) + 1) for b in blocks} - inner = _innermost(self.rows, sorted({n for pair in bounds.values() for n in pair})) + inner = _innermost(self.rows, sorted({top for top, _ in bounds.values()})) out: dict[int, dict[str, Any] | None] = {} for key, (top, below) in bounds.items(): - up, down = inner.get(top), inner.get(below) - if up is None or down is None: - out[key] = None - elif _span(up)[1] >= below: - out[key] = up - elif _span(down)[0] <= top: - out[key] = down - else: - out[key] = _HELD + row = inner.get(top) + while row is not None and _span(row)[1] < below: + row = self.parents.get(id(row)) + out[key] = row return out def holds(self, hunk: Hunk) -> bool: @@ -776,6 +781,7 @@ class body touches the class. A test file's lines are not counted: its functions by_path: dict[str, list[dict[str, Any]]] = {} for r in definitions: by_path.setdefault(str(r["path"]), []).append(r) + functions = _Functions(definitions) out: dict[str, list[tuple[int, int, Side]]] = {} placed: dict[str, dict[str, Any]] = {} for p, hunks in changes.items(): @@ -808,14 +814,14 @@ class body touches the class. A test file's lines are not counted: its functions removed = cr.merge_ranges(r for h in by_lines for r in h.removed) inside = _clip(removed, spans.covered) # A changed line outside every function, with the class that holds it or None at - # file scope: `_place_member` may place it - loose: list[tuple[tuple[int, int, Side], dict[str, Any] | None]] = [ - (m, None) for m in _changed(_outside(removed, inside), keys, inert_old) + # file scope, and whether `_place_member` may place it + loose: list[tuple[tuple[int, int, Side], dict[str, Any] | None, bool]] = [ + (m, None, True) for m in _changed(_outside(removed, inside), keys, inert_old) ] lines = [n for a, b in inside for n in range(a, b + 1)] owners = spans.owners(lines) loose += [ - ((n, n, "removed"), owners[n]) + ((n, n, "removed"), owners[n], True) for n in lines if str(owners[n].get("kind")) == "class" and n not in inert_old ] @@ -826,20 +832,20 @@ class body touches the class. A test file's lines are not counted: its functions run_of = {b.new + k: b.new for h in by_lines for b in h.blocks for k in range(len(b.added))} for hunk in by_lines: loose += [ - (m, around[run_of[m[0]]]) + (m, around[run_of[m[0]]], True) if seeds is not None and hunk.blocks and m[0] not in seeds - else (m, _HELD) + else (m, None, False) for m in _added(hunk, seeds, inert_new) ] context = { "removed": (text, cont_old, unseen_old), "added": (added, cont_new, unseen_new), } - for m, holder in loose: + for m, holder, placeable in loose: lines_of, cont, unseen = context.get(m[2], ({}, frozenset(), frozenset())) rows = ( - _place_member(m[0], holder, p, by_path, lines_of, cont, unseen) - if holder is not _HELD and m[0] == m[1] + _place_member(m[0], holder, p, functions, lines_of, cont, unseen) + if placeable and m[0] == m[1] else [] ) if rows: @@ -855,7 +861,7 @@ def _place_member( n: int, holder: dict[str, Any] | None, path: str, - by_path: dict[str, list[dict[str, Any]]], + functions: _Functions, lines: dict[int, str], continued: frozenset[int], unseen: frozenset[int], @@ -868,16 +874,17 @@ def _place_member( In C++ a member line of a class body (`cpp_members.member_line`) is placed on the class (`holder`), and a prototype there also on the function it declares - (`cpp_members.declared_name`): the definitions of the diff's files named for the - class and the prototype. A prototype at file scope (`holder` None) is placed on the - function of its name in the diff's files that sits in the same file or one of the - same stem (`widget.h` and `widget.cpp`), or that is a registration function - (`is_registration_caller`, often declared beside the call that runs it): only when - they name one definition. In Python a class body is one scope its indentation - keeps, and a line of it outside every method (an attribute, a docstring) is placed - on the class, but a `class`, `def` or decorator line (`_PY_HEAD`), which opens a - scope of its own; a module line is placed on nothing, as a shell line is: a shell - script has no class and no prototype.""" + (`cpp_members.declared_name`): the definitions of the diff's files whose qualified + name is the class's and the prototype's. A prototype at file scope (`holder` None) is + placed on the function of its name in the diff's files that sits in the same file or + one of the same stem (`widget.h` and `widget.cpp`), or that is a registration + function (`is_registration_caller`, often declared beside the call that runs it): + only when they name one definition. A test file's definitions are never one: a test + does not define what the code under test declares. In Python a class body is one + scope its indentation keeps, and a line of it outside every method (an attribute, a + docstring) is placed on the class, but not one that shapes a scope or may open a + string (`cpp_members.member_line`); a module line is placed on nothing, as a shell + line is: a shell script has no class and no prototype.""" lang = lang_for_path(path) t = lines.get(n) if t is None or n in continued or n in unseen or lang not in ("cpp", "python"): @@ -886,47 +893,55 @@ class and the prototype. A prototype at file scope (`holder` None) is placed on return [] is_class = holder is not None and str(holder.get("kind")) == "class" if lang == "python": - # a `class` or `def` head opens a scope of its own, and a decorator heads one - head = _PY_HEAD.match(t) - return [holder] if holder is not None and is_class and head is None else [] + return [holder] if holder is not None and is_class and member_line(t, python=True) else [] if holder is not None and is_class: - if not member_line(t): + owner = _parts(str(holder["qualified_name"])) + if not member_line(t, owner=owner[-1]): return [] name = declared_name(t, in_class=True) - owner = _bare(str(holder["qualified_name"])) - return [holder, *_named(by_path, lambda q: q[-2:] == [owner, name])] if name else [holder] + return [holder, *functions.named([*owner, name])] if name else [holder] name = declared_name(t, in_class=False) if holder is None else "" if not name: return [] stem = _stem(path) - return _named( - by_path, - lambda q: q[-1] == name, - lambda p: p == path or _stem(p) == stem or is_registration_caller(name), + registration = is_registration_caller(name) + return functions.named( + [name], lambda p: registration or p == path or _stem(p) == stem, whole=False ) -# A Python line that opens a scope: a class or function head, or a decorator. -_PY_HEAD = re.compile(r"\s*(?:class\s|def\s|async\s+def\s|@)") - - -def _named( - by_path: dict[str, list[dict[str, Any]]], - name_ok: Any, - path_ok: Any = None, -) -> list[dict[str, Any]]: - """The function rows whose qualified name (`::` parts, parameters dropped) `name_ok` - accepts, in files `path_ok` accepts, when they share one qualified name (overloads - are one subject of a claim), else none.""" - rows = [ - r - for p, rs in by_path.items() - if path_ok is None or path_ok(p) - for r in rs - if str(r.get("kind")) != "class" - and name_ok(str(r["qualified_name"]).split("(", 1)[0].strip().split("::")) - ] - return rows if len({str(r["qualified_name"]) for r in rows}) == 1 else [] +def _parts(qualified: str) -> list[str]: + """A qualified name's `::` parts, its parameters dropped.""" + return qualified.split("(", 1)[0].strip().split("::") + + +class _Functions: + """The function rows of the diff's files outside tests, by the last part of their + qualified name, built once for a diff: a prototype is placed on one of them.""" + + def __init__(self, definitions: list[dict[str, Any]]) -> None: + self.by_name: dict[str, list[dict[str, Any]]] = {} + for r in definitions: + if str(r.get("kind")) != "class" and not is_test_path(str(r["path"])): + self.by_name.setdefault(_parts(str(r["qualified_name"]))[-1], []).append(r) + + def named( + self, + parts: list[str], + path_ok: Callable[[str], bool] | None = None, + *, + whole: bool = True, + ) -> list[dict[str, Any]]: + """The rows whose qualified name is `parts` (with `whole`) or ends with its one + part, in files `path_ok` accepts, when they share one qualified name (overloads + are one subject of a claim), else none.""" + rows = [ + r + for r in self.by_name.get(parts[-1], []) + if (not whole or _parts(str(r["qualified_name"])) == parts) + and (path_ok is None or path_ok(str(r["path"]))) + ] + return rows if len({str(r["qualified_name"]) for r in rows}) == 1 else [] def _stem(path: str) -> str: diff --git a/tests/unit/test_code_diff_sides.py b/tests/unit/test_code_diff_sides.py index 561a18ebbf0..a1dbb74983c 100644 --- a/tests/unit/test_code_diff_sides.py +++ b/tests/unit/test_code_diff_sides.py @@ -843,6 +843,21 @@ def test_a_member_line_or_a_prototype_is_placed_on_what_it_declares( ("int area(const Widget & x);\n", "int area(const Widget & x);\nconst int limit = 4;\n"), ("#pragma once\n", "#pragma once\n#include \n"), ("int area(const Widget & x);\n", "int area(const Widget & x);\nint perimeter(int w);\n"), + # a constant built by a constructor, which reads as no prototype + ( + "int area(const Widget & x);\n", + 'int area(const Widget & x);\nstatic const std::regex pattern("^a+$");\n', + ), + # scope text after a member on one line, a base clause, a macro call, a raw + # string's opener and a quote no literal closes + (" int w = 0;\n", " int w = 0; using Base::resize;\n"), + (" int w = 0;\n", " int w = 0; private:\n"), + (" int w = 0;\n", " int w = 0; }; struct Next {\n"), + ("class Widget\n", "class Widget\n : public Base\n"), + (" int w = 0;\n", " int w = 0;\n FRIEND_TEST(WidgetTest, Resize);\n"), + (" int w = 0;\n", " int w = 0;\n check(w);\n"), + (" int w = 0;\n", ' int w = 0;\n const char * help = R"(\n'), + (" int w = 0;\n", ' int w = 0;\n std::string s = "a" "b;\n'), ], ) def test_a_line_that_shapes_a_scope_or_names_no_definition_stays_unmapped( @@ -875,10 +890,74 @@ def test_a_file_scope_prototype_is_placed_only_on_one_definition(tmp_path: Path) ) +def test_a_prototype_is_placed_on_the_function_of_its_class_outside_tests( + tmp_path: Path, +) -> None: + """A prototype in a class body is placed on the function whose qualified name is the + class's and its own, never on one of another class of that name or in a test file.""" + path = "src/ui/widget.h" + others = [ + *_rows("src/ui/other.cpp", "namespace other\n{\nvoid Widget::resize(int v)\n{\n}\n}\n"), + *_rows("tests/ui/widget.cpp", "namespace ui\n{\nvoid Widget::resize(int v)\n{\n}\n}\n"), + ] + assert {r["qualified_name"] for r in others} == {"other::Widget::resize", "ui::Widget::resize"} + changed = WIDGET_H.replace("resize(int w);", "resize(int w, int h);") + unmapped, placed = _place_header(tmp_path, path, WIDGET_H, changed, [*_widget_rows(), *others]) + assert (unmapped, placed) == (None, ["ui::Widget", "ui::Widget::resize"]) + + +def test_a_line_between_two_inline_methods_is_placed_on_their_class(tmp_path: Path) -> None: + """A member the diff adds between two methods defined in the class body sits below + one and above the other: the class holds both, so the line is placed on it.""" + path = "src/ui/widget.h" + inline = WIDGET_H.replace( + " int width() const;\n void resize(int w);\n", + " int width() const { return w; }\n void resize(int v) { w = v; }\n", + ) + added = inline.replace("{ return w; }\n", "{ return w; }\n int h = 0;\n") + unmapped, placed = _place_header(tmp_path, path, inline, added, _rows(path, inline)) + assert (unmapped, placed) == (None, ["ui::Widget"]) + + +def test_placing_many_prototypes_costs_time_linear_in_them() -> None: + """A diff that changes n prototypes of a class the diff's files define n functions + of: each prototype finds its function through one index of the names.""" + from tests.unit.code_fixtures import grows_linearly + + def run(n: int) -> None: + cls = { + "symbol_id": "c", + "path": "src/a.h", + "qualified_name": "A", + "kind": "class", + "start_line": 1, + "end_line": n + 2, + } + fns = [ + { + "symbol_id": f"f{i}", + "path": "src/a.cpp", + "qualified_name": f"A::f{i}", + "kind": "function", + "start_line": i + 1, + "end_line": i + 1, + } + for i in range(n) + ] + body = "".join(f"- int f{i}();\n+ long f{i}();\n" for i in range(n)) + diff = f"--- a/src/a.h\n+++ b/src/a.h\n@@ -1,{n + 2} +1,{n + 2} @@\n {{\n{body} }};\n" + _, _, changes = _parse_unified_diff_full(diff) + placement = place_lines([cls, *fns], changes, new_side={"src/a.h": []}) + assert not placement.unmapped and len(placement.rows) == n + 1 + + grows_linearly(run, 2_000, 8_000) + + def test_a_python_class_attribute_is_placed_on_the_class(tmp_path: Path) -> None: """A Python class body is one scope its indentation keeps: an attribute or docstring line outside every method is placed on the class, a module line on nothing, and a - `def` head whose function pairs with no row stays a change.""" + `def` head whose function pairs with no row, a compound statement's head (the line + under it is the class's) and a line that opens a string stay changes.""" path = "src/app/conf.py" before = 'class Conf:\n """Run settings."""\n retries = 3\n\n def run(self):\n return 1\n' for old, new, want in ( @@ -889,6 +968,12 @@ def test_a_python_class_attribute_is_placed_on_the_class(tmp_path: Path) -> None " retries = 3\n def stop(self): pass\n", ([(4, 4, "added")], []), ), + ( + " retries = 3\n", + " retries = 3\n if DEBUG:\n retries = 9\n", + ([(4, 4, "added")], ["src.app.conf::Conf"]), + ), + ('"""Run settings."""', '"""Run settings.', ([(2, 2, "added")], ["src.app.conf::Conf"])), # line 2 is blank, where an encoding cookie is read ("class Conf:", "LIMIT = 2\n\n\nclass Conf:", ([(1, 1, "added"), (2, 2, "added")], [])), ): diff --git a/tests/unit/test_code_review_brief_sections.py b/tests/unit/test_code_review_brief_sections.py index d1586735d9b..f8589d09e81 100644 --- a/tests/unit/test_code_review_brief_sections.py +++ b/tests/unit/test_code_review_brief_sections.py @@ -1551,11 +1551,9 @@ async def test_the_symbols_section_collapses_the_wiring_the_pr_adds_and_nothing_ "DB::FunctionGetMacro::executeImpl", "DB::FunctionGetMacro::useDefaultImplementationForConstants", "DB::FunctionFactory::isDeterministic", - "DB::FunctionGetMacro", "DB::FunctionGetMacro::getName", "DB::FunctionGetMacro::getName", "DB::FunctionGetMacro::getReturnTypeImpl", - "DB::FunctionGetSetting", "DB::FunctionGetSettingOrDefault::isDeterministic", "DB::create", "DB::registerStorageFoo", @@ -1563,7 +1561,7 @@ async def test_the_symbols_section_collapses_the_wiring_the_pr_adds_and_nothing_ assert [r["qualified_name"] for r in sym["rows"]] == kept assert not any("via" in r for r in sym["rows"]) assert sym["collapsed"] == {"registration": 2, "factory": 1, "constructor": 1, "one_line": 1} - assert sym["note"].startswith("14 touched functions and 5 collapsed;") + assert sym["note"].startswith("12 touched functions and 5 collapsed;") # the callers are read once, in both tiers, for the factories and constructors with # outside sites: the constructor's one site is in the parser's edges assert repo.asked == [["s-ctor", "s-ctor-ts"]] @@ -1583,11 +1581,10 @@ async def test_the_symbols_section_collapses_the_wiring_the_pr_adds_and_nothing_ history = [b["name"] for op, b in calls.calls if op == "code.symbol_history"] files = [_FACTORY, _SETTING, _SETTING, _MACRO, _MACRO, _MACRO] assert history == [f"{p}:{n}" for p, n in zip(files, first, strict=True)] - # a record is read per definition: the two files' registrations are two; the two classes - # whose member lines the PR adds are two more + # a record is read per definition: the two files' registrations are two assert (secs["tests"]["causes"], secs["history"]["causes"]) == ( - ["not_claimed:11"], - ["not_read:12"], + ["not_claimed:9"], + ["not_read:10"], ) # the files the PR adds hold lines outside every function (the fixture's lines 1-9 # of `getMacro.cpp`, its includes and namespace lines): those changes were checked by @@ -1614,22 +1611,20 @@ async def test_the_symbols_section_collapses_the_wiring_the_pr_adds_and_nothing_ assert payload["sections"]["symbols"]["failed"] == ["edges_for_symbols:RuntimeError"] assert "edges_for_symbols:RuntimeError" not in payload["sections"]["symbols"]["causes"] # call sites uncounted, or an open PR (its diff is its head's, which the index rows - # are not at; its added functions are the overlay's): nothing folds. The open PR adds - # its classes too, which the index does not hold, so their member lines touch none - for inp, repo, calls, n in ( - (_wiring_inputs(), _WiringRepo(counts_fail=True), _WiringCalls(), 19), + # are not at; its added functions are the overlay's): nothing folds + for inp, repo, calls in ( + (_wiring_inputs(), _WiringRepo(counts_fail=True), _WiringCalls()), ( dataclasses.replace(_wiring_inputs(), open=True), _WiringRepo(), _WiringCalls(overlay=True), - 17, ), ): payload = await review_brief_build.build_brief( inp, call=calls, repo=repo, tracker_rows=_tracker_not_bound, now=_fixed_now ) sym = payload["sections"]["symbols"] - assert "collapsed" not in sym and len(sym["rows"]) == n + assert "collapsed" not in sym and len(sym["rows"]) == 17 # A registration the PR adds to `getSetting.cpp` after line 68, behind a blank line @@ -1924,11 +1919,10 @@ async def __call__(self, op: str, body: dict[str, Any]) -> dict[str, Any]: @pytest.mark.parametrize( ("line", "rows"), [ - # a member, a changed default, a static constant, a call a macro may expand to a - # member: the class + # a member, a changed default, static constants: the class (" int step = 0;", ["DB::Shift"]), (" static constexpr int limit = 8;", ["DB::Shift"]), - (" check(table);", ["DB::Shift"]), + (' static constexpr auto name = "shift";', ["DB::Shift"]), # prototypes: of a function the index does not hold, and of `k`, which the # brief lists for its body too (" int other() const;", ["DB::Shift"]), @@ -2001,6 +1995,11 @@ async def test_a_member_line_of_a_class_body_is_claimed_on_the_class( _file_diff(_SHIFT, "@@ -33,0 +34 @@\n+ int k();\n"), # below a line a macro continues, a class body line is the macro's _file_diff(_SHIFT, "@@ -17 +28,2 @@\n #define STEP(x) \\\n+ int x;\n"), + # below a member, lines of the class body that declare no member: a macro call, + # which may expand to any member or none, and members spelled after other scope text + _file_diff(_SHIFT, "@@ -17 +28,2 @@\n int base = 1;\n+ check(table);\n"), + _file_diff(_SHIFT, "@@ -17 +28,2 @@\n int base = 1;\n+ int x; private:\n"), + _file_diff(_SHIFT, "@@ -17 +28,2 @@\n int base = 1;\n+ int a; }; struct N {\n"), # whole-line comments outside C++: one the compiler reads (a Go build constraint, # an export, a cgo preamble, a TypeScript reference), a shell one, and a Python one, # which may sit inside a module's string From 34bbe176665267d95498424385e7e151b33a15d8 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 6 Dec 2026 06:47:01 +0000 Subject: [PATCH 04/16] A Python decorator's argument line and a free prototype's same-named method are not placed A Python class-body line is placed only when it is an attribute or a docstring line below a line that leaves no bracket open, so a line inside a multi-line decorator stays the method's change. A file-scope prototype no longer matches a method of a class the diff's files hold. A C++ line holding virtual, override, final or a template head's words stays unmapped. The Python rule moves out of the C++ module. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- docs/features/code-index/history-and-prs.md | 48 +++++---- server/code/app/symbol/cpp_members.py | 23 ++--- server/code/app/symbol/diff.py | 99 ++++++++++++++----- tests/unit/test_code_diff_sides.py | 33 +++++++ tests/unit/test_code_review_brief_sections.py | 7 ++ 5 files changed, 148 insertions(+), 62 deletions(-) diff --git a/docs/features/code-index/history-and-prs.md b/docs/features/code-index/history-and-prs.md index bb2a75917ed..19a14ba30c3 100644 --- a/docs/features/code-index/history-and-prs.md +++ b/docs/features/code-index/history-and-prs.md @@ -395,28 +395,36 @@ uncovered one answers `gaps`. index. In C++ that is a member line, one shaped as a declaration: a member, a static constant, a method prototype or one of its parameter lines, a constructor. Any other line stays a change: a brace, a class head or its base clause, an access specifier, a - `using` or `friend` declaration, a namespace or preprocessor line, a macro call, a - statement (`return x;`, a line of a method the parser did not read), a line that - holds one of those words after a member, `/*`, `*/`, a raw string's opener or a quote - no literal closes. They shape a scope, may expand to anything, or belong to a function - nobody parsed. In Python a line of a class body outside its methods (an attribute, a - docstring) is placed, but a `class` or `def` head, a decorator, a compound - statement's head (`if`, `try`, `for`, `with` and the rest) and a line with an odd - count of `"""` or `'''`, which opens or closes a string around lines the diff leaves. + `using` or `friend` declaration, a namespace or preprocessor line, a template head's + lines, a macro call, a statement (`return x;`), a line holding `virtual`, `override` + or `final` (they change which function a call through a base reaches, an override no + claim on the class covers), a line that holds one of those words after a member, + `/*`, `*/`, a raw string's opener or a quote no literal closes. In Python an + attribute (`retries = 3`, `name: str`) or a docstring line of a class body outside + its methods is placed. Any other line stays a change: a `class` or `def` head, a + decorator, a compound statement's head, a `return` line, a line with an odd count of + `"""` or `'''` (it opens or closes a string around lines the diff leaves), and a + line below one that leaves a bracket open or ends with `,`, such as a decorator's + argument, which belongs to the method below it. - A C++ prototype is placed also on the function it declares, when the diff's files outside tests hold one definition of it: in a class body the function whose - qualified name is the class's and the prototype's, at file scope the function of its - name in the same file or a file of the same stem (`widget.h` and `widget.cpp`), or a - registration function by the index's registration rule (`registerWidgets`), which is - often declared beside the call that runs it. Two definitions of the name under - different qualified names leave it a change, and so does a file-scope line whose - parentheses start with a literal (`static const std::regex re("a+");`), a constant - built by a constructor. A registration statement inside a registration function's - body is that function's line already. -- The rules read the changed line, the line above it and the index's rows. A line of a - method the parser did not read as one (a head spelled with a macro it cannot expand) - sits in the class body by the rows, so a declaration in its body reads as a member - line and is placed on the class that holds the method. + qualified name is the class's and the prototype's; at file scope a free function of + its name (not a method of a class the diff's files hold) in the same file or a file + of the same stem (`widget.h` and `widget.cpp`), or a registration function by the + index's registration rule (`registerWidgets`), which is often declared beside the + call that runs it. Two definitions of the name under different qualified names leave + it a change, and so does a file-scope line whose parentheses start with a literal + (`static const std::regex re("a+");`), a constant built by a constructor. A + registration statement inside a registration function's body is that function's + line already. +- The rules read the changed line, the line above it and the index's rows, and they + are as good as those rows. A line of a method the parser did not read as one (a head + spelled with a macro it cannot expand) sits in the class body by the rows, so a + declaration in its body (`size_t n = rows.size();`) reads as a member line and is + placed on the class that holds the method: a claim on the class then decides it. The + index serves a C++ `struct` as no definition the brief reads, so a struct's body is + file scope to these rules: its members stay changes, a prototype in it is placed + only as a file-scope one is, and a struct's method counts as a free function there. - No line is placed that a macro or a statement continues (the line above it ends with `\` or `??/`), that starts a run the hunk shows no line above (a diff with no context), or that sits in a function the new side pairs with no row, or on a side nobody read. diff --git a/server/code/app/symbol/cpp_members.py b/server/code/app/symbol/cpp_members.py index d6c3544fae2..0ee1a17291d 100644 --- a/server/code/app/symbol/cpp_members.py +++ b/server/code/app/symbol/cpp_members.py @@ -1,5 +1,5 @@ -"""What a changed line outside every function declares, read off its text: a member of the -class whose body holds it, and in C++ the function a prototype declares. +"""What a changed C++ line outside every function declares, read off its text: a member of +the class whose body holds it, and the function a prototype declares. `diff.place_lines` places such a line on the class, and a prototype on the function the index holds too, so a claim about that definition decides the line. Only a line shaped @@ -30,13 +30,10 @@ class whose body holds it, and in C++ the function a prototype declares. _CPP_SCOPE_WORDS = re.compile( r"\b(?:using|friend|namespace|public|protected|private|class|struct|union|enum" r"|template|typedef|return|throw|co_return|co_yield|co_await|if|else|for|while|do" - r"|switch|case|default|break|continue|goto|try|catch|operator)\b" -) -# A Python line of a class body that shapes a scope: a class or function head, a -# decorator, or a compound statement, which decides which of the lines below it exist. -_PY_SCOPE = re.compile( - r"\s*(?:@|(?:class|def|if|elif|else|try|except|finally|for|while|with|match|case" - r"|async)\b)" + r"|switch|case|default|break|continue|goto|try|catch|operator" + # which function a call through a base reaches, and a template head's lines, which + # belong to the template below them + r"|virtual|override|final|typename|requires|concept)\b" ) # The head of a function declaration: the declarator's name and the `(` after it, with # the words before it (the return type and specifiers) spelled as names, `::`, `<>`, `*`, @@ -57,22 +54,18 @@ class whose body holds it, and in C++ the function a prototype declares. _LITERAL_START = (*"\"'0123456789-+.{", 'R"', 'u8"', 'L"') -def member_line(text: str, *, python: bool = False, owner: str = "") -> bool: +def member_line(text: str, *, owner: str = "") -> bool: """Whether a changed line of a class body, outside every function, declares a member of the class. In C++ it is shaped as a declaration (`_DECLARATION`: `int width = 0;`, `bool empty() const;`, a parameter line of a prototype spread over lines) or as the head of a special member of class `owner` (`Widget(int w);`); outside its string literals it holds no word that shapes a scope or opens a statement (`_CPP_SCOPE_WORDS`), no `#`, `/*` or `*/`, no raw string (it may span lines) and no - quote a literal does not close, and no brace closes what the line did not open. In - Python it is any line but one that shapes a scope (`_PY_SCOPE`) or holds an odd count - of three quotes, which opens or closes a string around unchanged lines. In either, a + quote a literal does not close, and no brace closes what the line did not open. A line ending with `\\` or `??/` continues onto the next one and is no member line.""" s = text.rstrip() if s.endswith(("\\", "??/")): return False - if python: - return _PY_SCOPE.match(s) is None and not (s.count('"""') % 2 or s.count("'''") % 2) if _RAW_STRING.search(s): return False s = _STRING.sub('""', s) diff --git a/server/code/app/symbol/diff.py b/server/code/app/symbol/diff.py index fa3733c92ea..78ca4fd2aa0 100644 --- a/server/code/app/symbol/diff.py +++ b/server/code/app/symbol/diff.py @@ -798,9 +798,9 @@ class body touches the class. A test file's lines are not counted: its functions text = _removed_lines(hunks) added = dict(_added_lines(hunks)) keys = sorted(text) - cont_old, unseen_old = _run_context(hunks, removed=True) + cont_old, unseen_old, above_old = _run_context(hunks, removed=True) inert_old = inert_lines(text, p, continued=cont_old, unseen=unseen_old) - cont_new, unseen_new = _run_context(hunks, removed=False) + cont_new, unseen_new, above_new = _run_context(hunks, removed=False) inert_new = inert_lines(added, p, continued=cont_new, unseen=unseen_new) missed: list[tuple[int, int, Side]] = [] by_lines: list[Hunk] = [] @@ -838,13 +838,13 @@ class body touches the class. A test file's lines are not counted: its functions for m in _added(hunk, seeds, inert_new) ] context = { - "removed": (text, cont_old, unseen_old), - "added": (added, cont_new, unseen_new), + "removed": (text, cont_old, unseen_old, above_old), + "added": (added, cont_new, unseen_new, above_new), } for m, holder, placeable in loose: - lines_of, cont, unseen = context.get(m[2], ({}, frozenset(), frozenset())) + lines_of, cont, unseen, above = context.get(m[2], ({}, frozenset(), frozenset(), {})) rows = ( - _place_member(m[0], holder, p, functions, lines_of, cont, unseen) + _place_member(m[0], holder, p, functions, (lines_of, above), cont, unseen) if placeable and m[0] == m[1] else [] ) @@ -862,12 +862,13 @@ def _place_member( holder: dict[str, Any] | None, path: str, functions: _Functions, - lines: dict[int, str], + side: tuple[dict[int, str], dict[int, str]], continued: frozenset[int], unseen: frozenset[int], ) -> list[dict[str, Any]]: - """The definition rows changed line `n` of one side (`lines`) outside every function - is placed on, none when it stays a change in no definition. A line a macro or a + """The definition rows changed line `n` of one side outside every function is placed + on, none when it stays a change in no definition. `side` is the side's changed lines + and, by the first line of each run, the context line above the run. A line a macro or a statement continues (`_CONTINUES`: the line above it on its side, or the context line above its run, `continued`), or that starts a run the hunk shows no line above (`unseen`), is never placed: it may be a macro's body or another line's end. @@ -879,21 +880,24 @@ class (`holder`), and a prototype there also on the function it declares placed on the function of its name in the diff's files that sits in the same file or one of the same stem (`widget.h` and `widget.cpp`), or that is a registration function (`is_registration_caller`, often declared beside the call that runs it): - only when they name one definition. A test file's definitions are never one: a test - does not define what the code under test declares. In Python a class body is one - scope its indentation keeps, and a line of it outside every method (an attribute, a - docstring) is placed on the class, but not one that shapes a scope or may open a - string (`cpp_members.member_line`); a module line is placed on nothing, as a shell - line is: a shell script has no class and no prototype.""" + only when they name one definition, and not a method of a class the diff's files + hold: a prototype outside a class declares no method. A test file's definitions are + never one: a test does not define what the code under test declares. In Python a + class body is one scope its indentation keeps, and an attribute or docstring line of + it outside every method is placed on the class (`_python_member_line`); a module line + is placed on nothing, as a shell line is: a shell script has no class and no + prototype.""" lang = lang_for_path(path) + lines, above = side t = lines.get(n) if t is None or n in continued or n in unseen or lang not in ("cpp", "python"): return [] - if lines.get(n - 1, "").rstrip().endswith(_CONTINUES): + prev = lines.get(n - 1, above.get(n, "")) + if prev.rstrip().endswith(_CONTINUES): return [] is_class = holder is not None and str(holder.get("kind")) == "class" if lang == "python": - return [holder] if holder is not None and is_class and member_line(t, python=True) else [] + return [holder] if holder is not None and is_class and _python_member_line(t, prev) else [] if holder is not None and is_class: owner = _parts(str(holder["qualified_name"])) if not member_line(t, owner=owner[-1]): @@ -910,6 +914,34 @@ class (`holder`), and a prototype there also on the function it declares ) +# A Python attribute (`retries = 3`, `name: str`, `limit: int = 4`), whose name is no +# keyword (`try: # why`, `else: x = 1`), and a line that starts with a string, as a +# docstring does. +_PY_ATTRIBUTE = re.compile( + r"\s*(?!(?:if|elif|else|try|except|finally|for|while|with|match|case|async|def|class" + r"|return|yield|raise|lambda|del|assert|global|nonlocal|pass|import|from|await)\b)" + r"[A-Za-z_]\w*\s*(?::[^=]|=(?!=))" +) +_PY_STRING = re.compile(r"\s*[rRbBuUfF]{0,2}[\"']") + + +def _python_member_line(text: str, prev: str) -> bool: + """Whether a changed line of a Python class body, outside every method, is an + attribute or a docstring line of the class: shaped as one (`_PY_ATTRIBUTE`, + `_PY_STRING`), with an even count of each triple quote (an odd one opens or closes a + string around unchanged lines), below a line (`prev`) that leaves no bracket open + and does not end with `,`: a line inside a decorator's or a call's arguments is the + definition's below it, or an expression's, not a member. A `def`, `class` or + compound statement head, a decorator and a `return` line are not shaped as either.""" + if text.count('"""') % 2 or text.count("'''") % 2: + return False + if _PY_ATTRIBUTE.match(text) is None and _PY_STRING.match(text) is None: + return False + p = prev.split("#", 1)[0].rstrip() + opened = sum(p.count(c) for c in "([{") - sum(p.count(c) for c in ")]}") + return opened <= 0 and not p.endswith((",", "(", "[", "{")) + + def _parts(qualified: str) -> list[str]: """A qualified name's `::` parts, its parameters dropped.""" return qualified.split("(", 1)[0].strip().split("::") @@ -921,6 +953,9 @@ class _Functions: def __init__(self, definitions: list[dict[str, Any]]) -> None: self.by_name: dict[str, list[dict[str, Any]]] = {} + self.classes = { + str(r["qualified_name"]) for r in definitions if str(r.get("kind")) == "class" + } for r in definitions: if str(r.get("kind")) != "class" and not is_test_path(str(r["path"])): self.by_name.setdefault(_parts(str(r["qualified_name"]))[-1], []).append(r) @@ -932,13 +967,18 @@ def named( *, whole: bool = True, ) -> list[dict[str, Any]]: - """The rows whose qualified name is `parts` (with `whole`) or ends with its one - part, in files `path_ok` accepts, when they share one qualified name (overloads - are one subject of a claim), else none.""" + """The rows whose qualified name is `parts` (with `whole`), or else ends with its + one part and names no class of the definitions above it (a free function's), in + files `path_ok` accepts, when they share one qualified name (overloads are one + subject of a claim), else none.""" rows = [ r for r in self.by_name.get(parts[-1], []) - if (not whole or _parts(str(r["qualified_name"])) == parts) + if ( + _parts(str(r["qualified_name"])) == parts + if whole + else "::".join(_parts(str(r["qualified_name"]))[:-1]) not in self.classes + ) and (path_ok is None or path_ok(str(r["path"]))) ] return rows if len({str(r["qualified_name"]) for r in rows}) == 1 else [] @@ -949,12 +989,15 @@ def _stem(path: str) -> str: return path.rsplit("/", 1)[-1].split(".", 1)[0] -def _run_context(hunks: list[Hunk], *, removed: bool) -> tuple[frozenset[int], frozenset[int]]: - """(continued, unseen): the first line of each run of `hunks` on one side whose line - above, as the hunk shows it, ends with `\\` or `??/` (`_CONTINUES`), and of each run, +def _run_context( + hunks: list[Hunk], *, removed: bool +) -> tuple[frozenset[int], frozenset[int], dict[int, str]]: + """(continued, unseen, above): the first line of each run of `hunks` on one side whose + line above, as the hunk shows it, ends with `\\` or `??/` (`_CONTINUES`), of each run, other than one at the top of the file, the hunk shows no line above (a diff with no - context).""" + context), and by the first line of each run the line above it the hunk shows.""" continued, unseen = set(), set() + above: dict[int, str] = {} for h in hunks: for b in h.blocks: first = b.after + 1 if removed else b.new @@ -962,9 +1005,11 @@ def _run_context(hunks: list[Hunk], *, removed: bool) -> tuple[frozenset[int], f continue if b.above is None: unseen.add(first) - elif b.above.rstrip().endswith(_CONTINUES): + continue + above[first] = b.above + if b.above.rstrip().endswith(_CONTINUES): continued.add(first) - return frozenset(continued), frozenset(unseen) + return frozenset(continued), frozenset(unseen), above def _changed( diff --git a/tests/unit/test_code_diff_sides.py b/tests/unit/test_code_diff_sides.py index a1dbb74983c..01c2a4bbf69 100644 --- a/tests/unit/test_code_diff_sides.py +++ b/tests/unit/test_code_diff_sides.py @@ -856,6 +856,13 @@ def test_a_member_line_or_a_prototype_is_placed_on_what_it_declares( ("class Widget\n", "class Widget\n : public Base\n"), (" int w = 0;\n", " int w = 0;\n FRIEND_TEST(WidgetTest, Resize);\n"), (" int w = 0;\n", " int w = 0;\n check(w);\n"), + # a prototype made virtual, which changes which function a call through a base + # reaches, and a template head's parameter lines + (" void resize(int w);\n", " virtual void resize(int w);\n"), + ( + " int width() const;\n", + " template <\n typename T,\n typename U = int>\n int width() const;\n", + ), (" int w = 0;\n", ' int w = 0;\n const char * help = R"(\n'), (" int w = 0;\n", ' int w = 0;\n std::string s = "a" "b;\n'), ], @@ -906,6 +913,32 @@ def test_a_prototype_is_placed_on_the_function_of_its_class_outside_tests( assert (unmapped, placed) == (None, ["ui::Widget", "ui::Widget::resize"]) +def test_a_file_scope_prototype_is_not_placed_on_a_method(tmp_path: Path) -> None: + """A free prototype whose only definition of its name in the diff's files is a method + of a class they hold declares that method no more than any other: it stays a change.""" + path = "src/ui/widget.h" + method = _rows("src/ui/widget.cpp", "namespace ui\n{\nvoid Widget::draw(int s)\n{\n}\n}\n") + rows = [*_rows(path, WIDGET_H), *method] + before = WIDGET_H.replace("int area(", "void draw(int scale = 1);\nint area(") + after = before.replace("scale = 1", "scale = 2") + unmapped, placed = _place_header(tmp_path, path, before, after, [*rows, *_rows(path, before)]) + assert (unmapped, placed) == ([(16, 16, "removed"), (16, 16, "added")], []) + + +def test_a_line_inside_a_python_decorator_stays_unmapped(tmp_path: Path) -> None: + """A line of a decorator's arguments spread over lines sits above the method's `def`, + where the method's row starts, so the rows put it in the class body: it is the + method's, not a member of the class, and stays a change.""" + path = "src/app/conf.py" + before = ( + 'class Conf:\n retries = 3\n\n @validator(\n "name",\n' + ' mode="before",\n )\n def check(cls, v):\n return v\n' + ) + after = before.replace('"before"', '"after"') + unmapped, placed = _place_header(tmp_path, path, before, after, _rows(path, before)) + assert (unmapped, placed) == ([(6, 6, "removed"), (6, 6, "added")], []) + + def test_a_line_between_two_inline_methods_is_placed_on_their_class(tmp_path: Path) -> None: """A member the diff adds between two methods defined in the class body sits below one and above the other: the class holds both, so the line is placed on it.""" diff --git a/tests/unit/test_code_review_brief_sections.py b/tests/unit/test_code_review_brief_sections.py index f8589d09e81..c3aff1598bf 100644 --- a/tests/unit/test_code_review_brief_sections.py +++ b/tests/unit/test_code_review_brief_sections.py @@ -1998,6 +1998,13 @@ async def test_a_member_line_of_a_class_body_is_claimed_on_the_class( # below a member, lines of the class body that declare no member: a macro call, # which may expand to any member or none, and members spelled after other scope text _file_diff(_SHIFT, "@@ -17 +28,2 @@\n int base = 1;\n+ check(table);\n"), + # a prototype made virtual below a member: calls through a base reach the + # overrides, which no claim on the class covers + _file_diff( + _SHIFT, + "@@ -17,2 +28,2 @@\n int base = 1;\n- int k(int step) const;\n" + "+ virtual int k(int step) const;\n", + ), _file_diff(_SHIFT, "@@ -17 +28,2 @@\n int base = 1;\n+ int x; private:\n"), _file_diff(_SHIFT, "@@ -17 +28,2 @@\n int base = 1;\n+ int a; }; struct N {\n"), # whole-line comments outside C++: one the compiler reads (a Go build constraint, From 9cfdd9ea30d9d8c594707f10117e3e9822325470 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 6 Dec 2026 07:03:57 +0000 Subject: [PATCH 05/16] A class-body line is placed only when it is a whole declaration on its own line A C++ member line must end with ';' and close every bracket it opens, so a parameter line of a multi-line (possibly virtual) prototype or a template head stays a change. A Python attribute line must leave no bracket open and sit below a line of code that leaves none open; below a blank or comment line it stays a change. code.test_gate's rows from code.impact are again exactly the gate's own: placed prototypes seed the walk and are claimed, and no longer reach impacted_tests. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- docs/features/code-index/history-and-prs.md | 29 +++++---- server/code/app/symbol/cpp_members.py | 59 ++++++++++--------- server/code/app/symbol/diff.py | 52 ++++++++++------ server/code/domain/index/epistemic.py | 7 ++- tests/unit/test_code_diff_sides.py | 34 +++++++---- tests/unit/test_code_review_brief_sections.py | 6 +- 6 files changed, 108 insertions(+), 79 deletions(-) diff --git a/docs/features/code-index/history-and-prs.md b/docs/features/code-index/history-and-prs.md index 19a14ba30c3..1853632acc9 100644 --- a/docs/features/code-index/history-and-prs.md +++ b/docs/features/code-index/history-and-prs.md @@ -392,20 +392,23 @@ uncovered one answers `gaps`. - A line of a class body is placed on the class, on the side that holds it: a line the diff removes on the index's class, a line it adds that no function of the new side holds on the class that holds the run's lines and the line on each side of it in the - index. In C++ that is a member line, one shaped as a declaration: a member, a static - constant, a method prototype or one of its parameter lines, a constructor. Any other - line stays a change: a brace, a class head or its base clause, an access specifier, a - `using` or `friend` declaration, a namespace or preprocessor line, a template head's - lines, a macro call, a statement (`return x;`), a line holding `virtual`, `override` - or `final` (they change which function a call through a base reaches, an override no - claim on the class covers), a line that holds one of those words after a member, - `/*`, `*/`, a raw string's opener or a quote no literal closes. In Python an + index. In C++ that is a member line, a declaration whole on one line: a member, a + static constant, a method prototype or a constructor, ending with `;`, with every + bracket it opens closed on the line and none closed it did not open. Any other line + stays a change: a brace, a class head or its base clause, an access specifier, a + `using` or `friend` declaration, a namespace or preprocessor line, a line of a + prototype or a template head spread over lines (the head they continue may be + `virtual`), a macro call, a statement (`return x;`), a line holding `virtual`, + `override` or `final` (they change which function a call through a base reaches, an + override no claim on the class covers), a line that holds one of those words after a + member, `/*`, `*/`, a raw string's opener or a quote no literal closes. In Python an attribute (`retries = 3`, `name: str`) or a docstring line of a class body outside - its methods is placed. Any other line stays a change: a `class` or `def` head, a - decorator, a compound statement's head, a `return` line, a line with an odd count of - `"""` or `'''` (it opens or closes a string around lines the diff leaves), and a - line below one that leaves a bracket open or ends with `,`, such as a decorator's - argument, which belongs to the method below it. + its methods is placed when it leaves no bracket open and the line above it is code + that leaves none open either. Any other line stays a change: a `class` or `def` head, + a decorator, a compound statement's head, a `return` line, a line with an odd count + of `"""` or `'''` (it opens or closes a string around lines the diff leaves), a + decorator's argument, which belongs to the method below it, and a line below a blank + or comment line, where the brackets open above are not known. - A C++ prototype is placed also on the function it declares, when the diff's files outside tests hold one definition of it: in a class body the function whose qualified name is the class's and the prototype's; at file scope a free function of diff --git a/server/code/app/symbol/cpp_members.py b/server/code/app/symbol/cpp_members.py index 0ee1a17291d..06fd8d38ef5 100644 --- a/server/code/app/symbol/cpp_members.py +++ b/server/code/app/symbol/cpp_members.py @@ -17,11 +17,8 @@ # A C++ member declaration: one word or more of its type and specifiers (names, `::`, # `<>`, `,`, `*`, `&`, `[]`), then its declarator's name, then what may follow a name in -# a declaration (`;`, `=`, `(`, `{`, `[`, `,`, `)` closing a parameter list, `:` of a -# bit-field, or the line's end). -_DECLARATION = re.compile( - r"\s*(?:[A-Za-z_][\w:<>,*&\[\]]*[\s*&]+)+~?[A-Za-z_]\w*\s*(?:[;=({\[,:)]|$)" -) +# a declaration (`;`, `=`, `(`, `{`, `[`, `,`, or `:` of a bit-field). +_DECLARATION = re.compile(r"\s*(?:[A-Za-z_][\w:<>,*&\[\]]*[\s*&]+)+~?[A-Za-z_]\w*\s*[;=({\[,:]") # A special member's head, which names no type: `explicit Widget(int w);`, `~Widget();`. _SPECIAL = r"\s*(?:(?:explicit|constexpr|inline|virtual)\s+)*~?{name}\s*\(" # What ends a prototype without a body: `= default;`, `= delete;`, `= 0;`. @@ -55,14 +52,14 @@ def member_line(text: str, *, owner: str = "") -> bool: - """Whether a changed line of a class body, outside every function, declares a member - of the class. In C++ it is shaped as a declaration (`_DECLARATION`: `int width = 0;`, - `bool empty() const;`, a parameter line of a prototype spread over lines) or as the - head of a special member of class `owner` (`Widget(int w);`); outside its string - literals it holds no word that shapes a scope or opens a statement - (`_CPP_SCOPE_WORDS`), no `#`, `/*` or `*/`, no raw string (it may span lines) and no - quote a literal does not close, and no brace closes what the line did not open. A - line ending with `\\` or `??/` continues onto the next one and is no member line.""" + """Whether a changed C++ line of a class body, outside every function, declares a + member of the class. It is shaped as a declaration (`_DECLARATION`: `int width = 0;`, + `bool empty() const;`) or as the head of a special member of class `owner` + (`Widget(int w);`), whole on the line: it ends with `;`, and every bracket it opens + it closes and none it did not open, so it continues no prototype or template head + above it. Outside its string literals it holds no word that shapes a scope or opens + a statement (`_CPP_SCOPE_WORDS`), no `#`, `/*` or `*/`, no raw string (it may span + lines) and no quote a literal does not close.""" s = text.rstrip() if s.endswith(("\\", "??/")): return False @@ -75,23 +72,27 @@ def member_line(text: str, *, owner: str = "") -> bool: special = owner != "" and re.match(_SPECIAL.format(name=re.escape(owner)), code) if not (special or _DECLARATION.match(code)) or _CPP_SCOPE_WORDS.search(code): return False - depth = 0 - for c in code: - depth += {"{": 1, "}": -1}.get(c, 0) - if depth < 0: + if not code.rstrip().endswith(";"): + return False + for opens, closes in ("()", "[]", "{}", "<>"): + depth = 0 + for c in code.replace("->", ""): + depth += 1 if c == opens else -1 if c == closes else 0 + if depth < 0: + return False + if depth: return False - return depth == 0 + return True def declared_name(text: str, *, in_class: bool) -> str: """The name a C++ line declares as a function, '' when it declares none: a prototype on one line (`bool isEmpty(const Rows & rows) const;`, `static T f(X x);`), and in a - class body also the first line of one the next lines continue (`void setRange(`) and - a constructor, which names no type. Outside a class the line must name a return type, - and what follows the `(` must not start with a literal, which makes the line a - constant built by a constructor (`static const std::regex re("a+");`). A name spelled - in capitals is a macro (`DECLARE(...)`), and one after a word that opens a statement - (`return f(x);`) is a call.""" + class body also a constructor, which names no type. Outside a class the line must + name a return type, and what follows the `(` must not start with a literal, which + makes the line a constant built by a constructor (`static const std::regex + re("a+");`). A name spelled in capitals is a macro (`DECLARE(...)`), and one after a + word that opens a statement (`return f(x);`) is a call.""" m = _HEAD.match(text) if m is None: return "" @@ -100,8 +101,8 @@ class body also the first line of one the next lines continue (`void setRange(`) return "" if "{" in rest: return "" - if rest.endswith(";"): - if not in_class and (not words or rest.lstrip().startswith(_LITERAL_START)): - return "" - return name - return name if in_class and (rest == "" or rest.endswith(",")) else "" + if not rest.endswith(";"): + return "" + if not in_class and (not words or rest.lstrip().startswith(_LITERAL_START)): + return "" + return name diff --git a/server/code/app/symbol/diff.py b/server/code/app/symbol/diff.py index 78ca4fd2aa0..6139aeae513 100644 --- a/server/code/app/symbol/diff.py +++ b/server/code/app/symbol/diff.py @@ -714,25 +714,26 @@ def touched_by_diff( ) -> tuple[list[dict[str, Any]], list[dict[str, Any]], bool]: """(the definitions a diff touches, which seed code.impact's walk and are the subjects of its claims; the ones code.test_gate reads, every class a changed line of a body - sits in included; whether a changed line is placed on no definition). A function is - touched by a line it holds (`_touched_rows_for_diff`), a class or a function by a - member line or a C++ prototype placed on it (`place_lines`); a class that holds only - lines that stay changes in no definition is the test gate's alone.""" - rows, _, _ = _touched_rows_for_diff(definitions, changes, new_side=new_side) + sits in included, as code.test_gate reads them itself; whether a changed line is + placed on no definition). A function is touched by a line it holds + (`_touched_rows_for_diff`), a class or a function by a member line or a C++ + prototype placed on it (`place_lines`); a class that holds only lines that stay + changes in no definition is the test gate's alone.""" + gate, _, _ = _touched_rows_for_diff(definitions, changes, new_side=new_side) placement = place_lines(definitions, changes, new_side=new_side) - held = {(str(r["path"]), str(r["symbol_id"])) for r in rows} - rows += [ - {**r, "via": "hunk", "tier_ids": list(r.get("tier_ids") or [r["symbol_id"]])} - for r in placement.rows - if (str(r["path"]), str(r["symbol_id"])) not in held - ] placed = {(str(r["path"]), str(r["symbol_id"])) for r in placement.rows} seeds = [ r - for r in rows + for r in gate if str(r.get("kind")) != "class" or (str(r["path"]), str(r["symbol_id"])) in placed ] - return seeds, rows, bool(placement.unmapped) + held = {(str(r["path"]), str(r["symbol_id"])) for r in gate} + seeds += [ + {**r, "via": "hunk", "tier_ids": list(r.get("tier_ids") or [r["symbol_id"]])} + for r in placement.rows + if (str(r["path"]), str(r["symbol_id"])) not in held + ] + return seeds, gate, bool(placement.unmapped) class Placement(NamedTuple): @@ -929,17 +930,30 @@ def _python_member_line(text: str, prev: str) -> bool: """Whether a changed line of a Python class body, outside every method, is an attribute or a docstring line of the class: shaped as one (`_PY_ATTRIBUTE`, `_PY_STRING`), with an even count of each triple quote (an odd one opens or closes a - string around unchanged lines), below a line (`prev`) that leaves no bracket open - and does not end with `,`: a line inside a decorator's or a call's arguments is the - definition's below it, or an expression's, not a member. A `def`, `class` or - compound statement head, a decorator and a `return` line are not shaped as either.""" + string around unchanged lines), that leaves no bracket open or closes one it did not + open and does not end with `,`, below a line (`prev`) of code that does neither: a + line inside a decorator's or a call's arguments is the definition's below it, or an + expression's, not a member. Below a blank or comment line the brackets open above + it are not known, so no line there is placed. A `def`, `class` or compound statement + head, a decorator and a `return` line are not shaped as either.""" if text.count('"""') % 2 or text.count("'''") % 2: return False if _PY_ATTRIBUTE.match(text) is None and _PY_STRING.match(text) is None: return False p = prev.split("#", 1)[0].rstrip() - opened = sum(p.count(c) for c in "([{") - sum(p.count(c) for c in ")]}") - return opened <= 0 and not p.endswith((",", "(", "[", "{")) + return p != "" and _closed(text) and _closed(p) + + +def _closed(line: str) -> bool: + """Whether a Python line, its comment dropped, leaves no bracket open, closes none it + did not open and does not end with `,`, which continues a bracketed list.""" + code = line.split("#", 1)[0].rstrip() + depth = 0 + for c in code: + depth += {"(": 1, "[": 1, "{": 1, ")": -1, "]": -1, "}": -1}.get(c, 0) + if depth < 0: + return False + return depth == 0 and not code.endswith(",") def _parts(qualified: str) -> list[str]: diff --git a/server/code/domain/index/epistemic.py b/server/code/domain/index/epistemic.py index d154ff4671d..5f1aefa62d8 100644 --- a/server/code/domain/index/epistemic.py +++ b/server/code/domain/index/epistemic.py @@ -59,9 +59,10 @@ # definition the index holds (module-level code, text added above a definition, a file # with no definition or one the index does not hold), so no definition answers for it. # Each op counts its own: code.impact places a line the diff adds on the diff's new side, -# and a C++ member line of a class body or a prototype on the class and the function it -# declares, and counts any other line of a class body outside its methods too -# (`symbol.diff.place_lines`), where code.test_gate's line touches the class. +# a C++ member line of a class body or a Python attribute or docstring line of one on the +# class, a C++ prototype also on the function it declares, and counts any other line of +# a class body outside its methods too (`symbol.diff.place_lines`), where +# code.test_gate's line touches the class. CAUSE_UNMAPPED = "unmapped_changes" # code.impact's diff shape. The new side of a changed source file was asked for (an open # PR's overlay, `new_side_sha`) and not read: the lines the diff adds there are placed on diff --git a/tests/unit/test_code_diff_sides.py b/tests/unit/test_code_diff_sides.py index 01c2a4bbf69..787e3b81a73 100644 --- a/tests/unit/test_code_diff_sides.py +++ b/tests/unit/test_code_diff_sides.py @@ -791,17 +791,12 @@ def _place_header( (" int w = 0;\n", " int w = 0;\n int h = 0;\n", ["ui::Widget"]), (" int w = 0;\n", " int w = 1;\n", ["ui::Widget"]), (" int w = 0;\n", " int w = 0;\n bool empty() const;\n", ["ui::Widget"]), - # a prototype of a function the index holds, and one spread over two lines + # a prototype of a function the index holds ( " void resize(int w);\n", " void resize(int w, int h);\n", ["ui::Widget", "ui::Widget::resize"], ), - ( - " void resize(int w);\n", - " void resize(\n int w);\n", - ["ui::Widget", "ui::Widget::resize"], - ), # a prototype at file scope, of the function the file of the same stem defines ( "int area(const Widget & x);\n", @@ -857,8 +852,18 @@ def test_a_member_line_or_a_prototype_is_placed_on_what_it_declares( (" int w = 0;\n", " int w = 0;\n FRIEND_TEST(WidgetTest, Resize);\n"), (" int w = 0;\n", " int w = 0;\n check(w);\n"), # a prototype made virtual, which changes which function a call through a base - # reaches, and a template head's parameter lines + # reaches, the lines of a prototype spread over lines (its head may be virtual), + # a template head's parameter lines, a non-type one among them (" void resize(int w);\n", " virtual void resize(int w);\n"), + (" void resize(int w);\n", " void resize(\n int w);\n"), + ( + " void resize(int w);\n", + " virtual void resize(\n // in pixels\n int w,\n int h) = 0;\n", + ), + ( + " int width() const;\n", + " template \n int width() const;\n", + ), ( " int width() const;\n", " template <\n typename T,\n typename U = int>\n int width() const;\n", @@ -881,8 +886,7 @@ def test_a_line_that_shapes_a_scope_or_names_no_definition_stays_unmapped( def test_a_file_scope_prototype_is_placed_only_on_one_definition(tmp_path: Path) -> None: """A prototype at file scope whose name two definitions of the diff's files share under different qualified names (in two files of its stem) is ambiguous and stays - unmapped; a registration - function's is placed on it in whichever file defines it.""" + unmapped; a registration function's is placed on it in whichever file defines it.""" other = _rows("src/ui/impl/widget.cpp", "namespace ui::impl\n{\nint area(int x)\n{\n}\n}\n") path = "src/ui/widget.h" changed = WIDGET_H.replace("x);\n", "x, int scale);\n") @@ -937,6 +941,12 @@ def test_a_line_inside_a_python_decorator_stays_unmapped(tmp_path: Path) -> None after = before.replace('"before"', '"after"') unmapped, placed = _place_header(tmp_path, path, before, after, _rows(path, before)) assert (unmapped, placed) == ([(6, 6, "removed"), (6, 6, "added")], []) + # below a comment the brackets open above it are not known + commented = before.replace('"name",\n', "# the field\n") + (tmp_path / "c").mkdir() + after = commented.replace('"before"', '"after"') + got = _place_header(tmp_path / "c", path, commented, after, _rows(path, commented)) + assert got == ([(6, 6, "removed"), (6, 6, "added")], []) def test_a_line_between_two_inline_methods_is_placed_on_their_class(tmp_path: Path) -> None: @@ -1035,8 +1045,9 @@ def test_a_class_seeds_the_walk_only_through_a_line_placed_on_it(tmp_path: Path) from server.code.app.symbol.diff import touched_by_diff path = "src/ui/widget.h" - for sub, (case, change) in enumerate( - (("member", " int h = 0;\n"), ("access", "protected:\n")) + for case, change, want in ( + ("member", " int h = 0;\n", (["ui::Widget"], ["ui::Widget"], False)), + ("access", "protected:\n", ([], ["ui::Widget"], True)), ): (tmp_path / case).mkdir() after = WIDGET_H.replace(" int w = 0;\n", f" int w = 0;\n{change}") @@ -1045,5 +1056,4 @@ def test_a_class_seeds_the_walk_only_through_a_line_placed_on_it(tmp_path: Path) rows = _rows(path, WIDGET_H) seeds, gate, unmapped = touched_by_diff(rows, changes, new_side={path: []}) names = ([r["qualified_name"] for r in seeds], [r["qualified_name"] for r in gate]) - want = ((["ui::Widget"], ["ui::Widget"], False), ([], ["ui::Widget"], True))[sub] assert (*names, unmapped) == want, case diff --git a/tests/unit/test_code_review_brief_sections.py b/tests/unit/test_code_review_brief_sections.py index c3aff1598bf..6dd4016fd5e 100644 --- a/tests/unit/test_code_review_brief_sections.py +++ b/tests/unit/test_code_review_brief_sections.py @@ -1849,8 +1849,8 @@ async def test_a_pr_that_adds_a_whole_file_holds_every_line_outside_a_function() async def test_an_open_brief_maps_the_lines_of_a_function_its_overlay_adds() -> None: """An open PR inserts a function into `Shift`: at its head that function holds the lines it adds, the blank above it has no behaviour, and the covered new function - settles the brief. A head whose functions lack it leaves its braces and body in no - function, and its head line is a member line of the class.""" + settles the brief. A head whose functions lack it leaves its head, braces and body + in no function: a function head is no member line of the class.""" body = "+\n+ int h() const\n+ {\n+ return 3;\n+ }\n" diff = _file_diff(_SHIFT, f"@@ -18,0 +19,5 @@\n{body}") inp = dataclasses.replace(_inputs(), diff=diff, changed_paths=[_SHIFT], open=True) @@ -1858,7 +1858,7 @@ async def test_an_open_brief_maps_the_lines_of_a_function_its_overlay_adds() -> head = [(12, 16, "DB::Shift::g"), (26, 29, "DB::Shift::k")] for side, rows, verdict in ( ([*head, (20, 23, "DB::Shift::h")], ["DB::Shift::h"], ("covered_no_gaps", [])), - (head, ["DB::Shift", "DB::Shift::h"], ("unsettled", ["symbols:unmapped_changes"])), + (head, ["DB::Shift::h"], ("unsettled", ["symbols:unmapped_changes"])), ): calls = _WiringCalls(covered=True, repo=_ShiftRepo(), added=[h], new_side={_SHIFT: side}) payload = await review_brief_build.build_brief( From 2f571606bfc40790c33ddc0692276771fe7987b7 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 6 Dec 2026 07:19:50 +0000 Subject: [PATCH 06/16] A file-scope prototype follows the member-line rules and matches only in its own directory A file-scope line, which a struct's body is too, goes through the same declaration check as a class-body line, so a virtual, override or friend prototype stays a change. A C++ member line below a line that does not end a declaration (a lone virtual or template head) stays a change. A same-stem match requires the same directory and skips anonymous-namespace functions. A Python string line is a docstring only right below the class head. Placed rows keep the touched-row order, and the symbols note counts touched definitions. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- docs/features/code-index/history-and-prs.md | 29 +++++--- server/code/app/index/review_brief_build.py | 2 +- server/code/app/symbol/cpp_members.py | 5 +- server/code/app/symbol/diff.py | 72 +++++++++++++------ tests/unit/test_code_diff_sides.py | 50 +++++++++++-- tests/unit/test_code_review_brief_sections.py | 2 +- 6 files changed, 119 insertions(+), 41 deletions(-) diff --git a/docs/features/code-index/history-and-prs.md b/docs/features/code-index/history-and-prs.md index 1853632acc9..a54bb34007f 100644 --- a/docs/features/code-index/history-and-prs.md +++ b/docs/features/code-index/history-and-prs.md @@ -401,19 +401,26 @@ uncovered one answers `gaps`. `virtual`), a macro call, a statement (`return x;`), a line holding `virtual`, `override` or `final` (they change which function a call through a base reaches, an override no claim on the class covers), a line that holds one of those words after a - member, `/*`, `*/`, a raw string's opener or a quote no literal closes. In Python an - attribute (`retries = 3`, `name: str`) or a docstring line of a class body outside - its methods is placed when it leaves no bracket open and the line above it is code - that leaves none open either. Any other line stays a change: a `class` or `def` head, + member, `/*`, `*/`, a raw string's opener or a quote no literal closes, and a line + below one that does not end a declaration or a scope's head (a `virtual` or a + `template <...>` alone on the line above). The words are read as the line spells + them: an override declared without `override` reads as a member, and a claim on the + class then decides it. In Python an attribute (`retries = 3`, `name: str`) of a class + body outside its methods is placed when it leaves no bracket open and the line above + it is code that leaves none open either, and a docstring line when it sits right + below the class's head. Any other line stays a change: a `class` or `def` head, a decorator, a compound statement's head, a `return` line, a line with an odd count of `"""` or `'''` (it opens or closes a string around lines the diff leaves), a - decorator's argument, which belongs to the method below it, and a line below a blank - or comment line, where the brackets open above are not known. -- A C++ prototype is placed also on the function it declares, when the diff's files - outside tests hold one definition of it: in a class body the function whose - qualified name is the class's and the prototype's; at file scope a free function of - its name (not a method of a class the diff's files hold) in the same file or a file - of the same stem (`widget.h` and `widget.cpp`), or a registration function by the + decorator's argument, which belongs to the method below it, a string line below any + other line (an argument's or a value's), and a line below a blank or comment line, + where the brackets open above are not known. +- A C++ prototype is placed also on the function it declares, when it is a member line + by the rules above and the diff's files outside tests hold one definition of it: in + a class body the function whose qualified name is the class's and the prototype's; + at file scope a free function of its name (not a method of a class the diff's files + hold, nor one the compiler tier names in an anonymous namespace) in the same file or + a file of the same stem in its directory (`widget.h` and `widget.cpp`), or a + registration function by the index's registration rule (`registerWidgets`), which is often declared beside the call that runs it. Two definitions of the name under different qualified names leave it a change, and so does a file-scope line whose parentheses start with a literal diff --git a/server/code/app/index/review_brief_build.py b/server/code/app/index/review_brief_build.py index a7c4c10915e..13e5245b19a 100644 --- a/server/code/app/index/review_brief_build.py +++ b/server/code/app/index/review_brief_build.py @@ -440,7 +440,7 @@ async def _symbols_section( by_hop: dict[Any, Any] = dict(impact.get("by_hop_counts") or {}) hop1 = int(by_hop.get(1) or by_hop.get("1") or 0) folded = sum(collapsed.values()) - note = f"{len(kept)} touched functions" + (f" and {folded} collapsed" if folded else "") + note = f"{len(kept)} touched definitions" + (f" and {folded} collapsed" if folded else "") out = section( SERVED, verdict=verdict, diff --git a/server/code/app/symbol/cpp_members.py b/server/code/app/symbol/cpp_members.py index 06fd8d38ef5..84af5855bb9 100644 --- a/server/code/app/symbol/cpp_members.py +++ b/server/code/app/symbol/cpp_members.py @@ -52,8 +52,9 @@ def member_line(text: str, *, owner: str = "") -> bool: - """Whether a changed C++ line of a class body, outside every function, declares a - member of the class. It is shaped as a declaration (`_DECLARATION`: `int width = 0;`, + """Whether a changed C++ line outside every function declares one thing whole: a + member of the class whose body holds it, or at file scope a prototype or a + variable. It is shaped as a declaration (`_DECLARATION`: `int width = 0;`, `bool empty() const;`) or as the head of a special member of class `owner` (`Widget(int w);`), whole on the line: it ends with `;`, and every bracket it opens it closes and none it did not open, so it continues no prototype or template head diff --git a/server/code/app/symbol/diff.py b/server/code/app/symbol/diff.py index 6139aeae513..615489341e2 100644 --- a/server/code/app/symbol/diff.py +++ b/server/code/app/symbol/diff.py @@ -699,13 +699,15 @@ def _touched_rows_for_diff( kept.setdefault((str(r["path"]), str(r["symbol_id"])), {**r, "tier_ids": list(ids)}) # Deterministic, explainable order: the definitions a changed line sits in, then the # ones only a hunk header names, then whole-file seeds. - rank = {"hunk": 0, "header": 1, "file": 2} - out = sorted( - kept.values(), key=lambda r: (rank[r["via"]], str(r["path"]), int(r["start_line"] or 0)) - ) + out = sorted(kept.values(), key=_touched_rank) return out, list(dict.fromkeys(sid for r in out for sid in r["tier_ids"])), unmapped +def _touched_rank(r: dict[str, Any]) -> tuple[int, str, int]: + """A touched row's place in the order `_touched_rows_for_diff` returns.""" + return {"hunk": 0, "header": 1, "file": 2}[r["via"]], str(r["path"]), int(r["start_line"] or 0) + + def touched_by_diff( definitions: list[dict[str, Any]], changes: dict[str, list[Hunk]], @@ -733,7 +735,7 @@ def touched_by_diff( for r in placement.rows if (str(r["path"]), str(r["symbol_id"])) not in held ] - return seeds, gate, bool(placement.unmapped) + return sorted(seeds, key=_touched_rank), gate, bool(placement.unmapped) class Placement(NamedTuple): @@ -899,19 +901,23 @@ class body is one scope its indentation keeps, and an attribute or docstring lin is_class = holder is not None and str(holder.get("kind")) == "class" if lang == "python": return [holder] if holder is not None and is_class and _python_member_line(t, prev) else [] + if not _ends_declaration(prev): + return [] if holder is not None and is_class: owner = _parts(str(holder["qualified_name"])) if not member_line(t, owner=owner[-1]): return [] name = declared_name(t, in_class=True) return [holder, *functions.named([*owner, name])] if name else [holder] - name = declared_name(t, in_class=False) if holder is None else "" + if holder is not None or not member_line(t): + return [] + name = declared_name(t, in_class=False) if not name: return [] stem = _stem(path) registration = is_registration_caller(name) return functions.named( - [name], lambda p: registration or p == path or _stem(p) == stem, whole=False + [name], lambda p: registration or p == path or _same_unit(p, path, stem), whole=False ) @@ -928,19 +934,24 @@ class body is one scope its indentation keeps, and an attribute or docstring lin def _python_member_line(text: str, prev: str) -> bool: """Whether a changed line of a Python class body, outside every method, is an - attribute or a docstring line of the class: shaped as one (`_PY_ATTRIBUTE`, - `_PY_STRING`), with an even count of each triple quote (an odd one opens or closes a - string around unchanged lines), that leaves no bracket open or closes one it did not - open and does not end with `,`, below a line (`prev`) of code that does neither: a - line inside a decorator's or a call's arguments is the definition's below it, or an - expression's, not a member. Below a blank or comment line the brackets open above - it are not known, so no line there is placed. A `def`, `class` or compound statement - head, a decorator and a `return` line are not shaped as either.""" + attribute or a docstring line of the class: shaped as one (`_PY_ATTRIBUTE`, or + `_PY_STRING` right below a line ending with `:`, the class's head), with an even + count of each triple quote (an odd one opens or closes a string around unchanged + lines), that leaves no bracket open or closes one it did not open and does not end + with `,`, below a line (`prev`) of code that does neither: a line inside a + decorator's or a call's arguments is the definition's below it, or an expression's, + not a member. Below a blank or comment line the brackets open above it are not + known, so no line there is placed. A `def`, `class` or compound statement head, a + decorator and a `return` line are not shaped as either.""" if text.count('"""') % 2 or text.count("'''") % 2: return False - if _PY_ATTRIBUTE.match(text) is None and _PY_STRING.match(text) is None: - return False p = prev.split("#", 1)[0].rstrip() + if _PY_STRING.match(text) is not None: + # a docstring sits right below its class's head; a string line below another + # line is a value's or an argument's + return p.endswith(":") and _closed(text) + if _PY_ATTRIBUTE.match(text) is None: + return False return p != "" and _closed(text) and _closed(p) @@ -956,14 +967,24 @@ def _closed(line: str) -> bool: return depth == 0 and not code.endswith(",") +def _ends_declaration(prev: str) -> bool: + """Whether a C++ line, the one above a changed line, leaves nothing for the changed + line to continue: it ends a declaration or a scope's head (`;`, `{`, `}`, `:`), or is + blank or a comment. A `virtual` or a `template <...>` alone on the line above makes + the changed line part of what it starts.""" + s = prev.split("//", 1)[0].strip() + return s == "" or s.startswith(("*", "/*")) or s.endswith((";", "{", "}", ":", "*/")) + + def _parts(qualified: str) -> list[str]: """A qualified name's `::` parts, its parameters dropped.""" return qualified.split("(", 1)[0].strip().split("::") class _Functions: - """The function rows of the diff's files outside tests, by the last part of their - qualified name, built once for a diff: a prototype is placed on one of them.""" + """The function rows of the diff's files outside tests and anonymous namespaces (no + header declares a function of one), by the last part of their qualified name, built + once for a diff: a prototype is placed on one of them.""" def __init__(self, definitions: list[dict[str, Any]]) -> None: self.by_name: dict[str, list[dict[str, Any]]] = {} @@ -971,7 +992,11 @@ def __init__(self, definitions: list[dict[str, Any]]) -> None: str(r["qualified_name"]) for r in definitions if str(r.get("kind")) == "class" } for r in definitions: - if str(r.get("kind")) != "class" and not is_test_path(str(r["path"])): + if ( + str(r.get("kind")) != "class" + and not is_test_path(str(r["path"])) + and "$anonymous_namespace" not in str(r["qualified_name"]) + ): self.by_name.setdefault(_parts(str(r["qualified_name"]))[-1], []).append(r) def named( @@ -998,6 +1023,13 @@ def named( return rows if len({str(r["qualified_name"]) for r in rows}) == 1 else [] +def _same_unit(p: str, path: str, stem: str) -> bool: + """Whether file `p` is of `path`'s stem in its directory: `src/ui/widget.cpp` for + `src/ui/widget.h`, never a `widget.cpp` of another directory, which another + namespace's function of the name may sit in.""" + return _stem(p) == stem and p.rsplit("/", 1)[0] == path.rsplit("/", 1)[0] + + def _stem(path: str) -> str: """A file's name without its extension: `src/ui/widget.h` is `widget`.""" return path.rsplit("/", 1)[-1].split(".", 1)[0] diff --git a/tests/unit/test_code_diff_sides.py b/tests/unit/test_code_diff_sides.py index 787e3b81a73..2b48f4e5940 100644 --- a/tests/unit/test_code_diff_sides.py +++ b/tests/unit/test_code_diff_sides.py @@ -838,6 +838,11 @@ def test_a_member_line_or_a_prototype_is_placed_on_what_it_declares( ("int area(const Widget & x);\n", "int area(const Widget & x);\nconst int limit = 4;\n"), ("#pragma once\n", "#pragma once\n#include \n"), ("int area(const Widget & x);\n", "int area(const Widget & x);\nint perimeter(int w);\n"), + # file-scope lines a struct's body holds too (the index serves no struct row the + # brief reads): a prototype made virtual, an override, a friend + ("int area(const Widget & x);\n", "virtual int area(const Widget & x);\n"), + ("int area(const Widget & x);\n", "int area(const Widget & x) override;\n"), + ("int area(const Widget & x);\n", "friend int area(const Widget & x);\n"), # a constant built by a constructor, which reads as no prototype ( "int area(const Widget & x);\n", @@ -884,14 +889,29 @@ def test_a_line_that_shapes_a_scope_or_names_no_definition_stays_unmapped( def test_a_file_scope_prototype_is_placed_only_on_one_definition(tmp_path: Path) -> None: - """A prototype at file scope whose name two definitions of the diff's files share - under different qualified names (in two files of its stem) is ambiguous and stays - unmapped; a registration function's is placed on it in whichever file defines it.""" - other = _rows("src/ui/impl/widget.cpp", "namespace ui::impl\n{\nint area(int x)\n{\n}\n}\n") + """A prototype at file scope whose name two definitions of its stem's file share + under different qualified names is ambiguous and stays unmapped; a file of its stem + in another directory, and a function the compiler tier names in an anonymous + namespace, are no candidates; a registration function's is placed on it in + whichever file defines it.""" path = "src/ui/widget.h" changed = WIDGET_H.replace("x);\n", "x, int scale);\n") - unmapped, placed = _place_header(tmp_path, path, WIDGET_H, changed, [*_widget_rows(), *other]) - assert (unmapped, placed) == ([(16, 16, "removed"), (16, 16, "added")], []) + impl = "namespace ui::impl\n{\nint area(int x)\n{\n}\n}\n" + anonymous = { + **_rows("src/ui/widget.cpp", impl)[0], + "qualified_name": "ui::$anonymous_namespace_src/ui/widget.cpp::area", + } + for sub, (other, want) in enumerate( + ( + (_rows("src/ui/widget.cpp", impl), [(16, 16, "removed"), (16, 16, "added")]), + (_rows("src/ui/impl/widget.cpp", impl), None), + ([anonymous], None), + ) + ): + (tmp_path / str(sub)).mkdir() + rows = [*_widget_rows(), *other] + got = _place_header(tmp_path / str(sub), path, WIDGET_H, changed, rows) + assert got == (want, [] if want else ["ui::area"]), sub path = "src/ui/register.h" changed = REGISTER_H.replace("();", "(int flags);") (tmp_path / "r").mkdir() @@ -929,6 +949,18 @@ def test_a_file_scope_prototype_is_not_placed_on_a_method(tmp_path: Path) -> Non assert (unmapped, placed) == ([(16, 16, "removed"), (16, 16, "added")], []) +def test_a_member_below_a_line_it_continues_stays_unmapped(tmp_path: Path) -> None: + """A C++ prototype below a `virtual` or a template head alone on the line above is + part of what that line starts: it stays a change.""" + path = "src/ui/widget.h" + for sub, above in enumerate((" virtual\n", " template \n")): + before = WIDGET_H.replace(" void resize(int w);\n", f"{above} void resize(int w);\n") + after = before.replace("resize(int w);", "resize(int w, int h);") + (tmp_path / str(sub)).mkdir() + unmapped, placed = _place_header(tmp_path / str(sub), path, before, after) + assert (unmapped, placed) == ([(11, 11, "removed"), (11, 11, "added")], []), above + + def test_a_line_inside_a_python_decorator_stays_unmapped(tmp_path: Path) -> None: """A line of a decorator's arguments spread over lines sits above the method's `def`, where the method's row starts, so the rows put it in the class body: it is the @@ -941,6 +973,12 @@ def test_a_line_inside_a_python_decorator_stays_unmapped(tmp_path: Path) -> None after = before.replace('"before"', '"after"') unmapped, placed = _place_header(tmp_path, path, before, after, _rows(path, before)) assert (unmapped, placed) == ([(6, 6, "removed"), (6, 6, "added")], []) + # a string the line above continues is an argument's, not a docstring + joined = before.replace('"name",\n', 'reason="slow "\n "name"\n') + (tmp_path / "j").mkdir() + after = joined.replace('"name"', '"names"') + got = _place_header(tmp_path / "j", path, joined, after, _rows(path, joined)) + assert got == ([(6, 6, "removed"), (6, 6, "added")], []) # below a comment the brackets open above it are not known commented = before.replace('"name",\n', "# the field\n") (tmp_path / "c").mkdir() diff --git a/tests/unit/test_code_review_brief_sections.py b/tests/unit/test_code_review_brief_sections.py index 6dd4016fd5e..2b0d7fdf26c 100644 --- a/tests/unit/test_code_review_brief_sections.py +++ b/tests/unit/test_code_review_brief_sections.py @@ -1561,7 +1561,7 @@ async def test_the_symbols_section_collapses_the_wiring_the_pr_adds_and_nothing_ assert [r["qualified_name"] for r in sym["rows"]] == kept assert not any("via" in r for r in sym["rows"]) assert sym["collapsed"] == {"registration": 2, "factory": 1, "constructor": 1, "one_line": 1} - assert sym["note"].startswith("12 touched functions and 5 collapsed;") + assert sym["note"].startswith("12 touched definitions and 5 collapsed;") # the callers are read once, in both tiers, for the factories and constructors with # outside sites: the constructor's one site is in the parser's edges assert repo.asked == [["s-ctor", "s-ctor-ts"]] From 9f80fe922184e3de79595ee5754740661910dcd5 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 6 Dec 2026 07:36:03 +0000 Subject: [PATCH 07/16] A prototype is placed only with the function it declares, and a struct's lines stay changes An in-class prototype whose function the diff's files do not define stays a change: its defaults and parameters reach the callers, which a claim on the class does not decide. So does one whose name a function in a scope nested in the class shares. code.impact reads the C++ struct rows of the diff's files for placement alone, and a line of a struct's body is placed on nothing. The pinned brief digest follows the symbols note's new label. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- docs/features/code-index/history-and-prs.md | 26 ++++---- server/code/app/symbol/diff.py | 62 +++++++++++++++-- server/code/app/symbol/impact.py | 12 +++- tests/unit/test_code_diff_sides.py | 66 ++++++++++++++++++- .../unit/test_code_review_brief_no_groups.py | 2 +- tests/unit/test_code_review_brief_sections.py | 7 +- 6 files changed, 150 insertions(+), 25 deletions(-) diff --git a/docs/features/code-index/history-and-prs.md b/docs/features/code-index/history-and-prs.md index a54bb34007f..1c963d5a728 100644 --- a/docs/features/code-index/history-and-prs.md +++ b/docs/features/code-index/history-and-prs.md @@ -420,21 +420,25 @@ uncovered one answers `gaps`. at file scope a free function of its name (not a method of a class the diff's files hold, nor one the compiler tier names in an anonymous namespace) in the same file or a file of the same stem in its directory (`widget.h` and `widget.cpp`), or a - registration function by the - index's registration rule (`registerWidgets`), which is often declared beside the - call that runs it. Two definitions of the name under different qualified names leave - it a change, and so does a file-scope line whose parentheses start with a literal - (`static const std::regex re("a+");`), a constant built by a constructor. A - registration statement inside a registration function's body is that function's - line already. + registration function by the index's registration rule (`registerWidgets`), which + is often declared beside the call that runs it. A prototype whose function the + diff's files do not define stays a change, in a class body too: its defaults and + parameters reach the function's callers, which a claim on the class does not + decide. So does a prototype in a class body when a function of its name sits in a + scope nested in the class, which it may declare instead. Two definitions of the + name under different qualified names leave it a change, and so does a file-scope + line whose parentheses start with a literal (`static const std::regex re("a+");`), + a constant built by a constructor. A registration statement inside a registration + function's body is that function's line already. - The rules read the changed line, the line above it and the index's rows, and they are as good as those rows. A line of a method the parser did not read as one (a head spelled with a macro it cannot expand) sits in the class body by the rows, so a declaration in its body (`size_t n = rows.size();`) reads as a member line and is - placed on the class that holds the method: a claim on the class then decides it. The - index serves a C++ `struct` as no definition the brief reads, so a struct's body is - file scope to these rules: its members stay changes, a prototype in it is placed - only as a file-scope one is, and a struct's method counts as a free function there. + placed on the class that holds the method: a claim on the class then decides it. A + C++ `struct` is no definition the brief claims, and `code.impact` reads its rows for + placement alone: a line of the body of a struct the index holds a row of stays a + change. The parser holds no row of a struct nested in a class, so a data member of + one reads as a member of the class around it. - No line is placed that a macro or a statement continues (the line above it ends with `\` or `??/`), that starts a run the hunk shows no line above (a diff with no context), or that sits in a function the new side pairs with no row, or on a side nobody read. diff --git a/server/code/app/symbol/diff.py b/server/code/app/symbol/diff.py index 615489341e2..b6e3169fad7 100644 --- a/server/code/app/symbol/diff.py +++ b/server/code/app/symbol/diff.py @@ -720,8 +720,10 @@ def touched_by_diff( placed on no definition). A function is touched by a line it holds (`_touched_rows_for_diff`), a class or a function by a member line or a C++ prototype placed on it (`place_lines`); a class that holds only lines that stay - changes in no definition is the test gate's alone.""" - gate, _, _ = _touched_rows_for_diff(definitions, changes, new_side=new_side) + changes in no definition is the test gate's alone. A `struct` row is read by + `place_lines` alone.""" + rows = [r for r in definitions if str(r.get("kind")) != "struct"] + gate, _, _ = _touched_rows_for_diff(rows, changes, new_side=new_side) placement = place_lines(definitions, changes, new_side=new_side) placed = {(str(r["path"]), str(r["symbol_id"])) for r in placement.rows} seeds = [ @@ -780,11 +782,16 @@ class body touches the class. A test file's lines are not counted: its functions leaves of the graph. Lines outside every definition are walked as ranges, the definitions that hold the rest are found once per file and the lines the diff adds by bisection, so the cost follows the file's extent and the diff's lines, not what the - hunk headers claim.""" + hunk headers claim. + + A C++ `struct` row in `definitions` is read only here, as a scope no claim is read + for: a line its body holds, at file scope or in a class, is placed on nothing.""" by_path: dict[str, list[dict[str, Any]]] = {} + structs: dict[str, list[dict[str, Any]]] = {} for r in definitions: - by_path.setdefault(str(r["path"]), []).append(r) - functions = _Functions(definitions) + into = structs if str(r.get("kind")) == "struct" else by_path + into.setdefault(str(r["path"]), []).append(r) + functions = _Functions([r for rs in by_path.values() for r in rs]) out: dict[str, list[tuple[int, int, Side]]] = {} placed: dict[str, dict[str, Any]] = {} for p, hunks in changes.items(): @@ -840,6 +847,8 @@ class body touches the class. A test file's lines are not counted: its functions else (m, None, False) for m in _added(hunk, seeds, inert_new) ] + if p in structs: + loose = _outside_structs(loose, structs[p], hunks, by_lines, run_of) context = { "removed": (text, cont_old, unseen_old, above_old), "added": (added, cont_new, unseen_new, above_new), @@ -860,6 +869,30 @@ class body touches the class. A test file's lines are not counted: its functions return Placement(out, list(placed.values())) +def _outside_structs( + loose: list[tuple[tuple[int, int, Side], dict[str, Any] | None, bool]], + structs: list[dict[str, Any]], + hunks: list[Hunk], + by_lines: list[Hunk], + run_of: dict[int, int], +) -> list[tuple[tuple[int, int, Side], dict[str, Any] | None, bool]]: + """`loose` with each line a struct's body holds inside its holder (or at file scope) + made unplaceable: the struct is the scope it declares in, and no row of it is read. + A removed line is held by the struct whose old extent holds it, an added one by the + struct that holds its run's old lines on both sides (`_FileSpans.around`).""" + spans = _FileSpans(structs, hunks, indented=False) + old = spans.owners(sorted({m[0] for m, _, ok in loose if ok and m[2] == "removed"})) + new = spans.around([b for h in by_lines for b in h.blocks if b.added]) + + def in_struct(m: tuple[int, int, Side], holder: dict[str, Any] | None) -> bool: + s = old.get(m[0]) if m[2] == "removed" else new.get(run_of.get(m[0], -1)) + if s is None: + return False + return holder is None or _span(holder)[0] <= _span(s)[0] <= _span(s)[1] <= _span(holder)[1] + + return [(m, h, ok and not in_struct(m, h)) for m, h, ok in loose] + + def _place_member( n: int, holder: dict[str, Any] | None, @@ -879,7 +912,8 @@ def _place_member( In C++ a member line of a class body (`cpp_members.member_line`) is placed on the class (`holder`), and a prototype there also on the function it declares (`cpp_members.declared_name`): the definitions of the diff's files whose qualified - name is the class's and the prototype's. A prototype at file scope (`holder` None) is + name is the class's and the prototype's. A prototype of a function they do not hold + stays a change. A prototype at file scope (`holder` None) is placed on the function of its name in the diff's files that sits in the same file or one of the same stem (`widget.h` and `widget.cpp`), or that is a registration function (`is_registration_caller`, often declared beside the call that runs it): @@ -908,7 +942,12 @@ class body is one scope its indentation keeps, and an attribute or docstring lin if not member_line(t, owner=owner[-1]): return [] name = declared_name(t, in_class=True) - return [holder, *functions.named([*owner, name])] if name else [holder] + if not name: + return [holder] + # a prototype changes what calls of its function do (a default, a parameter): + # the class's claim decides it only with the function's + declared = functions.named([*owner, name]) + return [holder, *declared] if declared and not functions.nested(owner, name) else [] if holder is not None or not member_line(t): return [] name = declared_name(t, in_class=False) @@ -999,6 +1038,15 @@ def __init__(self, definitions: list[dict[str, Any]]) -> None: ): self.by_name.setdefault(_parts(str(r["qualified_name"]))[-1], []).append(r) + def nested(self, owner: list[str], name: str) -> bool: + """Whether a function `name` sits in a scope inside class `owner` (a struct or a + class the index serves no row of): a prototype of that name in the class's + body may declare it rather than the class's own.""" + return any( + len(q) > len(owner) + 1 and q[: len(owner)] == owner + for q in (_parts(str(r["qualified_name"])) for r in self.by_name.get(name, [])) + ) + def named( self, parts: list[str], diff --git a/server/code/app/symbol/impact.py b/server/code/app/symbol/impact.py index a197cac93ef..e755ee93a32 100644 --- a/server/code/app/symbol/impact.py +++ b/server/code/app/symbol/impact.py @@ -54,6 +54,7 @@ link_tests, touched_of, ) +from server.code.domain.extract.treesitter import lang_for_path from server.code.domain.index.epistemic import ( CAUSE_NEW_SIDE_FAILED, CAUSE_NEW_SIDE_UNREAD, @@ -191,7 +192,16 @@ async def _diff_seeds( new_side, unread, failed = await _new_side( repo, org, ns, changes, definitions, overlay, new_side_sha ) - touched_rows, gate_touched, unmapped = touched_by_diff(definitions, changes, new_side=new_side) + # A C++ struct is no definition impact reads, but a line of its body declares in it, + # not in the class or the file around it: `place_lines` reads its rows for that alone + cpp = [p for p in changes if lang_for_path(p) == "cpp"] + read = ( + await repo.functions_for_paths(org, ns, cpp, limit=2000, kinds=("struct",)) if cpp else [] + ) + structs = [r for r in read if str(r.get("kind")) == "struct"] + touched_rows, gate_touched, unmapped = touched_by_diff( + [*definitions, *structs], changes, new_side=new_side + ) added_rows = _overlay_added_rows(overlay) causes = [CAUSE_NEW_SIDE_UNREAD] if unread else [] if failed: diff --git a/tests/unit/test_code_diff_sides.py b/tests/unit/test_code_diff_sides.py index 2b48f4e5940..432ae027116 100644 --- a/tests/unit/test_code_diff_sides.py +++ b/tests/unit/test_code_diff_sides.py @@ -752,6 +752,26 @@ def test_a_line_holding_a_comment_delimiter_is_a_change() -> None: REGISTER_CPP = "namespace ui\n{\nvoid registerWidgets()\n{\n add();\n}\n}\n" +def _structs(path: str, source: str) -> list[dict[str, Any]]: + """The struct rows the index holds of `source` at `path`, which code.impact reads + for placement alone.""" + pf, error = parse_for_ingest(path, source.encode()) + assert pf is not None and not error + return [ + { + "symbol_id": f"s-{s.qualified_name}@{s.start_line}", + "path": path, + "qualified_name": s.qualified_name, + "start_line": s.start_line, + "end_line": s.end_line, + "kind": "struct", + "tier": "treesitter", + } + for s in pf.symbols + if s.kind == "struct" + ] + + def _widget_rows() -> list[dict[str, Any]]: return [ *_rows("src/ui/widget.h", WIDGET_H), @@ -787,10 +807,9 @@ def _place_header( @pytest.mark.parametrize( ("old", "new", "placed"), [ - # a member, a changed default, a prototype the index holds no definition of + # a member and a changed default (" int w = 0;\n", " int w = 0;\n int h = 0;\n", ["ui::Widget"]), (" int w = 0;\n", " int w = 1;\n", ["ui::Widget"]), - (" int w = 0;\n", " int w = 0;\n bool empty() const;\n", ["ui::Widget"]), # a prototype of a function the index holds ( " void resize(int w);\n", @@ -856,6 +875,10 @@ def test_a_member_line_or_a_prototype_is_placed_on_what_it_declares( ("class Widget\n", "class Widget\n : public Base\n"), (" int w = 0;\n", " int w = 0;\n FRIEND_TEST(WidgetTest, Resize);\n"), (" int w = 0;\n", " int w = 0;\n check(w);\n"), + # a prototype of a function the diff's files do not define: what it declares + # (its defaults, its parameters) reaches its callers, which no claim on the + # class decides + (" int w = 0;\n", " int w = 0;\n bool empty() const;\n"), # a prototype made virtual, which changes which function a call through a base # reaches, the lines of a prototype spread over lines (its head may be virtual), # a template head's parameter lines, a non-type one among them @@ -949,6 +972,45 @@ def test_a_file_scope_prototype_is_not_placed_on_a_method(tmp_path: Path) -> Non assert (unmapped, placed) == ([(16, 16, "removed"), (16, 16, "added")], []) +def test_a_line_of_a_struct_body_stays_unmapped(tmp_path: Path) -> None: + """A struct is a scope no claim is read for: a member or a prototype of a struct the + index holds a row of stays a change. The parser holds none for a struct nested in a + class, whose body reads as the class's: a prototype there is no member line of the + class when a function of its name sits in a scope inside the class, which it may + declare; a data member there is the class's (the documented limit).""" + path = "src/ui/pool.h" + header = ( + "namespace ui\n{\nclass Pool\n{\npublic:\n struct Options\n {\n" + " int size = 0;\n void reset();\n };\n void reset();\n};\n\n" + "struct Stats\n{\n int hits = 0;\n void reset();\n};\n}\n" + ) + source = ( + "namespace ui\n{\nvoid Pool::reset()\n{\n}\nvoid Pool::Options::reset()\n{\n}\n" + "void Stats::reset()\n{\n}\n}\n" + ) + rows = [*_rows(path, header), *_rows("src/ui/pool.cpp", source)] + structs = _structs(path, header) + assert {r["qualified_name"] for r in structs} == {"ui::Stats"} + for sub, (old, new, line, placed) in enumerate( + ( + (" void reset();", " void reset(bool hard = true);", 9, None), + (" void reset();\n};\n}", " void reset(bool hard = true);\n};\n}", 17, None), + (" int hits = 0;", " int hits = 1;", 16, None), + (" int size = 0;", " int size = 4;", 8, ["ui::Pool"]), + ) + ): + (tmp_path / str(sub)).mkdir() + after = header.replace(old, new) + assert after != header + got = _place_header(tmp_path / str(sub), path, header, after, [*rows, *structs]) + want = ( + ([(line, line, "removed"), (line, line, "added")], []) + if placed is None + else (None, placed) + ) + assert got == want, old + + def test_a_member_below_a_line_it_continues_stays_unmapped(tmp_path: Path) -> None: """A C++ prototype below a `virtual` or a template head alone on the line above is part of what that line starts: it stays a change.""" diff --git a/tests/unit/test_code_review_brief_no_groups.py b/tests/unit/test_code_review_brief_no_groups.py index 9a6095f76bb..8de35c8409b 100644 --- a/tests/unit/test_code_review_brief_no_groups.py +++ b/tests/unit/test_code_review_brief_no_groups.py @@ -18,7 +18,7 @@ from server.code.app.index import review_brief_build # pinned canonical digest of the brief below -PAYLOAD_DIGEST = "1607bbe37cb7cd2b34d50bb337c8b5f4d3119f54ef5b0467af48f1cf70cc2cfb" +PAYLOAD_DIGEST = "104413eea6c7d8e50ea11feeb9728411a83ab96cd0c4d50d336a613e9bf870d4" ORG, NS = "clickhouse", "code-clickhouse" SHA = "1e93c0a25f177d3a971668e058745a6e8bfe3e2c" PARENT = "b41b780feecc85780bebca041acda03358719a79" diff --git a/tests/unit/test_code_review_brief_sections.py b/tests/unit/test_code_review_brief_sections.py index 2b0d7fdf26c..539fad252a3 100644 --- a/tests/unit/test_code_review_brief_sections.py +++ b/tests/unit/test_code_review_brief_sections.py @@ -1923,9 +1923,7 @@ async def __call__(self, op: str, body: dict[str, Any]) -> dict[str, Any]: (" int step = 0;", ["DB::Shift"]), (" static constexpr int limit = 8;", ["DB::Shift"]), (' static constexpr auto name = "shift";', ["DB::Shift"]), - # prototypes: of a function the index does not hold, and of `k`, which the - # brief lists for its body too - (" int other() const;", ["DB::Shift"]), + # a prototype of `k`, which the brief lists for its body too (" int k(int step) const;", ["DB::Shift::k", "DB::Shift"]), ], ) @@ -1998,6 +1996,9 @@ async def test_a_member_line_of_a_class_body_is_claimed_on_the_class( # below a member, lines of the class body that declare no member: a macro call, # which may expand to any member or none, and members spelled after other scope text _file_diff(_SHIFT, "@@ -17 +28,2 @@\n int base = 1;\n+ check(table);\n"), + # a prototype of a function the diff's files do not define: its callers see what + # it declares, which no claim on the class decides + _file_diff(_SHIFT, "@@ -17 +28,2 @@\n int base = 1;\n+ int other() const;\n"), # a prototype made virtual below a member: calls through a base reach the # overrides, which no claim on the class covers _file_diff( From 8ef5fd5cb2e2e18ea49e3629aa6150f445232c81 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 6 Dec 2026 07:50:49 +0000 Subject: [PATCH 08/16] A commented or braced prototype and a struct's method are not placed on the wrong definition The prototype name read drops a trailing // comment, and a class-body line that names something before a ( but is not read as a prototype stays a change rather than landing on the class alone. A file-scope prototype no longer takes a struct's method, or a method of a scope nested in a class, as a free function. An open PR's added functions are what its new prototypes declare. code.impact reads the struct rows alongside the new side, in their own span. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- docs/features/code-index/history-and-prs.md | 13 ++-- server/code/app/symbol/cpp_members.py | 12 +++- server/code/app/symbol/diff.py | 54 +++++++++++------ server/code/app/symbol/impact.py | 38 ++++++++---- tests/unit/test_code_diff_sides.py | 60 ++++++++++++++++--- tests/unit/test_code_review_brief_sections.py | 27 ++++++--- 6 files changed, 154 insertions(+), 50 deletions(-) diff --git a/docs/features/code-index/history-and-prs.md b/docs/features/code-index/history-and-prs.md index 1c963d5a728..d80df4d9ff7 100644 --- a/docs/features/code-index/history-and-prs.md +++ b/docs/features/code-index/history-and-prs.md @@ -417,15 +417,20 @@ uncovered one answers `gaps`. - A C++ prototype is placed also on the function it declares, when it is a member line by the rules above and the diff's files outside tests hold one definition of it: in a class body the function whose qualified name is the class's and the prototype's; - at file scope a free function of its name (not a method of a class the diff's files - hold, nor one the compiler tier names in an anonymous namespace) in the same file or - a file of the same stem in its directory (`widget.h` and `widget.cpp`), or a + at file scope a free function of its name (not a method: no class or struct the + index holds names a scope around it; nor one the compiler tier names in an anonymous + namespace) in the same file or a file of the same stem in its directory (`widget.h` + and `widget.cpp`), or a registration function by the index's registration rule (`registerWidgets`), which is often declared beside the call that runs it. A prototype whose function the diff's files do not define stays a change, in a class body too: its defaults and parameters reach the function's callers, which a claim on the class does not decide. So does a prototype in a class body when a function of its name sits in a - scope nested in the class, which it may declare instead. Two definitions of the + scope nested in the class, which it may declare instead, and a class-body line that + names something before a `(` but is not read as a prototype (`void f(Size s = +{});`). A trailing `//` comment is not read. The namespace a file-scope prototype + sits in is not read either: a free function of its name in another namespace of the + same-stem file is its candidate as well. Two definitions of the name under different qualified names leave it a change, and so does a file-scope line whose parentheses start with a literal (`static const std::regex re("a+");`), a constant built by a constructor. A registration statement inside a registration diff --git a/server/code/app/symbol/cpp_members.py b/server/code/app/symbol/cpp_members.py index 84af5855bb9..73dd53ea91b 100644 --- a/server/code/app/symbol/cpp_members.py +++ b/server/code/app/symbol/cpp_members.py @@ -86,6 +86,13 @@ def member_line(text: str, *, owner: str = "") -> bool: return True +def names_call(text: str) -> bool: + """Whether a C++ line names something right before a `(` the way a prototype, a call + or a constructor does (`_HEAD`): a line of a class body that does is a function's + declaration or nothing of the class's own.""" + return _HEAD.match(text.split("//", 1)[0]) is not None + + def declared_name(text: str, *, in_class: bool) -> str: """The name a C++ line declares as a function, '' when it declares none: a prototype on one line (`bool isEmpty(const Rows & rows) const;`, `static T f(X x);`), and in a @@ -93,8 +100,9 @@ class body also a constructor, which names no type. Outside a class the line mus name a return type, and what follows the `(` must not start with a literal, which makes the line a constant built by a constructor (`static const std::regex re("a+");`). A name spelled in capitals is a macro (`DECLARE(...)`), and one after a - word that opens a statement (`return f(x);`) is a call.""" - m = _HEAD.match(text) + word that opens a statement (`return f(x);`) is a call. A trailing `//` comment is + not read.""" + m = _HEAD.match(text.split("//", 1)[0]) if m is None: return "" name, words, rest = m["name"], m["type"].split(), m["rest"].rstrip() diff --git a/server/code/app/symbol/diff.py b/server/code/app/symbol/diff.py index b6e3169fad7..2d943812ada 100644 --- a/server/code/app/symbol/diff.py +++ b/server/code/app/symbol/diff.py @@ -10,7 +10,7 @@ from collections.abc import Callable from typing import Any, Literal, NamedTuple -from server.code.app.symbol.cpp_members import declared_name, member_line +from server.code.app.symbol.cpp_members import declared_name, member_line, names_call from server.code.domain.extract.registration import is_registration_caller from server.code.domain.extract.treesitter import lang_for_path from server.code.domain.index import coverage_runs as cr @@ -704,8 +704,13 @@ def _touched_rows_for_diff( def _touched_rank(r: dict[str, Any]) -> tuple[int, str, int]: - """A touched row's place in the order `_touched_rows_for_diff` returns.""" - return {"hunk": 0, "header": 1, "file": 2}[r["via"]], str(r["path"]), int(r["start_line"] or 0) + """A touched row's place in the order `_touched_rows_for_diff` returns, with the + functions an open PR adds (`added`) last, as code.impact lists them.""" + return ( + {"hunk": 0, "header": 1, "file": 2, "added": 3}[r["via"]], + str(r["path"]), + int(r["start_line"] or 0), + ) def touched_by_diff( @@ -713,6 +718,7 @@ def touched_by_diff( changes: dict[str, list[Hunk]], *, new_side: NewSide | None = None, + added: list[dict[str, Any]] | None = None, ) -> tuple[list[dict[str, Any]], list[dict[str, Any]], bool]: """(the definitions a diff touches, which seed code.impact's walk and are the subjects of its claims; the ones code.test_gate reads, every class a changed line of a body @@ -721,10 +727,10 @@ def touched_by_diff( (`_touched_rows_for_diff`), a class or a function by a member line or a C++ prototype placed on it (`place_lines`); a class that holds only lines that stay changes in no definition is the test gate's alone. A `struct` row is read by - `place_lines` alone.""" + `place_lines` alone, and so are the functions an open PR adds (`added`).""" rows = [r for r in definitions if str(r.get("kind")) != "struct"] gate, _, _ = _touched_rows_for_diff(rows, changes, new_side=new_side) - placement = place_lines(definitions, changes, new_side=new_side) + placement = place_lines(definitions, changes, new_side=new_side, added_functions=added) placed = {(str(r["path"]), str(r["symbol_id"])) for r in placement.rows} seeds = [ r @@ -733,7 +739,7 @@ def touched_by_diff( ] held = {(str(r["path"]), str(r["symbol_id"])) for r in gate} seeds += [ - {**r, "via": "hunk", "tier_ids": list(r.get("tier_ids") or [r["symbol_id"]])} + {**r, "via": r.get("via", "hunk"), "tier_ids": list(r.get("tier_ids") or [r["symbol_id"]])} for r in placement.rows if (str(r["path"]), str(r["symbol_id"])) not in held ] @@ -755,6 +761,7 @@ def place_lines( changes: dict[str, list[Hunk]], *, new_side: NewSide | None = None, + added_functions: list[dict[str, Any]] | None = None, ) -> Placement: """Per source file, the changed lines that are not inert (`inert_lines`) and sit in no function, each placed on its own side: a line the diff removes or replaces against @@ -785,13 +792,18 @@ class body touches the class. A test file's lines are not counted: its functions hunk headers claim. A C++ `struct` row in `definitions` is read only here, as a scope no claim is read - for: a line its body holds, at file scope or in a class, is placed on nothing.""" + for: a line its body holds, at file scope or in a class, is placed on nothing. The + functions an open PR adds (`added_functions`, its overlay's) are what a prototype the PR adds + with them declares: one is placed on them as on a definition the index holds.""" by_path: dict[str, list[dict[str, Any]]] = {} structs: dict[str, list[dict[str, Any]]] = {} for r in definitions: into = structs if str(r.get("kind")) == "struct" else by_path into.setdefault(str(r["path"]), []).append(r) - functions = _Functions([r for rs in by_path.values() for r in rs]) + functions = _Functions( + [*(r for rs in by_path.values() for r in rs), *(added_functions or [])], + [r for rs in structs.values() for r in rs], + ) out: dict[str, list[tuple[int, int, Side]]] = {} placed: dict[str, dict[str, Any]] = {} for p, hunks in changes.items(): @@ -943,7 +955,9 @@ class body is one scope its indentation keeps, and an attribute or docstring lin return [] name = declared_name(t, in_class=True) if not name: - return [holder] + # a line naming a function it is not read as the prototype of (`f(Size s = + # {});`) may declare one: the class's claim alone does not decide it + return [] if names_call(t) else [holder] # a prototype changes what calls of its function do (a default, a parameter): # the class's claim decides it only with the function's declared = functions.named([*owner, name]) @@ -1025,10 +1039,13 @@ class _Functions: header declares a function of one), by the last part of their qualified name, built once for a diff: a prototype is placed on one of them.""" - def __init__(self, definitions: list[dict[str, Any]]) -> None: + def __init__(self, definitions: list[dict[str, Any]], scopes: list[dict[str, Any]]) -> None: self.by_name: dict[str, list[dict[str, Any]]] = {} + # the classes and structs a function may be a method of self.classes = { - str(r["qualified_name"]) for r in definitions if str(r.get("kind")) == "class" + str(r["qualified_name"]) + for r in [*definitions, *scopes] + if str(r.get("kind")) in ("class", "struct") } for r in definitions: if ( @@ -1038,6 +1055,13 @@ def __init__(self, definitions: list[dict[str, Any]]) -> None: ): self.by_name.setdefault(_parts(str(r["qualified_name"]))[-1], []).append(r) + def _free(self, r: dict[str, Any]) -> bool: + """Whether a function row is a free function: no class or struct the index holds + names a scope around it (`ui::Pool::Options::reset` is a method of `ui::Pool`'s + even when the parser holds no row of `Options`).""" + q = _parts(str(r["qualified_name"]))[:-1] + return not any("::".join(q[:k]) in self.classes for k in range(1, len(q) + 1)) + def nested(self, owner: list[str], name: str) -> bool: """Whether a function `name` sits in a scope inside class `owner` (a struct or a class the index serves no row of): a prototype of that name in the class's @@ -1055,17 +1079,13 @@ def named( whole: bool = True, ) -> list[dict[str, Any]]: """The rows whose qualified name is `parts` (with `whole`), or else ends with its - one part and names no class of the definitions above it (a free function's), in + one part and is a free function's (`_free`), in files `path_ok` accepts, when they share one qualified name (overloads are one subject of a claim), else none.""" rows = [ r for r in self.by_name.get(parts[-1], []) - if ( - _parts(str(r["qualified_name"])) == parts - if whole - else "::".join(_parts(str(r["qualified_name"]))[:-1]) not in self.classes - ) + if (_parts(str(r["qualified_name"])) == parts if whole else self._free(r)) and (path_ok is None or path_ok(str(r["path"]))) ] return rows if len({str(r["qualified_name"]) for r in rows}) == 1 else [] diff --git a/server/code/app/symbol/impact.py b/server/code/app/symbol/impact.py index e755ee93a32..36ea6e9d75c 100644 --- a/server/code/app/symbol/impact.py +++ b/server/code/app/symbol/impact.py @@ -189,20 +189,14 @@ async def _diff_seeds( # Only the files the index reads: a path outside its prefixes holds no function prefixes = _indexed_prefixes(org, ns) changes = {p: h for p, h in changes.items() if not prefixes or p.startswith(prefixes)} - new_side, unread, failed = await _new_side( - repo, org, ns, changes, definitions, overlay, new_side_sha + (new_side, unread, failed), structs = await asyncio.gather( + _new_side(repo, org, ns, changes, definitions, overlay, new_side_sha), + _struct_rows(repo, org, ns, changes), ) - # A C++ struct is no definition impact reads, but a line of its body declares in it, - # not in the class or the file around it: `place_lines` reads its rows for that alone - cpp = [p for p in changes if lang_for_path(p) == "cpp"] - read = ( - await repo.functions_for_paths(org, ns, cpp, limit=2000, kinds=("struct",)) if cpp else [] - ) - structs = [r for r in read if str(r.get("kind")) == "struct"] + added_rows = _overlay_added_rows(overlay) touched_rows, gate_touched, unmapped = touched_by_diff( - [*definitions, *structs], changes, new_side=new_side + [*definitions, *structs], changes, new_side=new_side, added=added_rows ) - added_rows = _overlay_added_rows(overlay) causes = [CAUSE_NEW_SIDE_UNREAD] if unread else [] if failed: causes.append(CAUSE_NEW_SIDE_FAILED) @@ -219,12 +213,32 @@ async def _diff_seeds( seed_ids = list(dict.fromkeys(sid for r in touched_rows for sid in r["tier_ids"])) symbol_rows = [r for r in definitions if str(r.get("kind")) != "class"] if added_rows: - touched_rows = [*touched_rows, *added_rows] + # a prototype placed on an added function names it already + held = {(str(r["path"]), str(r["symbol_id"])) for r in touched_rows} + touched_rows = [ + *touched_rows, + *(r for r in added_rows if (str(r["path"]), str(r["symbol_id"])) not in held), + ] seed_ids = list(dict.fromkeys([*seed_ids, *(str(r["symbol_id"]) for r in added_rows)])) symbol_rows = [*symbol_rows, *(s.row() for s in overlay.symbols)] return seed_paths, symbol_rows, touched_rows, seed_ids, gate_rows, causes +async def _struct_rows( + repo: CodeRepo, org: str, ns: str, changes: dict[str, list[Any]] +) -> list[dict[str, Any]]: + """The struct rows of the diff's C++ files. A struct is no definition impact reads, + but a line of its body declares in it, not in the class or the file around it: + `place_lines` reads these rows for that alone.""" + cpp = [p for p in changes if lang_for_path(p) == "cpp"] + if not cpp: + return [] + with code_span("impact.struct_rows", seeds=len(cpp)) as sp: + rows = await repo.functions_for_paths(org, ns, cpp, limit=2000, kinds=("struct",)) + span_attrs(sp, results=len(rows)) + return list(rows) + + async def _new_side( repo: CodeRepo, org: str, diff --git a/tests/unit/test_code_diff_sides.py b/tests/unit/test_code_diff_sides.py index 432ae027116..60954fdb103 100644 --- a/tests/unit/test_code_diff_sides.py +++ b/tests/unit/test_code_diff_sides.py @@ -782,7 +782,12 @@ def _widget_rows() -> list[dict[str, Any]]: def _place_header( - tmp: Path, path: str, before: str, after: str, rows: list[dict[str, Any]] | None = None + tmp: Path, + path: str, + before: str, + after: str, + rows: list[dict[str, Any]] | None = None, + added: list[dict[str, Any]] | None = None, ) -> tuple[list[tuple[int, int, str]] | None, list[str]]: """(the lines git's diff of `path` from `before` to `after` leaves unmapped, the qualified names of the rows its other lines are placed on), the index holding the @@ -800,7 +805,7 @@ def _place_header( ] here = [r for r in rows if r["path"] == path] side = {path: paired_extents(functions, [r for r in here if r["kind"] != "class"], here)} - placement = place_lines(rows, changes, new_side=side) + placement = place_lines(rows, changes, new_side=side, added_functions=added) return placement.unmapped.get(path), sorted(r["qualified_name"] for r in placement.rows) @@ -810,12 +815,17 @@ def _place_header( # a member and a changed default (" int w = 0;\n", " int w = 0;\n int h = 0;\n", ["ui::Widget"]), (" int w = 0;\n", " int w = 1;\n", ["ui::Widget"]), - # a prototype of a function the index holds + # a prototype of a function the index holds, with a trailing comment too ( " void resize(int w);\n", " void resize(int w, int h);\n", ["ui::Widget", "ui::Widget::resize"], ), + ( + " void resize(int w);\n", + " void resize(int w = 1); // in px\n", + ["ui::Widget", "ui::Widget::resize"], + ), # a prototype at file scope, of the function the file of the same stem defines ( "int area(const Widget & x);\n", @@ -879,6 +889,9 @@ def test_a_member_line_or_a_prototype_is_placed_on_what_it_declares( # (its defaults, its parameters) reaches its callers, which no claim on the # class decides (" int w = 0;\n", " int w = 0;\n bool empty() const;\n"), + (" int w = 0;\n", " int w = 0;\n bool empty() const; // cheap\n"), + # a prototype the name read refuses (a braced default) may declare one all the same + (" void resize(int w);\n", " void resize(Size s = {});\n"), # a prototype made virtual, which changes which function a call through a base # reaches, the lines of a prototype spread over lines (its head may be virtual), # a template head's parameter lines, a non-type one among them @@ -964,12 +977,45 @@ def test_a_file_scope_prototype_is_not_placed_on_a_method(tmp_path: Path) -> Non """A free prototype whose only definition of its name in the diff's files is a method of a class they hold declares that method no more than any other: it stays a change.""" path = "src/ui/widget.h" - method = _rows("src/ui/widget.cpp", "namespace ui\n{\nvoid Widget::draw(int s)\n{\n}\n}\n") - rows = [*_rows(path, WIDGET_H), *method] before = WIDGET_H.replace("int area(", "void draw(int scale = 1);\nint area(") after = before.replace("scale = 1", "scale = 2") - unmapped, placed = _place_header(tmp_path, path, before, after, [*rows, *_rows(path, before)]) - assert (unmapped, placed) == ([(16, 16, "removed"), (16, 16, "added")], []) + # a method of a class, of a struct, and of a struct nested in a class, which the + # parser holds no row of + source = "namespace ui\n{\nstruct Calc\n{\n void draw(int s);\n};\nvoid Calc::draw(int s)\n{\n}\n}\n" + for sub, (cpp, structs) in enumerate( + ( + ("namespace ui\n{\nvoid Widget::draw(int s)\n{\n}\n}\n", []), + (source, _structs("src/ui/widget.cpp", source)), + ("namespace ui\n{\nvoid Widget::Options::draw(int s)\n{\n}\n}\n", []), + ) + ): + rows = [*_rows(path, before), *_rows("src/ui/widget.cpp", cpp), *structs] + (tmp_path / str(sub)).mkdir() + got = _place_header(tmp_path / str(sub), path, before, after, rows) + assert got == ([(16, 16, "removed"), (16, 16, "added")], []), sub + + +def test_a_prototype_an_open_pr_adds_is_placed_on_the_function_it_adds(tmp_path: Path) -> None: + """An open PR that adds a method adds its prototype to the class and its body to the + source: the body is the overlay's added function, which the prototype declares, so + the prototype is placed on the class and on it. Without it the line stays a change.""" + path = "src/ui/widget.h" + after = WIDGET_H.replace(" int w = 0;\n", " int w = 0;\n void clear();\n") + clear = { + "symbol_id": "o-clear", + "path": "src/ui/widget.cpp", + "qualified_name": "ui::Widget::clear", + "kind": "function", + "start_line": 30, + "end_line": 32, + "tier": "overlay", + "via": "added", + } + (tmp_path / "a").mkdir() + got = _place_header(tmp_path / "a", path, WIDGET_H, after, added=[clear]) + assert got == (None, ["ui::Widget", "ui::Widget::clear"]) + (tmp_path / "n").mkdir() + assert _place_header(tmp_path / "n", path, WIDGET_H, after) == ([(14, 14, "added")], []) def test_a_line_of_a_struct_body_stays_unmapped(tmp_path: Path) -> None: diff --git a/tests/unit/test_code_review_brief_sections.py b/tests/unit/test_code_review_brief_sections.py index 539fad252a3..77662eadfa1 100644 --- a/tests/unit/test_code_review_brief_sections.py +++ b/tests/unit/test_code_review_brief_sections.py @@ -1403,15 +1403,26 @@ async def __call__(self, op: str, body: dict[str, Any]) -> dict[str, Any]: if side is None: side = self.repo.parent_side if "new_side_sha" in body else self.repo.head_side side = self._paired(side, fns) - touched, _, unmapped = touched_by_diff(fns, changes, new_side=side) + new = [f for f in fns if f["path"] in _NEW_FILES and f["kind"] != "class"] + added = ( + [{**f, "tier": "overlay", "via": "added"} for f in self.added or new] + if self.overlay + else [] + ) + # as impact: a prototype may be placed on a function the PR adds, which is listed + # once + touched, _, unmapped = touched_by_diff(fns, changes, new_side=side, added=added) keys = ("qualified_name", "path", "start_line", "tier") - rows = [{k: t[k] for k in keys} for t in touched] - if self.overlay: - new = [f for f in fns if f["path"] in _NEW_FILES and f["kind"] != "class"] - rows += [ - {**{k: f[k] for k in keys}, "tier": "overlay", "via": "added"} - for f in self.added or new - ] + held = {(t["path"], t["symbol_id"]) for t in touched} + rows = [ + {k: t[k] for k in keys} | ({"via": "added"} if t.get("via") == "added" else {}) + for t in touched + ] + rows += [ + {**{k: f[k] for k in keys}, "via": "added"} + for f in added + if (f["path"], f["symbol_id"]) not in held + ] return { "touched_symbols": rows, "by_hop_counts": {1: 7}, From 1d24eb23463e5a99f4409cde810dd8b15568b43a Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 6 Dec 2026 08:15:27 +0000 Subject: [PATCH 09/16] A file-scope prototype is placed only on a free function the index shows to be one A function in a scope the diff's files show nothing about may be a method of a class declared elsewhere, so a file-scope prototype is placed only on a function at global scope or in a scope that holds a class or struct row and is none itself. The declaration pattern no longer backtracks on a long line that declares nothing. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- docs/features/code-index/history-and-prs.md | 41 ++++++++------- server/code/app/symbol/cpp_members.py | 9 ++-- server/code/app/symbol/diff.py | 56 +++++++++++---------- tests/unit/test_code_diff_sides.py | 31 +++++++++++- 4 files changed, 87 insertions(+), 50 deletions(-) diff --git a/docs/features/code-index/history-and-prs.md b/docs/features/code-index/history-and-prs.md index d80df4d9ff7..c0184953a55 100644 --- a/docs/features/code-index/history-and-prs.md +++ b/docs/features/code-index/history-and-prs.md @@ -415,25 +415,28 @@ uncovered one answers `gaps`. other line (an argument's or a value's), and a line below a blank or comment line, where the brackets open above are not known. - A C++ prototype is placed also on the function it declares, when it is a member line - by the rules above and the diff's files outside tests hold one definition of it: in - a class body the function whose qualified name is the class's and the prototype's; - at file scope a free function of its name (not a method: no class or struct the - index holds names a scope around it; nor one the compiler tier names in an anonymous - namespace) in the same file or a file of the same stem in its directory (`widget.h` - and `widget.cpp`), or a - registration function by the index's registration rule (`registerWidgets`), which - is often declared beside the call that runs it. A prototype whose function the - diff's files do not define stays a change, in a class body too: its defaults and - parameters reach the function's callers, which a claim on the class does not - decide. So does a prototype in a class body when a function of its name sits in a - scope nested in the class, which it may declare instead, and a class-body line that - names something before a `(` but is not read as a prototype (`void f(Size s = -{});`). A trailing `//` comment is not read. The namespace a file-scope prototype - sits in is not read either: a free function of its name in another namespace of the - same-stem file is its candidate as well. Two definitions of the - name under different qualified names leave it a change, and so does a file-scope - line whose parentheses start with a literal (`static const std::regex re("a+");`), - a constant built by a constructor. A registration statement inside a registration + by the rules above and the diff's files outside tests hold definitions of one + qualified name for it: in a class body the function whose qualified name is the + class's and the prototype's; at file scope a free function of its name in the same + file or a file of the same stem in its directory (`widget.h` and `widget.cpp`), or a + registration function by the index's registration rule (`registerWidgets`), which is + often declared beside the call that runs it. A free function is one at global scope or + in a scope the index shows to be a namespace: a scope that holds a class or struct row + and is none itself (a class whose own row sits outside the diff's files, with a nested + class's row in them, reads as one). A function in a scope the diff's files show + nothing about may be a method of a class declared elsewhere, so a file-scope prototype + is not placed on it, and one the compiler tier names in an anonymous namespace is not + placed either. A prototype whose function the diff's files do not define stays a + change, in a class body too: its defaults and parameters reach the function's callers, + which a claim on the class does not decide. So does a prototype in a class body when a + function of its name sits in a scope nested in the class, which it may declare + instead, and a class-body line that names something before a `(` but is not read as a + prototype (a default argument written with braces). A trailing `//` comment is not + read. The namespace a file-scope prototype sits in is not read either: a free function + of its name in another namespace of the same-stem file is its candidate as well. + Definitions under two qualified names leave it a change, and so does a file-scope line + whose parentheses start with a literal (`static const std::regex re("a+");`), a + constant built by a constructor. A registration statement inside a registration function's body is that function's line already. - The rules read the changed line, the line above it and the index's rows, and they are as good as those rows. A line of a method the parser did not read as one (a head diff --git a/server/code/app/symbol/cpp_members.py b/server/code/app/symbol/cpp_members.py index 73dd53ea91b..2f7d2707c85 100644 --- a/server/code/app/symbol/cpp_members.py +++ b/server/code/app/symbol/cpp_members.py @@ -16,9 +16,12 @@ import re # A C++ member declaration: one word or more of its type and specifiers (names, `::`, -# `<>`, `,`, `*`, `&`, `[]`), then its declarator's name, then what may follow a name in -# a declaration (`;`, `=`, `(`, `{`, `[`, `,`, or `:` of a bit-field). -_DECLARATION = re.compile(r"\s*(?:[A-Za-z_][\w:<>,*&\[\]]*[\s*&]+)+~?[A-Za-z_]\w*\s*[;=({\[,:]") +# `<>`, `,` and `[]`), each followed by spaces, `*` or `&`, then its declarator's name, +# then what may follow a name in a declaration (`;`, `=`, `(`, `{`, `[`, `,`, or `:` of +# a bit-field). A word holds none of the characters that follow it, so a line splits +# into words one way and a line that is no declaration fails in time linear in it; a +# type holding `*` inside its brackets (`std::vector`) is not read. +_DECLARATION = re.compile(r"\s*(?:[A-Za-z_][\w:<>,\[\]]*[\s*&]+)+~?[A-Za-z_]\w*\s*[;=({\[,:]") # A special member's head, which names no type: `explicit Widget(int w);`, `~Widget();`. _SPECIAL = r"\s*(?:(?:explicit|constexpr|inline|virtual)\s+)*~?{name}\s*\(" # What ends a prototype without a body: `= default;`, `= delete;`, `= 0;`. diff --git a/server/code/app/symbol/diff.py b/server/code/app/symbol/diff.py index 2d943812ada..22c56ef4340 100644 --- a/server/code/app/symbol/diff.py +++ b/server/code/app/symbol/diff.py @@ -793,8 +793,8 @@ class body touches the class. A test file's lines are not counted: its functions A C++ `struct` row in `definitions` is read only here, as a scope no claim is read for: a line its body holds, at file scope or in a class, is placed on nothing. The - functions an open PR adds (`added_functions`, its overlay's) are what a prototype the PR adds - with them declares: one is placed on them as on a definition the index holds.""" + functions an open PR adds (`added_functions`, its overlay's) are what a prototype the + PR adds with them declares: one is placed on them as on a definition the index holds.""" by_path: dict[str, list[dict[str, Any]]] = {} structs: dict[str, list[dict[str, Any]]] = {} for r in definitions: @@ -960,7 +960,7 @@ class body is one scope its indentation keeps, and an attribute or docstring lin return [] if names_call(t) else [holder] # a prototype changes what calls of its function do (a default, a parameter): # the class's claim decides it only with the function's - declared = functions.named([*owner, name]) + declared = functions.method_rows([*owner, name]) return [holder, *declared] if declared and not functions.nested(owner, name) else [] if holder is not None or not member_line(t): return [] @@ -969,8 +969,8 @@ class body is one scope its indentation keeps, and an attribute or docstring lin return [] stem = _stem(path) registration = is_registration_caller(name) - return functions.named( - [name], lambda p: registration or p == path or _same_unit(p, path, stem), whole=False + return functions.free_rows( + name, lambda p: registration or p == path or _same_unit(p, path, stem) ) @@ -1047,6 +1047,15 @@ def __init__(self, definitions: list[dict[str, Any]], scopes: list[dict[str, Any for r in [*definitions, *scopes] if str(r.get("kind")) in ("class", "struct") } + # the scopes the index shows to be namespaces: one that holds a class or a struct + # and is none itself. A scope nothing shows either way may be a class whose row + # sits in a file outside the diff. + held = { + "::".join(q[:k]) + for q in (str(c).split("::")[:-1] for c in self.classes) + for k in range(1, len(q) + 1) + } + self.namespaces = held - self.classes for r in definitions: if ( str(r.get("kind")) != "class" @@ -1056,11 +1065,12 @@ def __init__(self, definitions: list[dict[str, Any]], scopes: list[dict[str, Any self.by_name.setdefault(_parts(str(r["qualified_name"]))[-1], []).append(r) def _free(self, r: dict[str, Any]) -> bool: - """Whether a function row is a free function: no class or struct the index holds - names a scope around it (`ui::Pool::Options::reset` is a method of `ui::Pool`'s - even when the parser holds no row of `Options`).""" + """Whether a function row is known to be a free function: at global scope, or in + a scope the index shows to be a namespace (`namespaces`). `ui::Widget::draw` with + no row of `ui::Widget` in the diff's files is no free function, and neither is + `ui::Pool::Options::reset`, whose `ui::Pool` is a class.""" q = _parts(str(r["qualified_name"]))[:-1] - return not any("::".join(q[:k]) in self.classes for k in range(1, len(q) + 1)) + return not q or "::".join(q) in self.namespaces def nested(self, owner: list[str], name: str) -> bool: """Whether a function `name` sits in a scope inside class `owner` (a struct or a @@ -1071,23 +1081,17 @@ class the index serves no row of): a prototype of that name in the class's for q in (_parts(str(r["qualified_name"])) for r in self.by_name.get(name, [])) ) - def named( - self, - parts: list[str], - path_ok: Callable[[str], bool] | None = None, - *, - whole: bool = True, - ) -> list[dict[str, Any]]: - """The rows whose qualified name is `parts` (with `whole`), or else ends with its - one part and is a free function's (`_free`), in - files `path_ok` accepts, when they share one qualified name (overloads are one - subject of a claim), else none.""" - rows = [ - r - for r in self.by_name.get(parts[-1], []) - if (_parts(str(r["qualified_name"])) == parts if whole else self._free(r)) - and (path_ok is None or path_ok(str(r["path"]))) - ] + def method_rows(self, parts: list[str]) -> list[dict[str, Any]]: + """The rows whose qualified name is `parts`: a method of one class, its overloads + one subject of a claim.""" + rows = self.by_name.get(parts[-1], []) + return [r for r in rows if _parts(str(r["qualified_name"])) == parts] + + def free_rows(self, name: str, path_ok: Callable[[str], bool]) -> list[dict[str, Any]]: + """The free functions (`_free`) named `name` in files `path_ok` accepts, when they + share one qualified name (overloads are one subject of a claim), else none.""" + named = self.by_name.get(name, []) + rows = [r for r in named if self._free(r) and path_ok(str(r["path"]))] return rows if len({str(r["qualified_name"]) for r in rows}) == 1 else [] diff --git a/tests/unit/test_code_diff_sides.py b/tests/unit/test_code_diff_sides.py index 60954fdb103..2b330c43b1f 100644 --- a/tests/unit/test_code_diff_sides.py +++ b/tests/unit/test_code_diff_sides.py @@ -933,13 +933,17 @@ def test_a_file_scope_prototype_is_placed_only_on_one_definition(tmp_path: Path) path = "src/ui/widget.h" changed = WIDGET_H.replace("x);\n", "x, int scale);\n") impl = "namespace ui::impl\n{\nint area(int x)\n{\n}\n}\n" + # a free function at global scope beside `ui::area`: two qualified names + two = "int area(int x)\n{\n}\n" anonymous = { **_rows("src/ui/widget.cpp", impl)[0], "qualified_name": "ui::$anonymous_namespace_src/ui/widget.cpp::area", } for sub, (other, want) in enumerate( ( - (_rows("src/ui/widget.cpp", impl), [(16, 16, "removed"), (16, 16, "added")]), + (_rows("src/ui/widget.cpp", two), [(16, 16, "removed"), (16, 16, "added")]), + # a scope nothing in the diff's files shows to be a namespace may be a class + (_rows("src/ui/widget.cpp", impl), None), (_rows("src/ui/impl/widget.cpp", impl), None), ([anonymous], None), ) @@ -975,7 +979,9 @@ def test_a_prototype_is_placed_on_the_function_of_its_class_outside_tests( def test_a_file_scope_prototype_is_not_placed_on_a_method(tmp_path: Path) -> None: """A free prototype whose only definition of its name in the diff's files is a method - of a class they hold declares that method no more than any other: it stays a change.""" + declares that method no more than any other: it stays a change, whether the diff's + files hold the method's class (or struct) or not, as when a diff changes a source + file alone and the class sits in its unchanged header.""" path = "src/ui/widget.h" before = WIDGET_H.replace("int area(", "void draw(int scale = 1);\nint area(") after = before.replace("scale = 1", "scale = 2") @@ -993,6 +999,27 @@ def test_a_file_scope_prototype_is_not_placed_on_a_method(tmp_path: Path) -> Non (tmp_path / str(sub)).mkdir() got = _place_header(tmp_path / str(sub), path, before, after, rows) assert got == ([(16, 16, "removed"), (16, 16, "added")], []), sub + # a source-only diff: the prototype and the method in `widget.cpp`, no class row + source = "namespace ui\n{\nvoid draw(int scale = 1);\nvoid Widget::draw(int s)\n{\n}\n}\n" + cpp = "src/ui/widget.cpp" + (tmp_path / "cpp").mkdir() + changed = source.replace("scale = 1", "scale = 2") + got = _place_header(tmp_path / "cpp", cpp, source, changed, _rows(cpp, source)) + assert got == ([(3, 3, "removed"), (3, 3, "added")], []) + + +def test_reading_a_long_line_that_declares_nothing_costs_time_linear_in_it() -> None: + """A changed line of many words and `*`s that is no declaration fails the member-line + and prototype reads in time linear in its length: its words split one way.""" + from server.code.app.symbol.cpp_members import declared_name, member_line, names_call + from tests.unit.code_fixtures import grows_linearly + + def run(n: int) -> None: + for text in ("a*" * n + "-1;", "a " * n + "-1;", "a&" * n + "("): + assert not member_line(text) and not declared_name(text, in_class=True) + names_call(text) + + grows_linearly(run, 2_000, 8_000) def test_a_prototype_an_open_pr_adds_is_placed_on_the_function_it_adds(tmp_path: Path) -> None: From ae85ba991ea7b2e8e4487417843bbf9f5b54212a Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 6 Dec 2026 09:38:57 +0000 Subject: [PATCH 10/16] The C++ parser holds a row of a nested type and of a method under #elif A class or struct defined in a class body or a variable declaration, and a method under `#elif`, got no row, so a statement in a nested type's inline method read as a line of the outer class's body and was placed on it. They are rows now, so such a line is its method's and a nested struct's body stays a change. This changes C++ extraction: the symbol stage re-runs for C++ files in every indexed repository. The docs correct what the index's Python reads cover, and the placement loop names its entries. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- docs/features/code-index/history-and-prs.md | 27 +++--- server/code/app/symbol/diff.py | 62 ++++++++------ server/code/domain/extract/treesitter.py | 93 ++++++++++++--------- tests/unit/test_code_cpp_nested_types.py | 58 +++++++++++++ tests/unit/test_code_diff_sides.py | 33 ++++---- 5 files changed, 181 insertions(+), 92 deletions(-) create mode 100644 tests/unit/test_code_cpp_nested_types.py diff --git a/docs/features/code-index/history-and-prs.md b/docs/features/code-index/history-and-prs.md index c0184953a55..0e9534a1620 100644 --- a/docs/features/code-index/history-and-prs.md +++ b/docs/features/code-index/history-and-prs.md @@ -438,23 +438,28 @@ uncovered one answers `gaps`. whose parentheses start with a literal (`static const std::regex re("a+");`), a constant built by a constructor. A registration statement inside a registration function's body is that function's line already. -- The rules read the changed line, the line above it and the index's rows, and they - are as good as those rows. A line of a method the parser did not read as one (a head +- The rules read the changed line, the line above it and the index's rows, and they are + as good as those rows. A line of a method the parser did not read as one (a head spelled with a macro it cannot expand) sits in the class body by the rows, so a declaration in its body (`size_t n = rows.size();`) reads as a member line and is - placed on the class that holds the method: a claim on the class then decides it. A - C++ `struct` is no definition the brief claims, and `code.impact` reads its rows for - placement alone: a line of the body of a struct the index holds a row of stays a - change. The parser holds no row of a struct nested in a class, so a data member of - one reads as a member of the class around it. + placed on the class that holds the method: a claim on the class then decides it. The + parser holds a row of each named class or struct, a nested one and one defined in a + variable declaration included, and of each method under `#if`, `#elif` and `#else`; an + unnamed one (`struct { int a; } pair;`) has none, so its body reads as the scope + around it, a statement in an inline method of it too. A C++ `struct` is no definition + the brief claims, and `code.impact` reads its rows for placement alone: a line of the + body of a struct the index holds a row of stays a change. - No line is placed that a macro or a statement continues (the line above it ends with `\` or `??/`), that starts a run the hunk shows no line above (a diff with no context), or that sits in a function the new side pairs with no row, or on a side nobody read. -A constant or a static at file scope stays a change: the index links a C++ or Python -variable to none of its readers, so no claim could decide it. So do an `#include`, a -`using` line, a namespace line and a brace. Shell scripts have no class and no -prototype, and the other languages' lines in no function stay changes as before. +A constant or a static at file scope stays a change: the index links no C++ variable to +its readers, and a Python `reads` edge records an attribute read (`config.LIMIT`, a +typed receiver's field) but not a bare name read in its module or after `from config +import LIMIT`, so the readers it holds are not all of them and no claim on them could +decide the line. So do an `#include`, a `using` line, a namespace line and a brace. +Shell scripts have no class and no prototype, and the other languages' lines in no +function stay changes as before. The symbols section lists the wiring the PR adds as counts in `collapsed`, not as rows. The fold is how the section shows them: their coverage claims and regression records diff --git a/server/code/app/symbol/diff.py b/server/code/app/symbol/diff.py index 22c56ef4340..1eb9492dcbf 100644 --- a/server/code/app/symbol/diff.py +++ b/server/code/app/symbol/diff.py @@ -756,6 +756,15 @@ class Placement(NamedTuple): rows: list[dict[str, Any]] +class _Loose(NamedTuple): + """A changed line range outside every function, the class that holds it (None at file + scope) and whether `_place_member` may place it.""" + + lines: tuple[int, int, Side] + holder: dict[str, Any] | None + placeable: bool + + def place_lines( definitions: list[dict[str, Any]], changes: dict[str, list[Hunk]], @@ -835,15 +844,13 @@ class body touches the class. A test file's lines are not counted: its functions missed += _added(hunk, seeds, inert_new) removed = cr.merge_ranges(r for h in by_lines for r in h.removed) inside = _clip(removed, spans.covered) - # A changed line outside every function, with the class that holds it or None at - # file scope, and whether `_place_member` may place it - loose: list[tuple[tuple[int, int, Side], dict[str, Any] | None, bool]] = [ - (m, None, True) for m in _changed(_outside(removed, inside), keys, inert_old) + loose = [ + _Loose(m, None, True) for m in _changed(_outside(removed, inside), keys, inert_old) ] lines = [n for a, b in inside for n in range(a, b + 1)] owners = spans.owners(lines) loose += [ - ((n, n, "removed"), owners[n], True) + _Loose((n, n, "removed"), owners[n], True) for n in lines if str(owners[n].get("kind")) == "class" and n not in inert_old ] @@ -854,9 +861,9 @@ class body touches the class. A test file's lines are not counted: its functions run_of = {b.new + k: b.new for h in by_lines for b in h.blocks for k in range(len(b.added))} for hunk in by_lines: loose += [ - (m, around[run_of[m[0]]], True) + _Loose(m, around[run_of[m[0]]], True) if seeds is not None and hunk.blocks and m[0] not in seeds - else (m, None, False) + else _Loose(m, None, False) for m in _added(hunk, seeds, inert_new) ] if p in structs: @@ -865,44 +872,49 @@ class body touches the class. A test file's lines are not counted: its functions "removed": (text, cont_old, unseen_old, above_old), "added": (added, cont_new, unseen_new, above_new), } - for m, holder, placeable in loose: - lines_of, cont, unseen, above = context.get(m[2], ({}, frozenset(), frozenset(), {})) + for item in loose: + first, last, side = item.lines + lines_of, cont, unseen, above = context.get(side, ({}, frozenset(), frozenset(), {})) rows = ( - _place_member(m[0], holder, p, functions, (lines_of, above), cont, unseen) - if placeable and m[0] == m[1] + _place_member(first, item.holder, p, functions, (lines_of, above), cont, unseen) + if item.placeable and first == last else [] ) if rows: placed.update((str(r["symbol_id"]), r) for r in rows) else: - missed.append(m) + missed.append(item.lines) if missed: out[p] = missed return Placement(out, list(placed.values())) def _outside_structs( - loose: list[tuple[tuple[int, int, Side], dict[str, Any] | None, bool]], + loose: list[_Loose], structs: list[dict[str, Any]], hunks: list[Hunk], by_lines: list[Hunk], run_of: dict[int, int], -) -> list[tuple[tuple[int, int, Side], dict[str, Any] | None, bool]]: +) -> list[_Loose]: """`loose` with each line a struct's body holds inside its holder (or at file scope) made unplaceable: the struct is the scope it declares in, and no row of it is read. A removed line is held by the struct whose old extent holds it, an added one by the struct that holds its run's old lines on both sides (`_FileSpans.around`).""" spans = _FileSpans(structs, hunks, indented=False) - old = spans.owners(sorted({m[0] for m, _, ok in loose if ok and m[2] == "removed"})) + old = spans.owners( + sorted({x.lines[0] for x in loose if x.placeable and x.lines[2] == "removed"}) + ) new = spans.around([b for h in by_lines for b in h.blocks if b.added]) - def in_struct(m: tuple[int, int, Side], holder: dict[str, Any] | None) -> bool: - s = old.get(m[0]) if m[2] == "removed" else new.get(run_of.get(m[0], -1)) + def in_struct(x: _Loose) -> bool: + first, _, side = x.lines + s = old.get(first) if side == "removed" else new.get(run_of.get(first, -1)) if s is None: return False - return holder is None or _span(holder)[0] <= _span(s)[0] <= _span(s)[1] <= _span(holder)[1] + h = x.holder + return h is None or _span(h)[0] <= _span(s)[0] <= _span(s)[1] <= _span(h)[1] - return [(m, h, ok and not in_struct(m, h)) for m, h, ok in loose] + return [x._replace(placeable=x.placeable and not in_struct(x)) for x in loose] def _place_member( @@ -925,12 +937,12 @@ def _place_member( class (`holder`), and a prototype there also on the function it declares (`cpp_members.declared_name`): the definitions of the diff's files whose qualified name is the class's and the prototype's. A prototype of a function they do not hold - stays a change. A prototype at file scope (`holder` None) is - placed on the function of its name in the diff's files that sits in the same file or - one of the same stem (`widget.h` and `widget.cpp`), or that is a registration - function (`is_registration_caller`, often declared beside the call that runs it): - only when they name one definition, and not a method of a class the diff's files - hold: a prototype outside a class declares no method. A test file's definitions are + stays a change. A prototype at file scope (`holder` None) is placed on the free + function of its name (`_Functions.free_rows`) in the diff's files that sits in the + same file or one of the same stem (`widget.h` and `widget.cpp`), or that is a + registration function (`is_registration_caller`, often declared beside the call that + runs it), when they share one qualified name: a prototype outside a class declares + no method. A test file's definitions are never one: a test does not define what the code under test declares. In Python a class body is one scope its indentation keeps, and an attribute or docstring line of it outside every method is placed on the class (`_python_member_line`); a module line diff --git a/server/code/domain/extract/treesitter.py b/server/code/domain/extract/treesitter.py index 422ae74181a..4b599b178e1 100644 --- a/server/code/domain/extract/treesitter.py +++ b/server/code/domain/extract/treesitter.py @@ -298,6 +298,47 @@ def parse_cpp(path: str, source: bytes) -> ParsedFile: pf.includes = _INCLUDE_RE.findall(source.decode("utf-8", "replace")) + def walk_class(child: Any, scope: tuple[str, ...]) -> None: + t = child.type + name_node = child.child_by_field_name("name") + body = child.child_by_field_name("body") + # Body-less = forward declaration (`class Field;`). NEVER + # index it: it shares the RMT key with the real definition + # (same qualified_name, empty signature), so whichever row + # lands last would clobber the other — a forward decl in an + # unrelated header would hide the real class. + if name_node is not None and body is not None: + cls_name = node_text(name_node, source) + qname = "::".join(scope + (cls_name,)) + kind = "class" if t == "class_specifier" else "struct" + pf.symbols.append( + Symbol( + qualified_name=qname, + name=cls_name.split("::")[-1], + kind=kind, + signature="", + path=path, + start_line=child.start_point[0] + 1, + end_line=child.end_point[0] + 1, + doc_comment=_doc_comment(child, source), + ) + ) + bases = next( + (c for c in child.named_children if c.type == "base_class_clause"), + None, + ) + if bases is not None: + for b in bases.named_children: + if b.type in { + "type_identifier", "qualified_identifier", "template_type", + }: + base = node_text(b, source) + base = re.sub(r"<.*", "", base).strip() + if base: + pf.inherits.append((qname, base)) + if body is not None: + walk(body, scope + (cls_name,)) + def walk(node: Any, scope: tuple[str, ...]) -> None: for child in node.named_children: t = child.type @@ -308,45 +349,18 @@ def walk(node: Any, scope: tuple[str, ...]) -> None: if body is not None: walk(body, scope + tuple(ns.split("::")) if ns else scope) continue + if t in {"field_declaration", "declaration"}: + # A class or struct defined in a member or a variable declaration + # (`struct Options { ... };` in a class body, `struct S { ... } s;`) is + # the declaration's type: its body holds members and methods of its own. + type_node = child.child_by_field_name("type") + if type_node is not None and type_node.type in { + "class_specifier", "struct_specifier", + }: + walk_class(type_node, scope) + continue if t in {"class_specifier", "struct_specifier"}: - name_node = child.child_by_field_name("name") - body = child.child_by_field_name("body") - # Body-less = forward declaration (`class Field;`). NEVER - # index it: it shares the RMT key with the real definition - # (same qualified_name, empty signature), so whichever row - # lands last would clobber the other — a forward decl in an - # unrelated header would hide the real class. - if name_node is not None and body is not None: - cls_name = node_text(name_node, source) - qname = "::".join(scope + (cls_name,)) - kind = "class" if t == "class_specifier" else "struct" - pf.symbols.append( - Symbol( - qualified_name=qname, - name=cls_name.split("::")[-1], - kind=kind, - signature="", - path=path, - start_line=child.start_point[0] + 1, - end_line=child.end_point[0] + 1, - doc_comment=_doc_comment(child, source), - ) - ) - bases = next( - (c for c in child.named_children if c.type == "base_class_clause"), - None, - ) - if bases is not None: - for b in bases.named_children: - if b.type in { - "type_identifier", "qualified_identifier", "template_type", - }: - base = node_text(b, source) - base = re.sub(r"<.*", "", base).strip() - if base: - pf.inherits.append((qname, base)) - if body is not None: - walk(body, scope + (cls_name,)) + walk_class(child, scope) continue if t == "enum_specifier": name_node = child.child_by_field_name("name") @@ -436,7 +450,8 @@ def walk(node: Any, scope: tuple[str, ...]) -> None: continue if t in { "linkage_specification", "declaration_list", - "preproc_ifdef", "preproc_if", "preproc_else", + "preproc_ifdef", "preproc_if", "preproc_else", "preproc_elif", + "preproc_elifdef", }: walk(child, scope) continue diff --git a/tests/unit/test_code_cpp_nested_types.py b/tests/unit/test_code_cpp_nested_types.py new file mode 100644 index 00000000000..fa258021245 --- /dev/null +++ b/tests/unit/test_code_cpp_nested_types.py @@ -0,0 +1,58 @@ +"""The C++ parser's rows for a type defined inside a declaration and for `#elif` branches.""" + +from __future__ import annotations + +from server.code.domain.extract.treesitter import parse_cpp + +HEADER = b"""namespace ui +{ +class Pool +{ +public: + struct Options + { + int size = 0; + void reset() { size = 0; } + }; + class Inner + { + void go() {} + }; + void add() {} +#if defined(A) + void a() {} +#elif defined(B) + void b() {} +#endif +}; + +struct Stats +{ + void clear() {} +} stats; + +class Forward; +} +""" + + +def test_a_nested_type_and_an_elif_branch_get_rows() -> None: + """A class or struct defined in a class body or a variable declaration is a row with + its methods, and a method under `#elif` is one too: otherwise their lines read as the + outer class's. A forward declaration stays no row.""" + rows = { + (s.kind, s.qualified_name, s.start_line, s.end_line) + for s in parse_cpp("pool.h", HEADER).symbols + } + assert rows == { + ("class", "ui::Pool", 3, 21), + ("struct", "ui::Pool::Options", 6, 10), + ("function", "ui::Pool::Options::reset", 9, 9), + ("class", "ui::Pool::Inner", 11, 14), + ("function", "ui::Pool::Inner::go", 13, 13), + ("function", "ui::Pool::add", 15, 15), + ("function", "ui::Pool::a", 17, 17), + ("function", "ui::Pool::b", 19, 19), + ("struct", "ui::Stats", 23, 26), + ("function", "ui::Stats::clear", 25, 25), + } diff --git a/tests/unit/test_code_diff_sides.py b/tests/unit/test_code_diff_sides.py index 2b330c43b1f..fe645bb1024 100644 --- a/tests/unit/test_code_diff_sides.py +++ b/tests/unit/test_code_diff_sides.py @@ -1047,14 +1047,14 @@ def test_a_prototype_an_open_pr_adds_is_placed_on_the_function_it_adds(tmp_path: def test_a_line_of_a_struct_body_stays_unmapped(tmp_path: Path) -> None: """A struct is a scope no claim is read for: a member or a prototype of a struct the - index holds a row of stays a change. The parser holds none for a struct nested in a - class, whose body reads as the class's: a prototype there is no member line of the - class when a function of its name sits in a scope inside the class, which it may - declare; a data member there is the class's (the documented limit).""" + index holds a row of stays a change, a struct nested in a class too. A statement in an + inline method of a nested type is that method's line, never the outer class's.""" path = "src/ui/pool.h" header = ( "namespace ui\n{\nclass Pool\n{\npublic:\n struct Options\n {\n" - " int size = 0;\n void reset();\n };\n void reset();\n};\n\n" + " int size = 0;\n void reset();\n };\n void reset();\n" + " class Inner\n {\n void go()\n {\n" + " int n = 0;\n }\n };\n};\n\n" "struct Stats\n{\n int hits = 0;\n void reset();\n};\n}\n" ) source = ( @@ -1063,25 +1063,24 @@ class when a function of its name sits in a scope inside the class, which it may ) rows = [*_rows(path, header), *_rows("src/ui/pool.cpp", source)] structs = _structs(path, header) - assert {r["qualified_name"] for r in structs} == {"ui::Stats"} - for sub, (old, new, line, placed) in enumerate( + assert {r["qualified_name"] for r in structs} == {"ui::Pool::Options", "ui::Stats"} + for sub, (old, new, line) in enumerate( ( - (" void reset();", " void reset(bool hard = true);", 9, None), - (" void reset();\n};\n}", " void reset(bool hard = true);\n};\n}", 17, None), - (" int hits = 0;", " int hits = 1;", 16, None), - (" int size = 0;", " int size = 4;", 8, ["ui::Pool"]), + (" void reset();", " void reset(bool hard = true);", 9), + (" void reset();\n};\n}", " void reset(bool hard = true);\n};\n}", 24), + (" int hits = 0;", " int hits = 1;", 23), + (" int size = 0;", " int size = 4;", 8), ) ): (tmp_path / str(sub)).mkdir() after = header.replace(old, new) assert after != header got = _place_header(tmp_path / str(sub), path, header, after, [*rows, *structs]) - want = ( - ([(line, line, "removed"), (line, line, "added")], []) - if placed is None - else (None, placed) - ) - assert got == want, old + assert got == ([(line, line, "removed"), (line, line, "added")], []), old + (tmp_path / "stmt").mkdir() + after = header.replace("int n = 0;", "int n = 1;") + got = _place_header(tmp_path / "stmt", path, header, after, [*rows, *structs]) + assert got == (None, []), "a line the method ui::Pool::Inner::go holds" def test_a_member_below_a_line_it_continues_stays_unmapped(tmp_path: Path) -> None: From 9e318340af77ba51da5fd1c897cd59a4639018f7 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 6 Dec 2026 09:49:46 +0000 Subject: [PATCH 11/16] A type defined in a typedef gets a row, and a nested type keeps its doc comment A struct or class defined in a typedef is a row like one defined in a member or a variable declaration, and its doc comment is the one above the declaration. A pure-virtual method returning an elaborated type keeps its row: only a type with a body is walked as a class. A member line of a nested class is placed on the nested class. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- docs/features/code-index/history-and-prs.md | 10 ++--- server/code/app/symbol/diff.py | 18 ++++----- server/code/domain/extract/treesitter.py | 27 +++++++------ tests/unit/test_code_cpp_nested_types.py | 44 +++++++++++++-------- tests/unit/test_code_diff_sides.py | 25 +++++++++++- 5 files changed, 79 insertions(+), 45 deletions(-) diff --git a/docs/features/code-index/history-and-prs.md b/docs/features/code-index/history-and-prs.md index 0e9534a1620..483c754e0df 100644 --- a/docs/features/code-index/history-and-prs.md +++ b/docs/features/code-index/history-and-prs.md @@ -444,11 +444,11 @@ uncovered one answers `gaps`. declaration in its body (`size_t n = rows.size();`) reads as a member line and is placed on the class that holds the method: a claim on the class then decides it. The parser holds a row of each named class or struct, a nested one and one defined in a - variable declaration included, and of each method under `#if`, `#elif` and `#else`; an - unnamed one (`struct { int a; } pair;`) has none, so its body reads as the scope - around it, a statement in an inline method of it too. A C++ `struct` is no definition - the brief claims, and `code.impact` reads its rows for placement alone: a line of the - body of a struct the index holds a row of stays a change. + variable declaration or a `typedef` included, and of each method under `#if`, `#elif` + and `#else`; an unnamed one (`struct { int a; } pair;`) has none, so its body reads as + the scope around it, a statement in an inline method of it too. A C++ `struct` is no + definition the brief claims, and `code.impact` reads its rows for placement alone: a + line of the body of a struct the index holds a row of stays a change. - No line is placed that a macro or a statement continues (the line above it ends with `\` or `??/`), that starts a run the hunk shows no line above (a diff with no context), or that sits in a function the new side pairs with no row, or on a side nobody read. diff --git a/server/code/app/symbol/diff.py b/server/code/app/symbol/diff.py index 1eb9492dcbf..3277a991db1 100644 --- a/server/code/app/symbol/diff.py +++ b/server/code/app/symbol/diff.py @@ -942,12 +942,11 @@ class (`holder`), and a prototype there also on the function it declares same file or one of the same stem (`widget.h` and `widget.cpp`), or that is a registration function (`is_registration_caller`, often declared beside the call that runs it), when they share one qualified name: a prototype outside a class declares - no method. A test file's definitions are - never one: a test does not define what the code under test declares. In Python a - class body is one scope its indentation keeps, and an attribute or docstring line of - it outside every method is placed on the class (`_python_member_line`); a module line - is placed on nothing, as a shell line is: a shell script has no class and no - prototype.""" + no method. A test file's definitions are never one: a test does not define what the + code under test declares. In Python a class body is one scope its indentation keeps, + and an attribute or docstring line of it outside every method is placed on the class + (`_python_member_line`); a module line is placed on nothing, as a shell line is: a + shell script has no class and no prototype.""" lang = lang_for_path(path) lines, above = side t = lines.get(n) @@ -1085,9 +1084,10 @@ def _free(self, r: dict[str, Any]) -> bool: return not q or "::".join(q) in self.namespaces def nested(self, owner: list[str], name: str) -> bool: - """Whether a function `name` sits in a scope inside class `owner` (a struct or a - class the index serves no row of): a prototype of that name in the class's - body may declare it rather than the class's own.""" + """Whether a function `name` sits in a scope inside class `owner` (a nested class + or struct, whose row may sit outside the diff's files or be a struct row, which + this index does not hold): a prototype of that name in the class's body may + declare it rather than the class's own.""" return any( len(q) > len(owner) + 1 and q[: len(owner)] == owner for q in (_parts(str(r["qualified_name"])) for r in self.by_name.get(name, [])) diff --git a/server/code/domain/extract/treesitter.py b/server/code/domain/extract/treesitter.py index 4b599b178e1..c4266311f4e 100644 --- a/server/code/domain/extract/treesitter.py +++ b/server/code/domain/extract/treesitter.py @@ -298,7 +298,9 @@ def parse_cpp(path: str, source: bytes) -> ParsedFile: pf.includes = _INCLUDE_RE.findall(source.decode("utf-8", "replace")) - def walk_class(child: Any, scope: tuple[str, ...]) -> None: + def walk_class(child: Any, scope: tuple[str, ...], outer: Any = None) -> None: + # `outer`: the declaration a class defined in it is the type of, whose doc comment + # is the class's t = child.type name_node = child.child_by_field_name("name") body = child.child_by_field_name("body") @@ -320,7 +322,7 @@ def walk_class(child: Any, scope: tuple[str, ...]) -> None: path=path, start_line=child.start_point[0] + 1, end_line=child.end_point[0] + 1, - doc_comment=_doc_comment(child, source), + doc_comment=_doc_comment(outer or child, source), ) ) bases = next( @@ -336,8 +338,7 @@ def walk_class(child: Any, scope: tuple[str, ...]) -> None: base = re.sub(r"<.*", "", base).strip() if base: pf.inherits.append((qname, base)) - if body is not None: - walk(body, scope + (cls_name,)) + walk(body, scope + (cls_name,)) def walk(node: Any, scope: tuple[str, ...]) -> None: for child in node.named_children: @@ -349,15 +350,17 @@ def walk(node: Any, scope: tuple[str, ...]) -> None: if body is not None: walk(body, scope + tuple(ns.split("::")) if ns else scope) continue - if t in {"field_declaration", "declaration"}: - # A class or struct defined in a member or a variable declaration - # (`struct Options { ... };` in a class body, `struct S { ... } s;`) is - # the declaration's type: its body holds members and methods of its own. + if t in {"field_declaration", "declaration", "type_definition"}: + # A class or struct defined in a member, a variable declaration or a + # typedef (`struct Options { ... };` in a class body, `struct S { ... } s;`) + # is the declaration's type: its body holds members and methods of its own. type_node = child.child_by_field_name("type") - if type_node is not None and type_node.type in { - "class_specifier", "struct_specifier", - }: - walk_class(type_node, scope) + if ( + type_node is not None + and type_node.type in {"class_specifier", "struct_specifier"} + and type_node.child_by_field_name("body") is not None + ): + walk_class(type_node, scope, child) continue if t in {"class_specifier", "struct_specifier"}: walk_class(child, scope) diff --git a/tests/unit/test_code_cpp_nested_types.py b/tests/unit/test_code_cpp_nested_types.py index fa258021245..177e67e7f48 100644 --- a/tests/unit/test_code_cpp_nested_types.py +++ b/tests/unit/test_code_cpp_nested_types.py @@ -9,6 +9,7 @@ class Pool { public: + /// The options of a pool. struct Options { int size = 0; @@ -19,6 +20,11 @@ class Inner void go() {} }; void add() {} + virtual struct Result * make() = 0; + typedef struct Slot + { + int id; + } Slot; #if defined(A) void a() {} #elif defined(B) @@ -37,22 +43,26 @@ class Forward; def test_a_nested_type_and_an_elif_branch_get_rows() -> None: - """A class or struct defined in a class body or a variable declaration is a row with - its methods, and a method under `#elif` is one too: otherwise their lines read as the - outer class's. A forward declaration stays no row.""" - rows = { - (s.kind, s.qualified_name, s.start_line, s.end_line) - for s in parse_cpp("pool.h", HEADER).symbols - } + """A class or struct defined in a class body, a variable declaration or a typedef is a + row with its methods, and a method under `#elif` is one too: otherwise their lines + read as the outer class's. A nested type's doc comment is the one above its + declaration, a pure-virtual method returning an elaborated type keeps its row, and a + forward declaration stays no row.""" + symbols = parse_cpp("pool.h", HEADER).symbols + rows = {(s.kind, s.qualified_name, s.start_line, s.end_line) for s in symbols} assert rows == { - ("class", "ui::Pool", 3, 21), - ("struct", "ui::Pool::Options", 6, 10), - ("function", "ui::Pool::Options::reset", 9, 9), - ("class", "ui::Pool::Inner", 11, 14), - ("function", "ui::Pool::Inner::go", 13, 13), - ("function", "ui::Pool::add", 15, 15), - ("function", "ui::Pool::a", 17, 17), - ("function", "ui::Pool::b", 19, 19), - ("struct", "ui::Stats", 23, 26), - ("function", "ui::Stats::clear", 25, 25), + ("class", "ui::Pool", 3, 27), + ("struct", "ui::Pool::Options", 7, 11), + ("function", "ui::Pool::Options::reset", 10, 10), + ("class", "ui::Pool::Inner", 12, 15), + ("function", "ui::Pool::Inner::go", 14, 14), + ("function", "ui::Pool::add", 16, 16), + ("function", "ui::Pool::make", 17, 17), + ("struct", "ui::Pool::Slot", 18, 21), + ("function", "ui::Pool::a", 23, 23), + ("function", "ui::Pool::b", 25, 25), + ("struct", "ui::Stats", 29, 32), + ("function", "ui::Stats::clear", 31, 31), } + docs = {s.qualified_name: s.doc_comment for s in symbols} + assert docs["ui::Pool::Options"] == "/// The options of a pool." diff --git a/tests/unit/test_code_diff_sides.py b/tests/unit/test_code_diff_sides.py index fe645bb1024..1a4336b2763 100644 --- a/tests/unit/test_code_diff_sides.py +++ b/tests/unit/test_code_diff_sides.py @@ -985,8 +985,8 @@ def test_a_file_scope_prototype_is_not_placed_on_a_method(tmp_path: Path) -> Non path = "src/ui/widget.h" before = WIDGET_H.replace("int area(", "void draw(int scale = 1);\nint area(") after = before.replace("scale = 1", "scale = 2") - # a method of a class, of a struct, and of a struct nested in a class, which the - # parser holds no row of + # a method of a class, of a struct, and of a struct nested in a class whose row sits in + # no file of the diff source = "namespace ui\n{\nstruct Calc\n{\n void draw(int s);\n};\nvoid Calc::draw(int s)\n{\n}\n}\n" for sub, (cpp, structs) in enumerate( ( @@ -1083,6 +1083,27 @@ def test_a_line_of_a_struct_body_stays_unmapped(tmp_path: Path) -> None: assert got == (None, []), "a line the method ui::Pool::Inner::go holds" +def test_a_member_of_a_nested_class_is_placed_on_the_nested_class(tmp_path: Path) -> None: + """A member line of a class nested in a class body is the nested class's: a claim on + the outer class does not decide it.""" + path = "src/ui/pool.h" + header = ( + "namespace ui\n{\nclass Pool\n{\npublic:\n class Inner\n {\n" + " int n = 0;\n };\n int size = 0;\n};\n}\n" + ) + for sub, (old, new, placed) in enumerate( + ( + ("int n = 0;", "int n = 1;", ["ui::Pool::Inner"]), + ("int size = 0;", "int size = 1;", ["ui::Pool"]), + ) + ): + (tmp_path / str(sub)).mkdir() + got = _place_header( + tmp_path / str(sub), path, header, header.replace(old, new), _rows(path, header) + ) + assert got == (None, placed), old + + def test_a_member_below_a_line_it_continues_stays_unmapped(tmp_path: Path) -> None: """A C++ prototype below a `virtual` or a template head alone on the line above is part of what that line starts: it stays a change.""" From 984a9aa93c337aaa56cd737cdd22290ddec8843c Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 6 Dec 2026 10:05:29 +0000 Subject: [PATCH 12/16] No line is placed when code.impact's read of the diff's rows hit its limit A row the read cut off (a method, a struct) would leave its lines in the class around it, so with either read at its limit every line outside a function stays a change. The docs say why a class's static constant is placed on the class while a file-scope one is not, and that a docstring is read below any line ending with `:`. Two pattern alternatives no line could reach are gone, and `_place_member` reads one side's text as one tuple. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- docs/features/code-index/history-and-prs.md | 27 ++++++----- server/code/app/symbol/cpp_members.py | 8 ++-- server/code/app/symbol/diff.py | 53 ++++++++++++++------- server/code/app/symbol/impact.py | 15 ++++-- tests/unit/test_code_diff_sides.py | 18 ++++++- 5 files changed, 84 insertions(+), 37 deletions(-) diff --git a/docs/features/code-index/history-and-prs.md b/docs/features/code-index/history-and-prs.md index 483c754e0df..fd7e7187d94 100644 --- a/docs/features/code-index/history-and-prs.md +++ b/docs/features/code-index/history-and-prs.md @@ -403,17 +403,17 @@ uncovered one answers `gaps`. override no claim on the class covers), a line that holds one of those words after a member, `/*`, `*/`, a raw string's opener or a quote no literal closes, and a line below one that does not end a declaration or a scope's head (a `virtual` or a - `template <...>` alone on the line above). The words are read as the line spells - them: an override declared without `override` reads as a member, and a claim on the - class then decides it. In Python an attribute (`retries = 3`, `name: str`) of a class - body outside its methods is placed when it leaves no bracket open and the line above - it is code that leaves none open either, and a docstring line when it sits right - below the class's head. Any other line stays a change: a `class` or `def` head, - a decorator, a compound statement's head, a `return` line, a line with an odd count - of `"""` or `'''` (it opens or closes a string around lines the diff leaves), a - decorator's argument, which belongs to the method below it, a string line below any - other line (an argument's or a value's), and a line below a blank or comment line, - where the brackets open above are not known. + `template <...>` alone on the line above). The words are read as the line spells them: + an override declared without `override` reads as a member, and a claim on the class + then decides it. In Python an attribute (`retries = 3`, `name: str`) of a class body + outside its methods is placed when it leaves no bracket open and the line above it is + code that leaves none open either, and a string line (a docstring) when it sits right + below a line ending with `:`, such as the class's head. Any other line stays a change: + a `class` or `def` head, a decorator, a compound statement's head, a `return` line, a + line with an odd count of `"""` or `'''` (it opens or closes a string around lines the + diff leaves), a decorator's argument, which belongs to the method below it, a string + line below any other line (an argument's or a value's), and a line below a blank or + comment line, where the brackets open above are not known. - A C++ prototype is placed also on the function it declares, when it is a member line by the rules above and the diff's files outside tests hold definitions of one qualified name for it: in a class body the function whose qualified name is the @@ -459,7 +459,10 @@ typed receiver's field) but not a bare name read in its module or after `from co import LIMIT`, so the readers it holds are not all of them and no claim on them could decide the line. So do an `#include`, a `using` line, a namespace line and a brace. Shell scripts have no class and no prototype, and the other languages' lines in no -function stay changes as before. +function stay changes as before. A data member or a static constant of a class is placed +on the class like its other members: the brief claims the definition a change sits in, +as for a function whose body changes, not the code that reads it, and a constant at file +scope sits in no definition. The symbols section lists the wiring the PR adds as counts in `collapsed`, not as rows. The fold is how the section shows them: their coverage claims and regression records diff --git a/server/code/app/symbol/cpp_members.py b/server/code/app/symbol/cpp_members.py index 2f7d2707c85..6381ea363e0 100644 --- a/server/code/app/symbol/cpp_members.py +++ b/server/code/app/symbol/cpp_members.py @@ -23,9 +23,9 @@ # type holding `*` inside its brackets (`std::vector`) is not read. _DECLARATION = re.compile(r"\s*(?:[A-Za-z_][\w:<>,\[\]]*[\s*&]+)+~?[A-Za-z_]\w*\s*[;=({\[,:]") # A special member's head, which names no type: `explicit Widget(int w);`, `~Widget();`. -_SPECIAL = r"\s*(?:(?:explicit|constexpr|inline|virtual)\s+)*~?{name}\s*\(" -# What ends a prototype without a body: `= default;`, `= delete;`, `= 0;`. -_NO_BODY = re.compile(r"=\s*(?:default|delete|0)\s*;\s*$") +_SPECIAL = r"\s*(?:(?:explicit|constexpr|inline)\s+)*~?{name}\s*\(" +# What ends a prototype without a body: `= default;`, `= delete;`. +_NO_BODY = re.compile(r"=\s*(?:default|delete)\s*;\s*$") # Words that shape a scope or open a statement wherever they sit on a C++ line. _CPP_SCOPE_WORDS = re.compile( r"\b(?:using|friend|namespace|public|protected|private|class|struct|union|enum" @@ -51,7 +51,7 @@ _STRING = re.compile(r"\"(?:[^\"\\]|\\.)*\"|'(?:[^'\\]|\\.)*'") _RAW_STRING = re.compile(r'R"') # What a constant's direct initializer may start with, which a parameter cannot. -_LITERAL_START = (*"\"'0123456789-+.{", 'R"', 'u8"', 'L"') +_LITERAL_START = (*"\"'0123456789-+.{", 'u8"', 'L"') def member_line(text: str, *, owner: str = "") -> bool: diff --git a/server/code/app/symbol/diff.py b/server/code/app/symbol/diff.py index 3277a991db1..1e504718ed8 100644 --- a/server/code/app/symbol/diff.py +++ b/server/code/app/symbol/diff.py @@ -719,6 +719,7 @@ def touched_by_diff( *, new_side: NewSide | None = None, added: list[dict[str, Any]] | None = None, + placing: bool = True, ) -> tuple[list[dict[str, Any]], list[dict[str, Any]], bool]: """(the definitions a diff touches, which seed code.impact's walk and are the subjects of its claims; the ones code.test_gate reads, every class a changed line of a body @@ -727,10 +728,13 @@ def touched_by_diff( (`_touched_rows_for_diff`), a class or a function by a member line or a C++ prototype placed on it (`place_lines`); a class that holds only lines that stay changes in no definition is the test gate's alone. A `struct` row is read by - `place_lines` alone, and so are the functions an open PR adds (`added`).""" + `place_lines` alone, and so are the functions an open PR adds (`added`). With + `placing` off (the rows of the diff's files were not all read) no line is placed.""" rows = [r for r in definitions if str(r.get("kind")) != "struct"] gate, _, _ = _touched_rows_for_diff(rows, changes, new_side=new_side) - placement = place_lines(definitions, changes, new_side=new_side, added_functions=added) + placement = place_lines( + definitions, changes, new_side=new_side, added_functions=added, placing=placing + ) placed = {(str(r["path"]), str(r["symbol_id"])) for r in placement.rows} seeds = [ r @@ -756,6 +760,23 @@ class Placement(NamedTuple): rows: list[dict[str, Any]] +class _SideText(NamedTuple): + """One side of a file's diff as `_place_member` reads it.""" + + # the side's changed lines by number + lines: dict[int, str] + # the lines a macro or a statement above continues, and those that start a run the + # hunk shows no line above + continued: frozenset[int] + unseen: frozenset[int] + # by the first line of each run, the context line above the run + above: dict[int, str] + + +# a side no line of which was read (`inserted`: lines a hunk sent without their text) +_NO_TEXT = _SideText({}, frozenset(), frozenset(), {}) + + class _Loose(NamedTuple): """A changed line range outside every function, the class that holds it (None at file scope) and whether `_place_member` may place it.""" @@ -771,6 +792,7 @@ def place_lines( *, new_side: NewSide | None = None, added_functions: list[dict[str, Any]] | None = None, + placing: bool = True, ) -> Placement: """Per source file, the changed lines that are not inert (`inert_lines`) and sit in no function, each placed on its own side: a line the diff removes or replaces against @@ -869,15 +891,14 @@ class body touches the class. A test file's lines are not counted: its functions if p in structs: loose = _outside_structs(loose, structs[p], hunks, by_lines, run_of) context = { - "removed": (text, cont_old, unseen_old, above_old), - "added": (added, cont_new, unseen_new, above_new), + "removed": _SideText(text, cont_old, unseen_old, above_old), + "added": _SideText(added, cont_new, unseen_new, above_new), } for item in loose: first, last, side = item.lines - lines_of, cont, unseen, above = context.get(side, ({}, frozenset(), frozenset(), {})) rows = ( - _place_member(first, item.holder, p, functions, (lines_of, above), cont, unseen) - if item.placeable and first == last + _place_member(first, item.holder, p, functions, context.get(side, _NO_TEXT)) + if placing and item.placeable and first == last else [] ) if rows: @@ -922,12 +943,10 @@ def _place_member( holder: dict[str, Any] | None, path: str, functions: _Functions, - side: tuple[dict[int, str], dict[int, str]], - continued: frozenset[int], - unseen: frozenset[int], + side: _SideText, ) -> list[dict[str, Any]]: """The definition rows changed line `n` of one side outside every function is placed - on, none when it stays a change in no definition. `side` is the side's changed lines + on, none when it stays a change in no definition. `side` holds the side's changed lines and, by the first line of each run, the context line above the run. A line a macro or a statement continues (`_CONTINUES`: the line above it on its side, or the context line above its run, `continued`), or that starts a run the hunk shows no line above @@ -948,7 +967,7 @@ class (`holder`), and a prototype there also on the function it declares (`_python_member_line`); a module line is placed on nothing, as a shell line is: a shell script has no class and no prototype.""" lang = lang_for_path(path) - lines, above = side + lines, continued, unseen, above = side t = lines.get(n) if t is None or n in continued or n in unseen or lang not in ("cpp", "python"): return [] @@ -966,8 +985,8 @@ class (`holder`), and a prototype there also on the function it declares return [] name = declared_name(t, in_class=True) if not name: - # a line naming a function it is not read as the prototype of (`f(Size s = - # {});`) may declare one: the class's claim alone does not decide it + # a line naming a function it is not read as the prototype of (`void f(Size s + # = {});`) may declare one: the class's claim alone does not decide it return [] if names_call(t) else [holder] # a prototype changes what calls of its function do (a default, a parameter): # the class's claim decides it only with the function's @@ -999,7 +1018,7 @@ class (`holder`), and a prototype there also on the function it declares def _python_member_line(text: str, prev: str) -> bool: """Whether a changed line of a Python class body, outside every method, is an attribute or a docstring line of the class: shaped as one (`_PY_ATTRIBUTE`, or - `_PY_STRING` right below a line ending with `:`, the class's head), with an even + `_PY_STRING` right below a line ending with `:`, as the class's head does), with an even count of each triple quote (an odd one opens or closes a string around unchanged lines), that leaves no bracket open or closes one it did not open and does not end with `,`, below a line (`prev`) of code that does neither: a line inside a @@ -1011,8 +1030,8 @@ def _python_member_line(text: str, prev: str) -> bool: return False p = prev.split("#", 1)[0].rstrip() if _PY_STRING.match(text) is not None: - # a docstring sits right below its class's head; a string line below another - # line is a value's or an argument's + # a docstring sits right below a line ending with `:` (the class's head, or an + # `if` of the class body); a string line below another is a value's or an argument's return p.endswith(":") and _closed(text) if _PY_ATTRIBUTE.match(text) is None: return False diff --git a/server/code/app/symbol/impact.py b/server/code/app/symbol/impact.py index 36ea6e9d75c..77911b9a1fa 100644 --- a/server/code/app/symbol/impact.py +++ b/server/code/app/symbol/impact.py @@ -150,6 +150,10 @@ async def _impact_inputs( return overlay, in_files, in_diff +# The most definition rows, and the most struct rows, impact reads for the diff's files. +_ROWS_LIMIT = 2000 + + async def _diff_seeds( repo: CodeRepo, org: str, @@ -181,7 +185,9 @@ async def _diff_seeds( seed_paths = list(dict.fromkeys([*in_files, *hunks.keys()]))[:200] with code_span("impact.functions_for_paths", seeds=len(seed_paths)) as sp: definitions = ( - await repo.functions_for_paths(org, ns, seed_paths, limit=2000, kinds=DEFINITION_KINDS) + await repo.functions_for_paths( + org, ns, seed_paths, limit=_ROWS_LIMIT, kinds=DEFINITION_KINDS + ) if seed_paths else [] ) @@ -194,8 +200,11 @@ async def _diff_seeds( _struct_rows(repo, org, ns, changes), ) added_rows = _overlay_added_rows(overlay) + # a line is placed by the rows around it: with either read cut at its limit a missing + # row (a method, a struct) would leave its lines in the class around it + complete = len(definitions) < _ROWS_LIMIT and len(structs) < _ROWS_LIMIT touched_rows, gate_touched, unmapped = touched_by_diff( - [*definitions, *structs], changes, new_side=new_side, added=added_rows + [*definitions, *structs], changes, new_side=new_side, added=added_rows, placing=complete ) causes = [CAUSE_NEW_SIDE_UNREAD] if unread else [] if failed: @@ -234,7 +243,7 @@ async def _struct_rows( if not cpp: return [] with code_span("impact.struct_rows", seeds=len(cpp)) as sp: - rows = await repo.functions_for_paths(org, ns, cpp, limit=2000, kinds=("struct",)) + rows = await repo.functions_for_paths(org, ns, cpp, limit=_ROWS_LIMIT, kinds=("struct",)) span_attrs(sp, results=len(rows)) return list(rows) diff --git a/tests/unit/test_code_diff_sides.py b/tests/unit/test_code_diff_sides.py index 1a4336b2763..b89daa801a0 100644 --- a/tests/unit/test_code_diff_sides.py +++ b/tests/unit/test_code_diff_sides.py @@ -788,6 +788,7 @@ def _place_header( after: str, rows: list[dict[str, Any]] | None = None, added: list[dict[str, Any]] | None = None, + placing: bool = True, ) -> tuple[list[tuple[int, int, str]] | None, list[str]]: """(the lines git's diff of `path` from `before` to `after` leaves unmapped, the qualified names of the rows its other lines are placed on), the index holding the @@ -805,7 +806,7 @@ def _place_header( ] here = [r for r in rows if r["path"] == path] side = {path: paired_extents(functions, [r for r in here if r["kind"] != "class"], here)} - placement = place_lines(rows, changes, new_side=side, added_functions=added) + placement = place_lines(rows, changes, new_side=side, added_functions=added, placing=placing) return placement.unmapped.get(path), sorted(r["qualified_name"] for r in placement.rows) @@ -815,6 +816,13 @@ def _place_header( # a member and a changed default (" int w = 0;\n", " int w = 0;\n int h = 0;\n", ["ui::Widget"]), (" int w = 0;\n", " int w = 1;\n", ["ui::Widget"]), + # a static constant is the class's member like any other: the brief claims the + # definition a change sits in, not the code that reads it + ( + " int w = 0;\n", + " int w = 0;\n static constexpr int limit = 4;\n", + ["ui::Widget"], + ), # a prototype of a function the index holds, with a trailing comment too ( " void resize(int w);\n", @@ -1083,6 +1091,14 @@ def test_a_line_of_a_struct_body_stays_unmapped(tmp_path: Path) -> None: assert got == (None, []), "a line the method ui::Pool::Inner::go holds" +def test_no_line_is_placed_when_the_rows_were_not_all_read(tmp_path: Path) -> None: + """With `placing` off (code.impact read the diff's rows up to its limit) a member line + stays a change: a row the read cut off may hold it.""" + changed = WIDGET_H.replace("int w = 0;", "int w = 1;") + got = _place_header(tmp_path, "src/ui/widget.h", WIDGET_H, changed, placing=False) + assert got == ([(13, 13, "removed"), (13, 13, "added")], []) + + def test_a_member_of_a_nested_class_is_placed_on_the_nested_class(tmp_path: Path) -> None: """A member line of a class nested in a class body is the nested class's: a claim on the outer class does not decide it.""" From 4c95601c55be9cee9eecdb7726ddcf0e143e2583 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 6 Dec 2026 10:20:49 +0000 Subject: [PATCH 13/16] A C++ union is a struct row, and a Python docstring is read only below a class head A union nested in a class had no row, so a statement in its inline method read as the outer class's body line; it is a struct row now, as a Thrift union is. A Python string line is a docstring only right below the class's head, not below another line ending with `:` such as a dict key. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- docs/features/code-index/history-and-prs.md | 21 ++++----- server/code/app/symbol/diff.py | 17 ++++---- server/code/domain/extract/treesitter.py | 9 +++- tests/unit/test_code_cpp_nested_types.py | 16 +++++++ tests/unit/test_code_diff_sides.py | 48 +++++++++++++-------- 5 files changed, 73 insertions(+), 38 deletions(-) diff --git a/docs/features/code-index/history-and-prs.md b/docs/features/code-index/history-and-prs.md index fd7e7187d94..32b779f8a80 100644 --- a/docs/features/code-index/history-and-prs.md +++ b/docs/features/code-index/history-and-prs.md @@ -408,12 +408,12 @@ uncovered one answers `gaps`. then decides it. In Python an attribute (`retries = 3`, `name: str`) of a class body outside its methods is placed when it leaves no bracket open and the line above it is code that leaves none open either, and a string line (a docstring) when it sits right - below a line ending with `:`, such as the class's head. Any other line stays a change: - a `class` or `def` head, a decorator, a compound statement's head, a `return` line, a - line with an odd count of `"""` or `'''` (it opens or closes a string around lines the - diff leaves), a decorator's argument, which belongs to the method below it, a string - line below any other line (an argument's or a value's), and a line below a blank or - comment line, where the brackets open above are not known. + below the class's head, whole on its line. Any other line stays a change: a `class` or + `def` head, a decorator, a compound statement's head, a `return` line, a line with an + odd count of `"""` or `'''` (it opens or closes a string around lines the diff + leaves), a decorator's argument, which belongs to the method below it, a string line + below any other line (an argument's or a value's, below a dict key's `:` too), and a + line below a blank or comment line, where the brackets open above are not known. - A C++ prototype is placed also on the function it declares, when it is a member line by the rules above and the diff's files outside tests hold definitions of one qualified name for it: in a class body the function whose qualified name is the @@ -445,10 +445,11 @@ uncovered one answers `gaps`. placed on the class that holds the method: a claim on the class then decides it. The parser holds a row of each named class or struct, a nested one and one defined in a variable declaration or a `typedef` included, and of each method under `#if`, `#elif` - and `#else`; an unnamed one (`struct { int a; } pair;`) has none, so its body reads as - the scope around it, a statement in an inline method of it too. A C++ `struct` is no - definition the brief claims, and `code.impact` reads its rows for placement alone: a - line of the body of a struct the index holds a row of stays a change. + and `#else`; a union is a struct row, and an unnamed class, struct or union + (`struct { int a; } pair;`) has none, so its body reads as the scope around it, a + statement in an inline method of it too. A C++ `struct` is no definition the brief + claims, and `code.impact` reads its rows for placement alone: a line of the body of a + struct the index holds a row of stays a change. - No line is placed that a macro or a statement continues (the line above it ends with `\` or `??/`), that starts a run the hunk shows no line above (a diff with no context), or that sits in a function the new side pairs with no row, or on a side nobody read. diff --git a/server/code/app/symbol/diff.py b/server/code/app/symbol/diff.py index 1e504718ed8..b9123dbe254 100644 --- a/server/code/app/symbol/diff.py +++ b/server/code/app/symbol/diff.py @@ -773,10 +773,6 @@ class _SideText(NamedTuple): above: dict[int, str] -# a side no line of which was read (`inserted`: lines a hunk sent without their text) -_NO_TEXT = _SideText({}, frozenset(), frozenset(), {}) - - class _Loose(NamedTuple): """A changed line range outside every function, the class that holds it (None at file scope) and whether `_place_member` may place it.""" @@ -890,6 +886,7 @@ class body touches the class. A test file's lines are not counted: its functions ] if p in structs: loose = _outside_structs(loose, structs[p], hunks, by_lines, run_of) + # an `inserted` line (a hunk sent without its lines) is never placeable context = { "removed": _SideText(text, cont_old, unseen_old, above_old), "added": _SideText(added, cont_new, unseen_new, above_new), @@ -897,7 +894,7 @@ class body touches the class. A test file's lines are not counted: its functions for item in loose: first, last, side = item.lines rows = ( - _place_member(first, item.holder, p, functions, context.get(side, _NO_TEXT)) + _place_member(first, item.holder, p, functions, context[side]) if placing and item.placeable and first == last else [] ) @@ -1013,12 +1010,14 @@ class (`holder`), and a prototype there also on the function it declares r"[A-Za-z_]\w*\s*(?::[^=]|=(?!=))" ) _PY_STRING = re.compile(r"\s*[rRbBuUfF]{0,2}[\"']") +# A class head whole on its line, which a docstring sits right below. +_PY_CLASS_HEAD = re.compile(r"\s*class\s+\w+\s*(?:\([^()]*\))?\s*:$") def _python_member_line(text: str, prev: str) -> bool: """Whether a changed line of a Python class body, outside every method, is an attribute or a docstring line of the class: shaped as one (`_PY_ATTRIBUTE`, or - `_PY_STRING` right below a line ending with `:`, as the class's head does), with an even + `_PY_STRING` right below the class's head, `_PY_CLASS_HEAD`), with an even count of each triple quote (an odd one opens or closes a string around unchanged lines), that leaves no bracket open or closes one it did not open and does not end with `,`, below a line (`prev`) of code that does neither: a line inside a @@ -1030,9 +1029,9 @@ def _python_member_line(text: str, prev: str) -> bool: return False p = prev.split("#", 1)[0].rstrip() if _PY_STRING.match(text) is not None: - # a docstring sits right below a line ending with `:` (the class's head, or an - # `if` of the class body); a string line below another is a value's or an argument's - return p.endswith(":") and _closed(text) + # a docstring sits right below the class's head; a string line below another + # line ending with `:` (a dict key, an `if`) is a value's or an argument's + return _PY_CLASS_HEAD.match(p) is not None and p.endswith(":") and _closed(text) if _PY_ATTRIBUTE.match(text) is None: return False return p != "" and _closed(text) and _closed(p) diff --git a/server/code/domain/extract/treesitter.py b/server/code/domain/extract/treesitter.py index c4266311f4e..15c8f0e0f3c 100644 --- a/server/code/domain/extract/treesitter.py +++ b/server/code/domain/extract/treesitter.py @@ -290,6 +290,10 @@ def _doc_comment(node: Any, source: bytes) -> str: _INCLUDE_RE = re.compile(r'#\s*include\s*[<"]([^>"]+)[>"]') +# The C++ specifiers that define a class type with a body of members. +_CLASS_SPECIFIERS = frozenset({"class_specifier", "struct_specifier", "union_specifier"}) + + def parse_cpp(path: str, source: bytes) -> ParsedFile: """Parse one C++ file: symbols with qualified names, includes, inherits.""" parser = _cpp_parser() @@ -312,6 +316,7 @@ def walk_class(child: Any, scope: tuple[str, ...], outer: Any = None) -> None: if name_node is not None and body is not None: cls_name = node_text(name_node, source) qname = "::".join(scope + (cls_name,)) + # a union is a struct row, as Thrift's is: a scope of members no claim is read for kind = "class" if t == "class_specifier" else "struct" pf.symbols.append( Symbol( @@ -357,12 +362,12 @@ def walk(node: Any, scope: tuple[str, ...]) -> None: type_node = child.child_by_field_name("type") if ( type_node is not None - and type_node.type in {"class_specifier", "struct_specifier"} + and type_node.type in _CLASS_SPECIFIERS and type_node.child_by_field_name("body") is not None ): walk_class(type_node, scope, child) continue - if t in {"class_specifier", "struct_specifier"}: + if t in _CLASS_SPECIFIERS: walk_class(child, scope) continue if t == "enum_specifier": diff --git a/tests/unit/test_code_cpp_nested_types.py b/tests/unit/test_code_cpp_nested_types.py index 177e67e7f48..3c25e729266 100644 --- a/tests/unit/test_code_cpp_nested_types.py +++ b/tests/unit/test_code_cpp_nested_types.py @@ -66,3 +66,19 @@ def test_a_nested_type_and_an_elif_branch_get_rows() -> None: } docs = {s.qualified_name: s.doc_comment for s in symbols} assert docs["ui::Pool::Options"] == "/// The options of a pool." + + +def test_a_union_is_a_struct_row() -> None: + """A union, nested in a class or not, is a struct row with its methods: a line of its + body is no member of the class around it.""" + source = ( + b"class Cell\n{\n union Storage\n {\n int i;\n" + b" void set(int v) { i = v; }\n };\n};\nunion Bits\n{\n int a;\n};\n" + ) + rows = {(s.kind, s.qualified_name) for s in parse_cpp("cell.h", source).symbols} + assert rows == { + ("class", "Cell"), + ("struct", "Cell::Storage"), + ("function", "Cell::Storage::set"), + ("struct", "Bits"), + } diff --git a/tests/unit/test_code_diff_sides.py b/tests/unit/test_code_diff_sides.py index b89daa801a0..16f0b7b7268 100644 --- a/tests/unit/test_code_diff_sides.py +++ b/tests/unit/test_code_diff_sides.py @@ -1156,6 +1156,14 @@ def test_a_line_inside_a_python_decorator_stays_unmapped(tmp_path: Path) -> None after = commented.replace('"before"', '"after"') got = _place_header(tmp_path / "c", path, commented, after, _rows(path, commented)) assert got == ([(6, 6, "removed"), (6, 6, "added")], []) + # a string below a dict key's `:` is the value's, not a docstring + keyed = before.replace( + '"name",\n', 'responses={\n 200:\n "ok"\n },\n' + ) + (tmp_path / "k").mkdir() + after = keyed.replace('"ok"', '"fine"') + got = _place_header(tmp_path / "k", path, keyed, after, _rows(path, keyed)) + assert got == ([(7, 7, "removed"), (7, 7, "added")], []) def test_a_line_between_two_inline_methods_is_placed_on_their_class(tmp_path: Path) -> None: @@ -1212,27 +1220,33 @@ def test_a_python_class_attribute_is_placed_on_the_class(tmp_path: Path) -> None under it is the class's) and a line that opens a string stay changes.""" path = "src/app/conf.py" before = 'class Conf:\n """Run settings."""\n retries = 3\n\n def run(self):\n return 1\n' - for old, new, want in ( - ("retries = 3", "retries = 5", (None, ["src.app.conf::Conf"])), - ("Run settings.", "Settings of a run.", (None, ["src.app.conf::Conf"])), - ( - " retries = 3\n", - " retries = 3\n def stop(self): pass\n", - ([(4, 4, "added")], []), - ), + for sub, (old, new, want) in enumerate( ( - " retries = 3\n", - " retries = 3\n if DEBUG:\n retries = 9\n", - ([(4, 4, "added")], ["src.app.conf::Conf"]), - ), - ('"""Run settings."""', '"""Run settings.', ([(2, 2, "added")], ["src.app.conf::Conf"])), - # line 2 is blank, where an encoding cookie is read - ("class Conf:", "LIMIT = 2\n\n\nclass Conf:", ([(1, 1, "added"), (2, 2, "added")], [])), + ("retries = 3", "retries = 5", (None, ["src.app.conf::Conf"])), + ("Run settings.", "Settings of a run.", (None, ["src.app.conf::Conf"])), + ( + " retries = 3\n", + " retries = 3\n def stop(self): pass\n", + ([(4, 4, "added")], []), + ), + ( + " retries = 3\n", + " retries = 3\n if DEBUG:\n retries = 9\n", + ([(4, 4, "added")], ["src.app.conf::Conf"]), + ), + ( + '"""Run settings."""', + '"""Run settings.', + ([(2, 2, "added")], ["src.app.conf::Conf"]), + ), + # line 2 is blank, where an encoding cookie is read + ("class Conf:", "LIMIT = 2\n\n\nclass Conf:", ([(1, 1, "added"), (2, 2, "added")], [])), + ) ): - (tmp_path / str(len(old) + len(new))).mkdir() + (tmp_path / str(sub)).mkdir() after = before.replace(old, new) rows = _rows(path, before) - got = _place_header(tmp_path / str(len(old) + len(new)), path, before, after, rows) + got = _place_header(tmp_path / str(sub), path, before, after, rows) assert got == want, new From 703c0bf606fe2f35eaccb63d7910d6a3e4359aa9 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 6 Dec 2026 10:38:10 +0000 Subject: [PATCH 14/16] No line is placed when a changed file is past the 200 code.impact reads A changed file past the first 200 paths has no rows, so its class-body lines would read as file scope; placement is off then. A scope inside a known class is no namespace, so a function in it is no free function for a file-scope prototype. A header and its source at the repository root pair by stem, and a docstring below a generic class head is read. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- docs/features/code-index/history-and-prs.md | 33 ++++++++-------- server/code/app/symbol/cpp_members.py | 7 ++-- server/code/app/symbol/diff.py | 42 +++++++++++---------- server/code/app/symbol/impact.py | 10 ++++- tests/unit/test_code_diff_sides.py | 24 ++++++++++++ tests/unit/test_code_epistemic_envelope.py | 27 +++++++++++++ 6 files changed, 102 insertions(+), 41 deletions(-) diff --git a/docs/features/code-index/history-and-prs.md b/docs/features/code-index/history-and-prs.md index 32b779f8a80..ac52537875c 100644 --- a/docs/features/code-index/history-and-prs.md +++ b/docs/features/code-index/history-and-prs.md @@ -422,22 +422,23 @@ uncovered one answers `gaps`. registration function by the index's registration rule (`registerWidgets`), which is often declared beside the call that runs it. A free function is one at global scope or in a scope the index shows to be a namespace: a scope that holds a class or struct row - and is none itself (a class whose own row sits outside the diff's files, with a nested - class's row in them, reads as one). A function in a scope the diff's files show - nothing about may be a method of a class declared elsewhere, so a file-scope prototype - is not placed on it, and one the compiler tier names in an anonymous namespace is not - placed either. A prototype whose function the diff's files do not define stays a - change, in a class body too: its defaults and parameters reach the function's callers, - which a claim on the class does not decide. So does a prototype in a class body when a - function of its name sits in a scope nested in the class, which it may declare - instead, and a class-body line that names something before a `(` but is not read as a - prototype (a default argument written with braces). A trailing `//` comment is not - read. The namespace a file-scope prototype sits in is not read either: a free function - of its name in another namespace of the same-stem file is its candidate as well. - Definitions under two qualified names leave it a change, and so does a file-scope line - whose parentheses start with a literal (`static const std::regex re("a+");`), a - constant built by a constructor. A registration statement inside a registration - function's body is that function's line already. + and neither is one nor sits in one (a class whose own row sits outside the diff's + files, with a nested class's row in them, reads as one). A function in a scope the + diff's files show nothing about may be a method of a class declared elsewhere, so a + file-scope prototype is not placed on it, and one the compiler tier names in an + anonymous namespace is not placed either. A prototype whose function the diff's files + do not define stays a change, in a class body too: its defaults and parameters reach + the function's callers, which a claim on the class does not decide. So does a + prototype in a class body when a function of its name sits in a scope nested in the + class, which it may declare instead, and a class-body line that names something before + a `(` but is not read as a prototype (a default argument written with braces). A + trailing `//` comment is not read. The namespace a file-scope prototype sits in is not + read either: a free function of its name in another namespace of the same-stem file is + its candidate as well. Definitions under two qualified names leave it a change, and so + does a file-scope line whose parentheses start with a literal + (`static const std::regex re("a+");`), a constant built by a constructor. A + registration statement inside a registration function's body is that function's line + already. - The rules read the changed line, the line above it and the index's rows, and they are as good as those rows. A line of a method the parser did not read as one (a head spelled with a macro it cannot expand) sits in the class body by the rows, so a diff --git a/server/code/app/symbol/cpp_members.py b/server/code/app/symbol/cpp_members.py index 6381ea363e0..42b3bc18300 100644 --- a/server/code/app/symbol/cpp_members.py +++ b/server/code/app/symbol/cpp_members.py @@ -101,10 +101,9 @@ def declared_name(text: str, *, in_class: bool) -> str: one line (`bool isEmpty(const Rows & rows) const;`, `static T f(X x);`), and in a class body also a constructor, which names no type. Outside a class the line must name a return type, and what follows the `(` must not start with a literal, which - makes the line a constant built by a constructor (`static const std::regex - re("a+");`). A name spelled in capitals is a macro (`DECLARE(...)`), and one after a - word that opens a statement (`return f(x);`) is a call. A trailing `//` comment is - not read.""" + makes the line a constant built by a constructor (`const std::regex re("a+");`). A + name spelled in capitals is a macro (`DECLARE(...)`), and one after a word that + opens a statement (`return f(x);`) is a call. A trailing `//` comment is not read.""" m = _HEAD.match(text.split("//", 1)[0]) if m is None: return "" diff --git a/server/code/app/symbol/diff.py b/server/code/app/symbol/diff.py index b9123dbe254..f9451f3e124 100644 --- a/server/code/app/symbol/diff.py +++ b/server/code/app/symbol/diff.py @@ -5,6 +5,7 @@ from __future__ import annotations +import posixpath import re from bisect import bisect_left, bisect_right from collections.abc import Callable @@ -971,24 +972,25 @@ class (`holder`), and a prototype there also on the function it declares prev = lines.get(n - 1, above.get(n, "")) if prev.rstrip().endswith(_CONTINUES): return [] - is_class = holder is not None and str(holder.get("kind")) == "class" + cls = holder if holder is not None and str(holder.get("kind")) == "class" else None if lang == "python": - return [holder] if holder is not None and is_class and _python_member_line(t, prev) else [] + return [cls] if cls is not None and _python_member_line(t, prev) else [] if not _ends_declaration(prev): return [] - if holder is not None and is_class: - owner = _parts(str(holder["qualified_name"])) + if cls is not None: + owner = _parts(str(cls["qualified_name"])) if not member_line(t, owner=owner[-1]): return [] name = declared_name(t, in_class=True) if not name: - # a line naming a function it is not read as the prototype of (`void f(Size s - # = {});`) may declare one: the class's claim alone does not decide it - return [] if names_call(t) else [holder] + # a line naming a function it is not read as the prototype of (a default + # written with braces) may declare one: the class's claim alone does not + # decide it + return [] if names_call(t) else [cls] # a prototype changes what calls of its function do (a default, a parameter): # the class's claim decides it only with the function's declared = functions.method_rows([*owner, name]) - return [holder, *declared] if declared and not functions.nested(owner, name) else [] + return [cls, *declared] if declared and not functions.nested(owner, name) else [] if holder is not None or not member_line(t): return [] name = declared_name(t, in_class=False) @@ -1011,7 +1013,7 @@ class (`holder`), and a prototype there also on the function it declares ) _PY_STRING = re.compile(r"\s*[rRbBuUfF]{0,2}[\"']") # A class head whole on its line, which a docstring sits right below. -_PY_CLASS_HEAD = re.compile(r"\s*class\s+\w+\s*(?:\([^()]*\))?\s*:$") +_PY_CLASS_HEAD = re.compile(r"\s*class\s+\w+\s*(?:\[[^\[\]]*\])?\s*(?:\([^()]*\))?\s*:$") def _python_member_line(text: str, prev: str) -> bool: @@ -1031,7 +1033,7 @@ def _python_member_line(text: str, prev: str) -> bool: if _PY_STRING.match(text) is not None: # a docstring sits right below the class's head; a string line below another # line ending with `:` (a dict key, an `if`) is a value's or an argument's - return _PY_CLASS_HEAD.match(p) is not None and p.endswith(":") and _closed(text) + return _PY_CLASS_HEAD.match(p) is not None and _closed(text) if _PY_ATTRIBUTE.match(text) is None: return False return p != "" and _closed(text) and _closed(p) @@ -1077,14 +1079,16 @@ def __init__(self, definitions: list[dict[str, Any]], scopes: list[dict[str, Any if str(r.get("kind")) in ("class", "struct") } # the scopes the index shows to be namespaces: one that holds a class or a struct - # and is none itself. A scope nothing shows either way may be a class whose row - # sits in a file outside the diff. - held = { - "::".join(q[:k]) - for q in (str(c).split("::")[:-1] for c in self.classes) - for k in range(1, len(q) + 1) - } - self.namespaces = held - self.classes + # and is none itself, nor sits in one. A scope nothing shows either way may be a + # class whose row sits in a file outside the diff. + self.namespaces: set[str] = set() + for c in self.classes: + q = str(c).split("::")[:-1] + for k in range(1, len(q) + 1): + scope = "::".join(q[:k]) + if scope in self.classes: + break + self.namespaces.add(scope) for r in definitions: if ( str(r.get("kind")) != "class" @@ -1129,7 +1133,7 @@ def _same_unit(p: str, path: str, stem: str) -> bool: """Whether file `p` is of `path`'s stem in its directory: `src/ui/widget.cpp` for `src/ui/widget.h`, never a `widget.cpp` of another directory, which another namespace's function of the name may sit in.""" - return _stem(p) == stem and p.rsplit("/", 1)[0] == path.rsplit("/", 1)[0] + return _stem(p) == stem and posixpath.dirname(p) == posixpath.dirname(path) def _stem(path: str) -> str: diff --git a/server/code/app/symbol/impact.py b/server/code/app/symbol/impact.py index 77911b9a1fa..a63dcadd7ee 100644 --- a/server/code/app/symbol/impact.py +++ b/server/code/app/symbol/impact.py @@ -201,8 +201,14 @@ async def _diff_seeds( ) added_rows = _overlay_added_rows(overlay) # a line is placed by the rows around it: with either read cut at its limit a missing - # row (a method, a struct) would leave its lines in the class around it - complete = len(definitions) < _ROWS_LIMIT and len(structs) < _ROWS_LIMIT + # row (a method, a struct) would leave its lines in the class around it, and a file + # past the 200 read has no rows at all, so its class-body lines read as file scope + read = set(seed_paths) + complete = ( + len(definitions) < _ROWS_LIMIT + and len(structs) < _ROWS_LIMIT + and all(p in read for p in changes) + ) touched_rows, gate_touched, unmapped = touched_by_diff( [*definitions, *structs], changes, new_side=new_side, added=added_rows, placing=complete ) diff --git a/tests/unit/test_code_diff_sides.py b/tests/unit/test_code_diff_sides.py index 16f0b7b7268..b406441ff10 100644 --- a/tests/unit/test_code_diff_sides.py +++ b/tests/unit/test_code_diff_sides.py @@ -960,6 +960,24 @@ def test_a_file_scope_prototype_is_placed_only_on_one_definition(tmp_path: Path) rows = [*_widget_rows(), *other] got = _place_header(tmp_path / str(sub), path, WIDGET_H, changed, rows) assert got == (want, [] if want else ["ui::area"]), sub + # a header and its source at the repository's root + (tmp_path / "root").mkdir() + rows = [*_rows("widget.h", WIDGET_H), *_rows("widget.cpp", WIDGET_CPP)] + got = _place_header(tmp_path / "root", "widget.h", WIDGET_H, changed, rows) + assert got == (None, ["ui::area"]) + # a scope inside a class (`ui::Widget::Parts`) is none of the namespaces a nested + # type's row shows: a function in it may be a method + nested = "namespace ui\n{\nint Widget::Parts::area(int x)\n{\n}\n}\n" + parts = { + **_rows("src/ui/widget.cpp", WIDGET_CPP)[0], + "symbol_id": "s-parts", + "qualified_name": "ui::Widget::Parts::Cell", + "kind": "struct", + } + (tmp_path / "n").mkdir() + rows = [*_rows(path, WIDGET_H), *_rows("src/ui/widget.cpp", nested), parts] + got = _place_header(tmp_path / "n", path, WIDGET_H, changed, rows) + assert got == ([(16, 16, "removed"), (16, 16, "added")], []) path = "src/ui/register.h" changed = REGISTER_H.replace("();", "(int flags);") (tmp_path / "r").mkdir() @@ -1248,6 +1266,12 @@ def test_a_python_class_attribute_is_placed_on_the_class(tmp_path: Path) -> None rows = _rows(path, before) got = _place_header(tmp_path / str(sub), path, before, after, rows) assert got == want, new + # a docstring below a generic class head + generic = before.replace("class Conf:", "class Conf[T](Base):") + (tmp_path / "g").mkdir() + after = generic.replace("Run settings.", "Settings of a run.") + got = _place_header(tmp_path / "g", path, generic, after, _rows(path, generic)) + assert got == (None, ["src.app.conf::Conf"]) def test_a_line_in_an_unpaired_function_stays_unmapped(tmp_path: Path) -> None: diff --git a/tests/unit/test_code_epistemic_envelope.py b/tests/unit/test_code_epistemic_envelope.py index ca28c0578a0..473d2dc99de 100644 --- a/tests/unit/test_code_epistemic_envelope.py +++ b/tests/unit/test_code_epistemic_envelope.py @@ -384,6 +384,33 @@ async def parsed_at(org: str, ns: str, sha: str, paths: list[str]) -> Any: assert place_lines([cls, seed], changes).unmapped +async def test_no_line_is_placed_when_a_changed_file_is_past_the_rows_read( + intel, monkeypatch: pytest.MonkeyPatch +) -> None: + """impact reads the rows of the first 200 files a diff names: a changed file past them + has no rows at all, so its class-body lines would read as file scope, and nothing is + placed. A diff within the read places as usual.""" + asked: list[bool] = [] + real = impact.touched_by_diff + + def recording(*args: Any, **kw: Any) -> Any: + asked.append(kw["placing"]) + return real(*args, **kw) + + monkeypatch.setattr(impact, "touched_by_diff", recording) + + def diff(n: int) -> str: + return "".join( + f"diff --git a/src/f{k}.h b/src/f{k}.h\n--- a/src/f{k}.h\n+++ b/src/f{k}.h\n" + "@@ -2,1 +2,1 @@\n-a\n+b\n" + for k in range(n) + ) + + await _impact(impact, _Repo(), diff=diff(200)) + await _impact(impact, _Repo(), diff=diff(201)) + assert asked == [True, False] + + def test_a_hunk_credited_to_a_row_with_no_body_extent_is_a_change_in_no_function() -> None: """A file only the compiler tier holds: `f`'s row has its start line alone. The hunk git's header credits to `void f()` touches `f` for its claim, but no line number puts From 6fedda6a7a840265b1daca66248d67247bc1d83d Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 6 Dec 2026 11:01:36 +0000 Subject: [PATCH 15/16] The C++ line rules move to domain, and impact's cut read is tested by its cause `cpp_members` does no I/O, so it sits in `server/code/domain/index`. The struct rows are not read when a changed file is past the 200 code.impact reads, since nothing is placed then. code.impact's test now asserts the cause: a prototype of a header past the read stays `unmapped_changes`, and so does a member line when the definitions read is at its limit. The docs name a line inside a string or macro call spread over lines as read on its own text, and what a trailing comment keeps a change. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- docs/features/code-index/history-and-prs.md | 13 +++- server/code/app/symbol/diff.py | 8 +- server/code/app/symbol/impact.py | 17 ++--- server/code/domain/extract/treesitter.py | 3 +- .../symbol => domain/index}/cpp_members.py | 18 ++--- tests/unit/test_code_cpp_nested_types.py | 6 ++ tests/unit/test_code_diff_sides.py | 2 +- tests/unit/test_code_epistemic_envelope.py | 73 +++++++++++++++---- 8 files changed, 94 insertions(+), 46 deletions(-) rename server/code/{app/symbol => domain/index}/cpp_members.py (88%) diff --git a/docs/features/code-index/history-and-prs.md b/docs/features/code-index/history-and-prs.md index ac52537875c..30a911a3d7f 100644 --- a/docs/features/code-index/history-and-prs.md +++ b/docs/features/code-index/history-and-prs.md @@ -432,9 +432,10 @@ uncovered one answers `gaps`. prototype in a class body when a function of its name sits in a scope nested in the class, which it may declare instead, and a class-body line that names something before a `(` but is not read as a prototype (a default argument written with braces). A - trailing `//` comment is not read. The namespace a file-scope prototype sits in is not - read either: a free function of its name in another namespace of the same-stem file is - its candidate as well. Definitions under two qualified names leave it a change, and so + trailing `//` comment is not read, unless it holds a `#`, `/*`, `*/` or a quote, which + keep the line a change. The namespace a file-scope prototype sits in is not read + either: a free function of its name in another namespace of the same-stem file is its + candidate as well. Definitions under two qualified names leave it a change, and so does a file-scope line whose parentheses start with a literal (`static const std::regex re("a+");`), a constant built by a constructor. A registration statement inside a registration function's body is that function's line @@ -450,7 +451,11 @@ uncovered one answers `gaps`. (`struct { int a; } pair;`) has none, so its body reads as the scope around it, a statement in an inline method of it too. A C++ `struct` is no definition the brief claims, and `code.impact` reads its rows for placement alone: a line of the body of a - struct the index holds a row of stays a change. + struct the index holds a row of stays a change. Since only the changed line and the + one above it are read, a line inside a string or a macro call that spans lines with no + `\` (a raw string's body, a call's arguments) reads as what its own text declares when + the line above ends a declaration, and is placed as one: the hunk's lines are not read + for the string or the call around it. - No line is placed that a macro or a statement continues (the line above it ends with `\` or `??/`), that starts a run the hunk shows no line above (a diff with no context), or that sits in a function the new side pairs with no row, or on a side nobody read. diff --git a/server/code/app/symbol/diff.py b/server/code/app/symbol/diff.py index f9451f3e124..dcf48764f3b 100644 --- a/server/code/app/symbol/diff.py +++ b/server/code/app/symbol/diff.py @@ -11,10 +11,10 @@ from collections.abc import Callable from typing import Any, Literal, NamedTuple -from server.code.app.symbol.cpp_members import declared_name, member_line, names_call from server.code.domain.extract.registration import is_registration_caller from server.code.domain.extract.treesitter import lang_for_path from server.code.domain.index import coverage_runs as cr +from server.code.domain.index.cpp_members import declared_name, member_line, names_call from server.code.domain.index.test_gate import is_test_path from server.code.domain.index.verdicts import is_graphed_path @@ -998,9 +998,7 @@ class (`holder`), and a prototype there also on the function it declares return [] stem = _stem(path) registration = is_registration_caller(name) - return functions.free_rows( - name, lambda p: registration or p == path or _same_unit(p, path, stem) - ) + return functions.free_rows(name, lambda p: registration or _same_unit(p, path, stem)) # A Python attribute (`retries = 3`, `name: str`, `limit: int = 4`), whose name is no @@ -1083,7 +1081,7 @@ def __init__(self, definitions: list[dict[str, Any]], scopes: list[dict[str, Any # class whose row sits in a file outside the diff. self.namespaces: set[str] = set() for c in self.classes: - q = str(c).split("::")[:-1] + q = c.split("::")[:-1] for k in range(1, len(q) + 1): scope = "::".join(q[:k]) if scope in self.classes: diff --git a/server/code/app/symbol/impact.py b/server/code/app/symbol/impact.py index a63dcadd7ee..84e36b265d4 100644 --- a/server/code/app/symbol/impact.py +++ b/server/code/app/symbol/impact.py @@ -195,20 +195,17 @@ async def _diff_seeds( # Only the files the index reads: a path outside its prefixes holds no function prefixes = _indexed_prefixes(org, ns) changes = {p: h for p, h in changes.items() if not prefixes or p.startswith(prefixes)} + # a line is placed by the rows around it: a file past the 200 read has no rows at all, + # so its class-body lines would read as file scope, and with either read cut at its + # limit a missing row (a method, a struct) would leave its lines in the class around it + read = set(seed_paths) + within = all(p in read for p in changes) (new_side, unread, failed), structs = await asyncio.gather( _new_side(repo, org, ns, changes, definitions, overlay, new_side_sha), - _struct_rows(repo, org, ns, changes), + _struct_rows(repo, org, ns, changes if within else {}), ) added_rows = _overlay_added_rows(overlay) - # a line is placed by the rows around it: with either read cut at its limit a missing - # row (a method, a struct) would leave its lines in the class around it, and a file - # past the 200 read has no rows at all, so its class-body lines read as file scope - read = set(seed_paths) - complete = ( - len(definitions) < _ROWS_LIMIT - and len(structs) < _ROWS_LIMIT - and all(p in read for p in changes) - ) + complete = within and len(definitions) < _ROWS_LIMIT and len(structs) < _ROWS_LIMIT touched_rows, gate_touched, unmapped = touched_by_diff( [*definitions, *structs], changes, new_side=new_side, added=added_rows, placing=complete ) diff --git a/server/code/domain/extract/treesitter.py b/server/code/domain/extract/treesitter.py index 15c8f0e0f3c..2ca1c497ade 100644 --- a/server/code/domain/extract/treesitter.py +++ b/server/code/domain/extract/treesitter.py @@ -316,7 +316,8 @@ def walk_class(child: Any, scope: tuple[str, ...], outer: Any = None) -> None: if name_node is not None and body is not None: cls_name = node_text(name_node, source) qname = "::".join(scope + (cls_name,)) - # a union is a struct row, as Thrift's is: a scope of members no claim is read for + # a union is a struct row, as Thrift's is: a scope of members no claim is + # read for kind = "class" if t == "class_specifier" else "struct" pf.symbols.append( Symbol( diff --git a/server/code/app/symbol/cpp_members.py b/server/code/domain/index/cpp_members.py similarity index 88% rename from server/code/app/symbol/cpp_members.py rename to server/code/domain/index/cpp_members.py index 42b3bc18300..aa5c6e74674 100644 --- a/server/code/app/symbol/cpp_members.py +++ b/server/code/domain/index/cpp_members.py @@ -1,14 +1,14 @@ """What a changed C++ line outside every function declares, read off its text: a member of the class whose body holds it, and the function a prototype declares. -`diff.place_lines` places such a line on the class, and a prototype on the function the -index holds too, so a claim about that definition decides the line. Only a line shaped -as a declaration is a member line. A line that shapes a scope (a brace, a class head or -its base clause, an access specifier, `using`, `friend`, a namespace, preprocessor or -compound statement line), one that may open or close a comment or a string the diff -leaves as it was, a statement and a macro call stay changes in no definition: they can -move unchanged code into another scope or change what an unchanged line means, which no -claim about one definition shows. +The review brief's placement (`place_lines`) puts such a line on the class, and a +prototype on the function the index holds too, so a claim about that definition decides +the line. Only a line shaped as a declaration is a member line. A line that shapes a +scope (a brace, a class head or its base clause, an access specifier, `using`, `friend`, +a namespace, preprocessor or compound statement line), one that may open or close a +comment or a string the diff leaves as it was, a statement and a macro call stay changes +in no definition: they can move unchanged code into another scope or change what an +unchanged line means, which no claim about one definition shows. """ from __future__ import annotations @@ -51,7 +51,7 @@ _STRING = re.compile(r"\"(?:[^\"\\]|\\.)*\"|'(?:[^'\\]|\\.)*'") _RAW_STRING = re.compile(r'R"') # What a constant's direct initializer may start with, which a parameter cannot. -_LITERAL_START = (*"\"'0123456789-+.{", 'u8"', 'L"') +_LITERAL_START = (*"\"'0123456789-+.", 'u8"', 'L"') def member_line(text: str, *, owner: str = "") -> bool: diff --git a/tests/unit/test_code_cpp_nested_types.py b/tests/unit/test_code_cpp_nested_types.py index 3c25e729266..901e7b96b5d 100644 --- a/tests/unit/test_code_cpp_nested_types.py +++ b/tests/unit/test_code_cpp_nested_types.py @@ -82,3 +82,9 @@ def test_a_union_is_a_struct_row() -> None: ("function", "Cell::Storage::set"), ("struct", "Bits"), } + + +def test_a_method_under_elifdef_gets_a_row() -> None: + source = b"class Cell\n{\n#ifdef A\n void a() {}\n#elifdef B\n void b() {}\n#endif\n};\n" + rows = {s.qualified_name for s in parse_cpp("cell.h", source).symbols} + assert rows == {"Cell", "Cell::a", "Cell::b"} diff --git a/tests/unit/test_code_diff_sides.py b/tests/unit/test_code_diff_sides.py index b406441ff10..6e06212ff7e 100644 --- a/tests/unit/test_code_diff_sides.py +++ b/tests/unit/test_code_diff_sides.py @@ -1037,7 +1037,7 @@ def test_a_file_scope_prototype_is_not_placed_on_a_method(tmp_path: Path) -> Non def test_reading_a_long_line_that_declares_nothing_costs_time_linear_in_it() -> None: """A changed line of many words and `*`s that is no declaration fails the member-line and prototype reads in time linear in its length: its words split one way.""" - from server.code.app.symbol.cpp_members import declared_name, member_line, names_call + from server.code.domain.index.cpp_members import declared_name, member_line, names_call from tests.unit.code_fixtures import grows_linearly def run(n: int) -> None: diff --git a/tests/unit/test_code_epistemic_envelope.py b/tests/unit/test_code_epistemic_envelope.py index 473d2dc99de..2b1a530f4fc 100644 --- a/tests/unit/test_code_epistemic_envelope.py +++ b/tests/unit/test_code_epistemic_envelope.py @@ -384,31 +384,72 @@ async def parsed_at(org: str, ns: str, sha: str, paths: list[str]) -> Any: assert place_lines([cls, seed], changes).unmapped -async def test_no_line_is_placed_when_a_changed_file_is_past_the_rows_read( +class _ClassRepo(_Repo): + """The index holds class `ui::W` over the first 30 lines of `src/W.h`, a free function + `area` in `src/W.cpp`, a function over the first 10 lines of each `src/g.cpp`, and + `filler` more rows of another file.""" + + def __init__(self, filler: int = 0) -> None: + super().__init__() + self.filler = filler + + async def functions_for_paths(self, org, ns, paths, *, limit=400, kinds=(), **_kw): + if "class" not in kinds: + return [] + rows = [ + {**_sym(p, p, p), "start_line": 1, "end_line": 10} + for p in paths + if p.startswith("src/g") + ] + cls = {**_sym("ui::W", "cW", "src/W.h"), "kind": "class", "start_line": 1, "end_line": 30} + rows += [cls] if "src/W.h" in paths else [] + area = {**_sym("area", "fA", "src/W.cpp"), "start_line": 1, "end_line": 10} + rows += [area] if "src/W.cpp" in paths else [] + return rows + [_sym(f"ui::f{k}", f"f{k}", "src/F.cpp") for k in range(self.filler)] + + +async def test_no_line_is_placed_when_the_rows_of_the_diff_were_not_all_read( intel, monkeypatch: pytest.MonkeyPatch ) -> None: - """impact reads the rows of the first 200 files a diff names: a changed file past them - has no rows at all, so its class-body lines would read as file scope, and nothing is - placed. A diff within the read places as usual.""" - asked: list[bool] = [] - real = impact.touched_by_diff + """A member line of a class body is placed on the class, and impact names no + `unmapped_changes`. It reads the rows of the first 200 files a diff names, and at most + 2,000 of them: with the read at its limit a row it lacks may hold a line, and a header + past the 200 has no rows, so a prototype of its class body would read as file scope + and land on the free function of its name in the source read: the line stays a + change.""" - def recording(*args: Any, **kw: Any) -> Any: - asked.append(kw["placing"]) - return real(*args, **kw) + async def parsed_at(org: str, ns: str, sha: str, paths: list[str]) -> Any: + return {p: [] for p in paths}, False - monkeypatch.setattr(impact, "touched_by_diff", recording) + monkeypatch.setattr(impact, "_parsed_at", parsed_at) + member = ( + "diff --git a/src/W.h b/src/W.h\n--- a/src/W.h\n+++ b/src/W.h\n" + "@@ -11,2 +11,2 @@\n int a;\n- int w = 0;\n+ int w = 1;\n" + ) + + prototype = ( + "diff --git a/src/W.h b/src/W.h\n--- a/src/W.h\n+++ b/src/W.h\n" + "@@ -11,2 +11,2 @@\n int a;\n- static int area(int x);\n" + "+ static int area(int x, int y);\n" + ) + source = "diff --git a/src/W.cpp b/src/W.cpp\n--- a/src/W.cpp\n+++ b/src/W.cpp\n" + source += "@@ -2,1 +1,0 @@\n-a();\n" - def diff(n: int) -> str: + def functions(n: int) -> str: return "".join( - f"diff --git a/src/f{k}.h b/src/f{k}.h\n--- a/src/f{k}.h\n+++ b/src/f{k}.h\n" - "@@ -2,1 +2,1 @@\n-a\n+b\n" + f"diff --git a/src/g{k}.cpp b/src/g{k}.cpp\n--- a/src/g{k}.cpp\n" + f"+++ b/src/g{k}.cpp\n@@ -2,1 +1,0 @@\n-a();\n" for k in range(n) ) - await _impact(impact, _Repo(), diff=diff(200)) - await _impact(impact, _Repo(), diff=diff(201)) - assert asked == [True, False] + async def causes(diff: str, filler: int = 0) -> list[str]: + out = await _impact(impact, _ClassRepo(filler), diff=diff, new_side_sha="c" * 40) + return [c for c in out.causes if c == "unmapped_changes"] + + assert await causes(member) == [] + assert await causes(functions(199) + member) == [] # 200 files, all read + assert await causes(source + functions(199) + prototype) == ["unmapped_changes"] + assert await causes(member, filler=2000) == ["unmapped_changes"] def test_a_hunk_credited_to_a_row_with_no_body_extent_is_a_change_in_no_function() -> None: From 2dbd09db2fc23c5245ce34f779fb74a9dc3326ad Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 6 Dec 2026 11:27:19 +0000 Subject: [PATCH 16/16] code.impact places no line while a namespace's rows are an older parser's While the ingest re-extracts after a parser change, the rows lack what the running parser adds (a nested type, a method under `#elif`), so a line of such a method read as the outer class's body. Placement runs only when the namespace's recorded `symbol` stage stamp is the running one, read once per namespace per five minutes; an unreadable state places nothing. `_place_member` hands a line to one function per rule, and the docs page's older text names touched definitions and the lines placed on one. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- docs/features/code-index/history-and-prs.md | 103 +++++++++++--------- server/code/app/symbol/diff.py | 80 +++++++++------ server/code/app/symbol/impact.py | 36 ++++++- server/code/domain/index/cpp_members.py | 2 +- server/code/domain/index/epistemic.py | 6 +- tests/unit/test_code_epistemic_envelope.py | 20 +++- 6 files changed, 154 insertions(+), 93 deletions(-) diff --git a/docs/features/code-index/history-and-prs.md b/docs/features/code-index/history-and-prs.md index 30a911a3d7f..a6b40a8e799 100644 --- a/docs/features/code-index/history-and-prs.md +++ b/docs/features/code-index/history-and-prs.md @@ -210,8 +210,8 @@ other than `gaps` or `unsettled` says that every check it rests on ran in full. values are tried in this order: - `gaps`: something to act on; `verdict_causes` names each: `uncovered_symbol` (the - coverage claim of a touched function or setting says `uncovered`), - `symbol_with_regressions` (a fix PR or revert names a touched function), + coverage claim of a touched definition or setting says `uncovered`), + `symbol_with_regressions` (a fix PR or revert names a touched definition), `randomized_setting` (CI randomizes a touched setting), `rationale_check`. - `unsettled`, when what the brief is of was not read in full: - `paths:no_paths`, `paths:diff_unread`, `paths:diff_cut` (a source path with hunks @@ -223,11 +223,11 @@ values are tried in this order: `functions_for_paths`, `caller_counts`, `git_diff`, `git_ls_tree`, `git_head:unread`, and `detect_lang` for a file read by its text whose language rule's parse could not run); - - `symbols:unmapped_changes` for a changed source line in no function that the brief - does not exempt (below), and `symbols:new_side_unread` for a changed source file - whose new side impact did not read to place the lines the diff adds (below), with - `symbols:code.impact:new_side_failed` when that read failed and a later read may - succeed; + - `symbols:unmapped_changes` for a changed source line in no function and placed on no + definition that the brief does not exempt (below), and `symbols:new_side_unread` for + a changed source file whose new side impact did not read to place the lines the diff + adds (below), with `symbols:code.impact:new_side_failed` when that read failed and a + later read may succeed; - `symbols:drifted:` for changed source files that differ between the diff's old side and the commit the index rows are at; - `symbols:ungraphed:` for changed files the index holds no file row of, of a path @@ -235,7 +235,7 @@ values are tried in this order: - `symbols:index_error:` for changed source files, or files in no language, whose file row records an index error (a file over the size cap, a failed chunking or parse), whose symbol rows are an older commit's or none; - - `symbols:not_read:` for touched functions past the first 30; + - `symbols:not_read:` for touched definitions past the first 30; - `overlay:` for an open PR whose overlay was off (`no_repo_entry`, `head_not_in_mirror`, `no_merge_base`, `no_git_mirror`, `error`) and `overlay:partial` for one that did not read every changed file (its parse time was @@ -269,10 +269,10 @@ values are tried in this order: rests on a coverage run or a test that names or includes its subject. - `""`: no brief was found (`source` is `missing`). -The brief caps its fan-out: coverage claims for the first six touched functions and four -settings, regression records for the first six touched definitions (a name in two files -is two), facts for the first eight settings, and the first 30 touched functions. Each -cap that leaves a subject out is a cause of its section, so the verdict stays +The brief caps its fan-out: coverage claims for the first six touched definitions and +four settings, regression records for the first six touched definitions (a name in two +files is two), facts for the first eight settings, and the first 30 touched definitions. +Each cap that leaves a subject out is a cause of its section, so the verdict stays `unsettled`; so is a subject an op refuses to read, such as a compiler-tier name past a field's 300 characters, since every build refuses it the same way. The paths section stores its first 200 changed paths as rows; its `rows_total`, verdict and causes count @@ -352,36 +352,36 @@ changed line is a line in no function, and so is every line of a source file an deletes, which is `unmapped_changes` unless it is blank, a comment included. A changed source line in no function, outside every function or in a class body, is -`unmapped_changes` unless it is blank (spaces, tabs, vertical tabs, form feeds and -carriage returns) or one of these C++ comment lines, none ending with `\` or `??/` -(which continues it onto the next line) or holding a carriage return (where a compiler -starts a new line): a line comment, or a line inside a block comment that reads `* ` -(one space) and a doxygen command, or `* ` and two words or more of prose. In a prose -line, punctuation after the first word, or a word (as the lexer splits it at `-` or `'`) -spelled as a macro (two characters or more, all capitals, or holding `_`) or as an -operator, a qualifier or a declarator keyword, makes it a continued expression or -declarator. In either kind, an end with `;` or `,` does too, and so does a `\u`, `\U`, -`\u{` or `\N{` escape where a doxygen command would be. A line holding `/*` or `*/` is a -change, a whole `/* */` comment included: inside a block comment the diff leaves as it -was, a `*/` ends that comment and turns the code below it on or off, and the hunk need -not show where the comment opened. A Python `#` line is a change, since it may sit -inside a module's string, and so is a blank Python line on the first two lines or a -blank shell line on the first, where it moves the lines an interpreter line and an -encoding cookie are read on. In C++, Python and shell, a blank line or a comment below a -line that ends with `\` (or `??/`, which the rule reads as one in each of them) ends -that line's macro or statement, so it is a change, and so is a comment that starts a run -the hunk shows no line above (a diff with no context), or follows only blank lines of -such a run, except at the top of the file, since it may sit below such a line. A blank -line there is exempt, so the comment below it is what keeps such a change visible. A -brace, a namespace line, an access specifier and an `#include` are code: each can move -unchanged code into another scope or change which overload it calls. A comment in -another language is a change, since the compiler reads some (a Go build constraint, a -cgo preamble, a TypeScript reference). A registration above a changed signature is in -no function at the side that holds it. The rule reads the changed lines and the line -above each run alone, so a blank line inside a multi-line string or a heredoc, a -comment-like line inside a C++ raw string or a macro argument, or a declarator line -whose macro is not spelled in capitals or with `_` (`* buf unused`, `* NonNull ptr`), -reads as blank or as a comment. +`unmapped_changes` unless it is placed on a definition (below) or it is blank (spaces, +tabs, vertical tabs, form feeds and carriage returns) or one of these C++ comment lines, +none ending with `\` or `??/` (which continues it onto the next line) or holding a +carriage return (where a compiler starts a new line): a line comment, or a line inside a +block comment that reads `* ` (one space) and a doxygen command, or `* ` and two words +or more of prose. In a prose line, punctuation after the first word, or a word (as the +lexer splits it at `-` or `'`) spelled as a macro (two characters or more, all capitals, +or holding `_`) or as an operator, a qualifier or a declarator keyword, makes it a +continued expression or declarator. In either kind, an end with `;` or `,` does too, and +so does a `\u`, `\U`, `\u{` or `\N{` escape where a doxygen command would be. A line +holding `/*` or `*/` is a change, a whole `/* */` comment included: inside a block +comment the diff leaves as it was, a `*/` ends that comment and turns the code below it +on or off, and the hunk need not show where the comment opened. A Python `#` line is a +change, since it may sit inside a module's string, and so is a blank Python line on the +first two lines or a blank shell line on the first, where it moves the lines an +interpreter line and an encoding cookie are read on. In C++, Python and shell, a blank +line or a comment below a line that ends with `\` (or `??/`, which the rule reads as one +in each of them) ends that line's macro or statement, so it is a change, and so is a +comment that starts a run the hunk shows no line above (a diff with no context), or +follows only blank lines of such a run, except at the top of the file, since it may sit +below such a line. A blank line there is exempt, so the comment below it is what keeps +such a change visible. A brace, a namespace line, an access specifier and an `#include` +are code: each can move unchanged code into another scope or change which overload it +calls. A comment in another language is a change, since the compiler reads some (a Go +build constraint, a cgo preamble, a TypeScript reference). A registration above a +changed signature is in no function at the side that holds it. The rule reads the +changed lines and the line above each run alone, so a blank line inside a multi-line +string or a heredoc, a comment-like line inside a C++ raw string or a macro argument, or +a declarator line whose macro is not spelled in capitals or with `_` (`* buf unused`, +`* NonNull ptr`), reads as blank or as a comment. A changed line outside every function is placed on a definition, and adds no `unmapped_changes`, where the language says which definition it belongs to. That @@ -432,11 +432,11 @@ uncovered one answers `gaps`. prototype in a class body when a function of its name sits in a scope nested in the class, which it may declare instead, and a class-body line that names something before a `(` but is not read as a prototype (a default argument written with braces). A - trailing `//` comment is not read, unless it holds a `#`, `/*`, `*/` or a quote, which - keep the line a change. The namespace a file-scope prototype sits in is not read - either: a free function of its name in another namespace of the same-stem file is its - candidate as well. Definitions under two qualified names leave it a change, and so - does a file-scope line whose parentheses start with a literal + trailing `//` comment is not read, unless it holds a `#`, `/*`, `*/` or an odd count + of `"`, which keep the line a change. The namespace a file-scope prototype sits in is + not read either: a free function of its name in another namespace of the same-stem + file is its candidate as well. Definitions under two qualified names leave it a + change, and so does a file-scope line whose parentheses start with a literal (`static const std::regex re("a+");`), a constant built by a constructor. A registration statement inside a registration function's body is that function's line already. @@ -455,7 +455,14 @@ uncovered one answers `gaps`. one above it are read, a line inside a string or a macro call that spans lines with no `\` (a raw string's body, a call's arguments) reads as what its own text declares when the line above ends a declaration, and is placed as one: the hunk's lines are not read - for the string or the call around it. + for the string or the call around it. For the same reason a `virtual` alone on a line, + with a comment or a blank line between it and the prototype it starts, is not seen, + and the prototype is placed as one of the class; and in Python a method the parser + gives no row (one defined in a class body's `for`, `while` or `match` block) sits in + the class body by the rows, so a line of its body shaped as an attribute is placed on + the class. The rules are as good as the rows of the running parser: while the ingest + re-extracts after a parser change, `code.impact` places no line (the namespace's + recorded `symbol` stage stamp is not the running one). - No line is placed that a macro or a statement continues (the line above it ends with `\` or `??/`), that starts a run the hunk shows no line above (a diff with no context), or that sits in a function the new side pairs with no row, or on a side nobody read. diff --git a/server/code/app/symbol/diff.py b/server/code/app/symbol/diff.py index dcf48764f3b..e486f81d0a0 100644 --- a/server/code/app/symbol/diff.py +++ b/server/code/app/symbol/diff.py @@ -948,22 +948,10 @@ def _place_member( and, by the first line of each run, the context line above the run. A line a macro or a statement continues (`_CONTINUES`: the line above it on its side, or the context line above its run, `continued`), or that starts a run the hunk shows no line above - (`unseen`), is never placed: it may be a macro's body or another line's end. - - In C++ a member line of a class body (`cpp_members.member_line`) is placed on the - class (`holder`), and a prototype there also on the function it declares - (`cpp_members.declared_name`): the definitions of the diff's files whose qualified - name is the class's and the prototype's. A prototype of a function they do not hold - stays a change. A prototype at file scope (`holder` None) is placed on the free - function of its name (`_Functions.free_rows`) in the diff's files that sits in the - same file or one of the same stem (`widget.h` and `widget.cpp`), or that is a - registration function (`is_registration_caller`, often declared beside the call that - runs it), when they share one qualified name: a prototype outside a class declares - no method. A test file's definitions are never one: a test does not define what the - code under test declares. In Python a class body is one scope its indentation keeps, - and an attribute or docstring line of it outside every method is placed on the class - (`_python_member_line`); a module line is placed on nothing, as a shell line is: a - shell script has no class and no prototype.""" + (`unseen`), is never placed: it may be a macro's body or another line's end. A Python + line is read by `_place_python`, a C++ line of a class body by `_place_in_class` and + one at file scope (`holder` None) by `_place_at_file_scope`; a shell script has no + class and no prototype, so its lines are placed on nothing.""" lang = lang_for_path(path) lines, continued, unseen, above = side t = lines.get(n) @@ -974,26 +962,54 @@ class (`holder`), and a prototype there also on the function it declares return [] cls = holder if holder is not None and str(holder.get("kind")) == "class" else None if lang == "python": - return [cls] if cls is not None and _python_member_line(t, prev) else [] + return _place_python(t, prev, cls) if not _ends_declaration(prev): return [] if cls is not None: - owner = _parts(str(cls["qualified_name"])) - if not member_line(t, owner=owner[-1]): - return [] - name = declared_name(t, in_class=True) - if not name: - # a line naming a function it is not read as the prototype of (a default - # written with braces) may declare one: the class's claim alone does not - # decide it - return [] if names_call(t) else [cls] - # a prototype changes what calls of its function do (a default, a parameter): - # the class's claim decides it only with the function's - declared = functions.method_rows([*owner, name]) - return [cls, *declared] if declared and not functions.nested(owner, name) else [] - if holder is not None or not member_line(t): + return _place_in_class(t, cls, functions) + if holder is not None: + return [] + return _place_at_file_scope(t, path, functions) + + +def _place_python(text: str, prev: str, cls: dict[str, Any] | None) -> list[dict[str, Any]]: + """A Python class body is one scope its indentation keeps: an attribute or docstring + line of it outside every method (`_python_member_line`) is placed on the class, a + module line on nothing.""" + return [cls] if cls is not None and _python_member_line(text, prev) else [] + + +def _place_in_class(text: str, cls: dict[str, Any], functions: _Functions) -> list[dict[str, Any]]: + """A C++ member line of a class body (`cpp_members.member_line`) is placed on the + class, and a prototype there also on the function it declares + (`cpp_members.declared_name`): the definitions of the diff's files whose qualified + name is the class's and the prototype's. A prototype of a function they do not hold + stays a change.""" + owner = _parts(str(cls["qualified_name"])) + if not member_line(text, owner=owner[-1]): + return [] + name = declared_name(text, in_class=True) + if not name: + # a line naming a function it is not read as the prototype of (a default written + # with braces) may declare one: the class's claim alone does not decide it + return [] if names_call(text) else [cls] + # a prototype changes what calls of its function do (a default, a parameter): the + # class's claim decides it only with the function's + declared = functions.method_rows([*owner, name]) + return [cls, *declared] if declared and not functions.nested(owner, name) else [] + + +def _place_at_file_scope(text: str, path: str, functions: _Functions) -> list[dict[str, Any]]: + """A C++ prototype at file scope is placed on the free function of its name + (`_Functions.free_rows`) in the diff's files that sits in the same file or one of the + same stem (`widget.h` and `widget.cpp`), or that is a registration function + (`is_registration_caller`, often declared beside the call that runs it), when they + share one qualified name: a prototype outside a class declares no method. A test + file's definitions are never one: a test does not define what the code under test + declares. Any other file-scope line stays a change.""" + if not member_line(text): return [] - name = declared_name(t, in_class=False) + name = declared_name(text, in_class=False) if not name: return [] stem = _stem(path) diff --git a/server/code/app/symbol/impact.py b/server/code/app/symbol/impact.py index 84e36b265d4..07fbb77bf15 100644 --- a/server/code/app/symbol/impact.py +++ b/server/code/app/symbol/impact.py @@ -54,7 +54,9 @@ link_tests, touched_of, ) +from server.code.app.ttl_cache import TtlCache from server.code.domain.extract.treesitter import lang_for_path +from server.code.domain.index.compiler_tiers import state_value from server.code.domain.index.epistemic import ( CAUSE_NEW_SIDE_FAILED, CAUSE_NEW_SIDE_UNREAD, @@ -71,7 +73,7 @@ ) from server.code.domain.index.verdicts import paths_seen as _paths_seen from server.code.store.index import CodeRepo -from server.core.errors import NotFoundError +from server.core.errors import NotFoundError, caller_text from server.observability import degradations from server.settings import settings @@ -152,6 +154,30 @@ async def _impact_inputs( # The most definition rows, and the most struct rows, impact reads for the diff's files. _ROWS_LIMIT = 2000 +# Per namespace, whether its rows come from the running symbol extraction, and the error +# that kept the state from being read +_SYMBOL_STAGE_CACHE: TtlCache[tuple[str, str], tuple[bool, str]] = TtlCache(300.0) + + +async def _symbol_stage_converged(repo: CodeRepo, org: str, ns: str) -> bool: + """Whether the namespace's recorded `symbol` stage stamp is the running one. While + the ingest re-extracts after a parser change, the index's rows are the old parser's: + a type or a method it gave no row reads as part of the class around it, so a line is + placed only on rows of the running parser. One state read per namespace per five + minutes; an unreadable state places nothing.""" + hit = _SYMBOL_STAGE_CACHE.get((org, ns)) + if hit is None: + try: + from server.code.domain.extract.extractor_stamp import stage_stamps + + recorded = state_value(await repo.all_state(org, ns), "extractor_stamp_symbol") + hit = (bool(recorded) and recorded == stage_stamps()["symbol"], "") + except Exception as e: # noqa: BLE001 — state unreadable: place no line + hit = (False, caller_text(e)) + _SYMBOL_STAGE_CACHE.put((org, ns), hit) + if hit[1]: + degradations.partial("code_index", "symbol_stage_unread", hit[1]) + return hit[0] async def _diff_seeds( @@ -197,15 +223,17 @@ async def _diff_seeds( changes = {p: h for p, h in changes.items() if not prefixes or p.startswith(prefixes)} # a line is placed by the rows around it: a file past the 200 read has no rows at all, # so its class-body lines would read as file scope, and with either read cut at its - # limit a missing row (a method, a struct) would leave its lines in the class around it + # limit, or the rows an older parser's, a missing row (a method, a struct) would leave + # its lines in the class around it read = set(seed_paths) within = all(p in read for p in changes) - (new_side, unread, failed), structs = await asyncio.gather( + (new_side, unread, failed), structs, current = await asyncio.gather( _new_side(repo, org, ns, changes, definitions, overlay, new_side_sha), _struct_rows(repo, org, ns, changes if within else {}), + _symbol_stage_converged(repo, org, ns), ) added_rows = _overlay_added_rows(overlay) - complete = within and len(definitions) < _ROWS_LIMIT and len(structs) < _ROWS_LIMIT + complete = within and current and len(definitions) < _ROWS_LIMIT and len(structs) < _ROWS_LIMIT touched_rows, gate_touched, unmapped = touched_by_diff( [*definitions, *structs], changes, new_side=new_side, added=added_rows, placing=complete ) diff --git a/server/code/domain/index/cpp_members.py b/server/code/domain/index/cpp_members.py index aa5c6e74674..fa315d22431 100644 --- a/server/code/domain/index/cpp_members.py +++ b/server/code/domain/index/cpp_members.py @@ -63,7 +63,7 @@ def member_line(text: str, *, owner: str = "") -> bool: it closes and none it did not open, so it continues no prototype or template head above it. Outside its string literals it holds no word that shapes a scope or opens a statement (`_CPP_SCOPE_WORDS`), no `#`, `/*` or `*/`, no raw string (it may span - lines) and no quote a literal does not close.""" + lines) and no `"` a string literal does not close.""" s = text.rstrip() if s.endswith(("\\", "??/")): return False diff --git a/server/code/domain/index/epistemic.py b/server/code/domain/index/epistemic.py index 5f1aefa62d8..2368fe21ff1 100644 --- a/server/code/domain/index/epistemic.py +++ b/server/code/domain/index/epistemic.py @@ -60,9 +60,9 @@ # with no definition or one the index does not hold), so no definition answers for it. # Each op counts its own: code.impact places a line the diff adds on the diff's new side, # a C++ member line of a class body or a Python attribute or docstring line of one on the -# class, a C++ prototype also on the function it declares, and counts any other line of -# a class body outside its methods too (`symbol.diff.place_lines`), where -# code.test_gate's line touches the class. +# class, a C++ prototype on the function it declares (in a class body on the class too), +# and counts any other line of a class body outside its methods too +# (`symbol.diff.place_lines`), where code.test_gate's line touches the class. CAUSE_UNMAPPED = "unmapped_changes" # code.impact's diff shape. The new side of a changed source file was asked for (an open # PR's overlay, `new_side_sha`) and not read: the lines the diff adds there are placed on diff --git a/tests/unit/test_code_epistemic_envelope.py b/tests/unit/test_code_epistemic_envelope.py index 2b1a530f4fc..109b507f4e4 100644 --- a/tests/unit/test_code_epistemic_envelope.py +++ b/tests/unit/test_code_epistemic_envelope.py @@ -10,6 +10,7 @@ import pytest from server.code.app.symbol import dispatch, gate, graph, impact +from server.code.domain.extract.extractor_stamp import stage_stamps from server.code.domain.index import epistemic as ep from server.settings import settings @@ -387,11 +388,16 @@ async def parsed_at(org: str, ns: str, sha: str, paths: list[str]) -> Any: class _ClassRepo(_Repo): """The index holds class `ui::W` over the first 30 lines of `src/W.h`, a free function `area` in `src/W.cpp`, a function over the first 10 lines of each `src/g.cpp`, and - `filler` more rows of another file.""" + `filler` more rows of another file; its rows come from the symbol extraction `stamp` + names, the running one by default.""" - def __init__(self, filler: int = 0) -> None: + def __init__(self, filler: int = 0, stamp: str = "") -> None: super().__init__() self.filler = filler + self.stamp = stamp or stage_stamps()["symbol"] + + async def all_state(self, org, ns): + return {"extractor_stamp_symbol": {"value": self.stamp}} async def functions_for_paths(self, org, ns, paths, *, limit=400, kinds=(), **_kw): if "class" not in kinds: @@ -416,7 +422,8 @@ async def test_no_line_is_placed_when_the_rows_of_the_diff_were_not_all_read( 2,000 of them: with the read at its limit a row it lacks may hold a line, and a header past the 200 has no rows, so a prototype of its class body would read as file scope and land on the free function of its name in the source read: the line stays a - change.""" + change. So it does while the rows are an older parser's, which may lack a nested type + or a method that holds it.""" async def parsed_at(org: str, ns: str, sha: str, paths: list[str]) -> Any: return {p: [] for p in paths}, False @@ -442,14 +449,17 @@ def functions(n: int) -> str: for k in range(n) ) - async def causes(diff: str, filler: int = 0) -> list[str]: - out = await _impact(impact, _ClassRepo(filler), diff=diff, new_side_sha="c" * 40) + async def causes(diff: str, filler: int = 0, stamp: str = "") -> list[str]: + impact._SYMBOL_STAGE_CACHE.clear() + repo = _ClassRepo(filler, stamp) + out = await _impact(impact, repo, diff=diff, new_side_sha="c" * 40) return [c for c in out.causes if c == "unmapped_changes"] assert await causes(member) == [] assert await causes(functions(199) + member) == [] # 200 files, all read assert await causes(source + functions(199) + prototype) == ["unmapped_changes"] assert await causes(member, filler=2000) == ["unmapped_changes"] + assert await causes(member, stamp="an older parser") == ["unmapped_changes"] def test_a_hunk_credited_to_a_row_with_no_body_extent_is_a_change_in_no_function() -> None: