diff --git a/docs/features/code-index/history-and-prs.md b/docs/features/code-index/history-and-prs.md index 8794a107f1e..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,38 +352,132 @@ 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 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 +`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 +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 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, 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 string line (a docstring) when it sits right + 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 + 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 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, 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. +- 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 + 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`; 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. 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. 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. + +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. 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 are read all the same. The kinds follow the index's 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..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, @@ -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/diff.py b/server/code/app/symbol/diff.py index 1dd0dfbfb5b..e486f81d0a0 100644 --- a/server/code/app/symbol/diff.py +++ b/server/code/app/symbol/diff.py @@ -5,12 +5,16 @@ from __future__ import annotations +import posixpath import re from bisect import bisect_left, bisect_right +from collections.abc import Callable from typing import Any, Literal, NamedTuple +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 @@ -18,8 +22,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 `unmapped_lines` names 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 @@ -438,6 +443,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]) @@ -498,6 +517,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}) @@ -530,6 +550,23 @@ 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. 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({top for top, _ in bounds.values()})) + out: dict[int, dict[str, Any] | None] = {} + for key, (top, below) in bounds.items(): + 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: """Whether a changed line of the hunk sits in a definition.""" for a, b in hunk.removed: @@ -555,7 +592,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 +654,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 @@ -663,19 +700,97 @@ 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 unmapped_lines( +def _touched_rank(r: dict[str, Any]) -> tuple[int, str, int]: + """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( + definitions: list[dict[str, Any]], + changes: dict[str, list[Hunk]], + *, + 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 + 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. A `struct` row is read by + `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, placing=placing + ) + placed = {(str(r["path"]), str(r["symbol_id"])) for r in placement.rows} + seeds = [ + r + for r in gate + if str(r.get("kind")) != "class" or (str(r["path"]), str(r["symbol_id"])) in placed + ] + held = {(str(r["path"]), str(r["symbol_id"])) for r in gate} + seeds += [ + {**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 + ] + return sorted(seeds, key=_touched_rank), gate, 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 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]] + + +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] + + +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]], *, new_side: NewSide | None = None, -) -> dict[str, list[tuple[int, int, Side]]]: + 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 the definitions the index holds (`definitions`, the old side), a line it adds against @@ -690,17 +805,35 @@ 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. + + 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.""" 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) + 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), *(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(): if not hunks or not is_graphed_path(p) or is_test_path(p): continue @@ -713,11 +846,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, above_old = _run_context(hunks, removed=True) + inert_old = inert_lines(text, p, continued=cont_old, unseen=unseen_old) + 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] = [] for hunk in hunks: @@ -729,27 +863,307 @@ 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) + 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) - missed += [ - (n, n, "removed") + loose += [ + _Loose((n, n, "removed"), owners[n], True) 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 += [ + _Loose(m, around[run_of[m[0]]], True) + if seeds is not None and hunk.blocks and m[0] not in seeds + else _Loose(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) + # 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), + } + for item in loose: + first, last, side = item.lines + rows = ( + _place_member(first, item.holder, p, functions, context[side]) + if placing and item.placeable and first == last + else [] + ) + if rows: + placed.update((str(r["symbol_id"]), r) for r in rows) + else: + missed.append(item.lines) if missed: out[p] = missed - return out + return Placement(out, list(placed.values())) + + +def _outside_structs( + loose: list[_Loose], + structs: list[dict[str, Any]], + hunks: list[Hunk], + by_lines: list[Hunk], + run_of: dict[int, int], +) -> 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({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(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 + h = x.holder + return h is None or _span(h)[0] <= _span(s)[0] <= _span(s)[1] <= _span(h)[1] + return [x._replace(placeable=x.placeable and not in_struct(x)) for x in loose] -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 _place_member( + n: int, + holder: dict[str, Any] | None, + path: str, + functions: _Functions, + 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` 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 + (`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) + if t is None or n in continued or n in unseen or lang not in ("cpp", "python"): + return [] + prev = lines.get(n - 1, above.get(n, "")) + if prev.rstrip().endswith(_CONTINUES): + return [] + cls = holder if holder is not None and str(holder.get("kind")) == "class" else None + if lang == "python": + return _place_python(t, prev, cls) + if not _ends_declaration(prev): + return [] + if cls is not None: + 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(text, in_class=False) + if not name: + return [] + stem = _stem(path) + registration = is_registration_caller(name) + 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 +# 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}[\"']") +# 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*(?:\([^()]*\))?\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 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 + 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 + p = prev.split("#", 1)[0].rstrip() + 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 _closed(text) + if _PY_ATTRIBUTE.match(text) is None: + return False + 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 _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 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]], 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, *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, 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 = 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" + 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 _free(self, r: dict[str, Any]) -> bool: + """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 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 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, [])) + ) + + 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 [] + + +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 posixpath.dirname(p) == posixpath.dirname(path) + + +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], 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 @@ -757,9 +1171,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/server/code/app/symbol/impact.py b/server/code/app/symbol/impact.py index 5b97486bc36..07fbb77bf15 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 ( @@ -55,6 +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 @@ -150,6 +152,34 @@ 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 +# 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( repo: CodeRepo, org: str, @@ -181,7 +211,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 [] ) @@ -189,35 +221,64 @@ 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 + # 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, 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, 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), ) - # 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) added_rows = _overlay_added_rows(overlay) + 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 + ) 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: - 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=_ROWS_LIMIT, kinds=("struct",)) + span_attrs(sp, results=len(rows)) + return list(rows) + + async def _new_side( repo: CodeRepo, org: str, diff --git a/server/code/domain/extract/treesitter.py b/server/code/domain/extract/treesitter.py index 422ae74181a..2ca1c497ade 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() @@ -298,6 +302,50 @@ 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, ...], 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") + # 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,)) + # 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( + 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(outer or 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)) + walk(body, scope + (cls_name,)) + def walk(node: Any, scope: tuple[str, ...]) -> None: for child in node.named_children: t = child.type @@ -308,45 +356,20 @@ 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 {"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,)) + 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_SPECIFIERS + and type_node.child_by_field_name("body") is not None + ): + walk_class(type_node, scope, child) + continue + if t in _CLASS_SPECIFIERS: + walk_class(child, scope) continue if t == "enum_specifier": name_node = child.child_by_field_name("name") @@ -436,7 +459,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/server/code/domain/index/cpp_members.py b/server/code/domain/index/cpp_members.py new file mode 100644 index 00000000000..fa315d22431 --- /dev/null +++ b/server/code/domain/index/cpp_members.py @@ -0,0 +1,119 @@ +"""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. + +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 + +import re + +# A C++ member declaration: one word or more of its type and specifiers (names, `::`, +# `<>`, `,` 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)\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" + 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" + # 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, `::`, `<>`, `*`, +# `&` 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.*)" +) +# 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-+.", 'u8"', 'L"') + + +def member_line(text: str, *, owner: str = "") -> bool: + """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 + 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 `"` a string literal does not close.""" + s = text.rstrip() + if s.endswith(("\\", "??/")): + return False + 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 + 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 + 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 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 + 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 (`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 "" + 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 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/domain/index/epistemic.py b/server/code/domain/index/epistemic.py index 0ad04b03e78..2368fe21ff1 100644 --- a/server/code/domain/index/epistemic.py +++ b/server/code/domain/index/epistemic.py @@ -58,9 +58,11 @@ # 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, +# a C++ member line of a class body or a Python attribute or docstring line of one on the +# 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_cpp_nested_types.py b/tests/unit/test_code_cpp_nested_types.py new file mode 100644 index 00000000000..901e7b96b5d --- /dev/null +++ b/tests/unit/test_code_cpp_nested_types.py @@ -0,0 +1,90 @@ +"""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: + /// The options of a pool. + struct Options + { + int size = 0; + void reset() { size = 0; } + }; + 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) + 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, 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, 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." + + +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"), + } + + +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 4d493ed7381..6e06212ff7e 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,573 @@ 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 _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), + *_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, + 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 + 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, added_functions=added, placing=placing) + return placement.unmapped.get(path), sorted(r["qualified_name"] for r in placement.rows) + + +@pytest.mark.parametrize( + ("old", "new", "placed"), + [ + # 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", + " 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", + "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"), + # 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", + '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"), + # 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"), + (" 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 + (" 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", + ), + (" 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( + 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 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") + 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", 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), + ) + ): + (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 + # 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() + assert _place_header(tmp_path / "r", path, REGISTER_H, changed) == ( + None, + ["ui::registerWidgets"], + ) + + +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_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 + 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") + # 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( + ( + ("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 + # 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.domain.index.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: + """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: + """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, 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" + " 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 = ( + "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::Pool::Options", "ui::Stats"} + for sub, (old, new, line) in enumerate( + ( + (" 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]) + 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_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.""" + 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.""" + 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 + 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")], []) + # 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() + 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: + """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, 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 sub, (old, new, want) in enumerate( + ( + ("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(sub)).mkdir() + after = before.replace(old, new) + 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: + """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 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}") + *_, 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]) + 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..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 @@ -361,7 +362,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 +382,84 @@ 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 + + +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; its rows come from the symbol extraction `stamp` + names, the running one by default.""" + + 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: + 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: + """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. 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 + + 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 functions(n: int) -> str: + return "".join( + 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) + ) + + 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: @@ -392,7 +470,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 +480,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_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 ca28bdc2b54..77662eadfa1 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,21 +1403,32 @@ 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) + 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 t["kind"] != "class"] - 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}, "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 {}), } @@ -1565,7 +1572,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"]] @@ -1815,10 +1822,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 +1833,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 +1847,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 +1860,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 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) 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::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 +1906,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 +1917,56 @@ 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, static constants: the class + (" int step = 0;", ["DB::Shift"]), + (" static constexpr int limit = 8;", ["DB::Shift"]), + (' static constexpr auto name = "shift";', ["DB::Shift"]), + # a prototype of `k`, which the brief lists for its body too + (" 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 +1984,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 +1996,29 @@ 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"), + # 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( + _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, # 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 +2038,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 +2621,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 +2667,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 +2922,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 +2930,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)