Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(health): dataflow def/use dialect for C++ (#1225)
Raghav Chamadiyab3e565a819b2
diff --git a/docs/architecture/language-support.md b/docs/architecture/language-support.mdindex 6592e9067..fbb7aed94 100644--- a/docs/architecture/language-support.md+++ b/docs/architecture/language-support.md@@ -390,6 +390,17 @@ per-language plugin pattern, registered in a dict exactly like `resolvers/`:already flagged (`large_method` / `brain_method` / `complex_method`), so itstays within the health-pass budget.+ A dialect is only half the requirement: the CFG builder resolves bodies,+ conditions and jumps through *field names* (`body` / `consequence` /+ `alternative`) and *node types* (`break_kinds` / `continue_kinds`), so a+ grammar that labels none of them cannot be served by a dialect alone. The+ slicer additionally refuses any span containing a jump — which means an+ untyped jump is worse than no signal, because it would license an extraction+ that silently changes control flow. `find_extractions` also refuses a function+ whose subtree carries a parse error (`Node.has_error`): macro-heavy C/C+++ headers make tree-sitter emit one bogus `function_definition` spanning a whole+ class, and proposing to lift "statements" out of that is a wrong suggestion.+All tiers are purely additive and degrade to silence: an unmapped languageproduces no findings rather than wrong ones.diff --git a/docs/layers/LANGUAGE_SUPPORT.md b/docs/layers/LANGUAGE_SUPPORT.mdindex 86faab4f9..f455d37b8 100644--- a/docs/layers/LANGUAGE_SUPPORT.md+++ b/docs/layers/LANGUAGE_SUPPORT.md@@ -214,7 +214,7 @@ is "Full" vs "Good".| Rust | ✅ | ✅ | ✅ | ✅ | ✅² || C# | ✅ | ✅ | ✅ | later | ✅ || Kotlin | ✅ | ✅ | ✅ | later | ✅¹¹ |-| C++ | ✅ | ✅ | ✅ | later | ✅¹² |+| C++ | ✅ | ✅ | ✅ | ✅ | ✅¹² || Dart | ✅ | n/a³ | ✅ | later | ✅ || Scala | ✅ | ✅ | ✅⁴ | later | ✅⁵ || Ruby | ✅ | ✅⁶ | ✅⁷ | later | ✅⁸ |@@ -298,6 +298,22 @@ excluded, because an implicit-`this` member call is spelled identically. C hasno `LanguageNodeMap` at all, so it reaches no dialect despite sharing thegrammar.+¹³ **Kotlin dataflow is blocked on tree-sitter-kotlin, not merely unscheduled.**+The def/use dialect itself would be routine; the CFG builder and the Extract+Method slicer are what the grammar defeats, in four independent places:+`function_declaration` labels no `body` field (and wraps its block in a+`function_body` sibling, so the existing single-child unwrap misses it);+`for_statement` / `while_statement` label no `body` field either;+`if_expression` labels no `alternative` field and has no `else_clause` node, so+an `else` body would be silently dropped from the CFG; and a bare `break` /+`continue` parses as a plain `identifier`, with no node type to key on. That+last one is the blocker that matters: the slicer refuses any span containing a+jump, so invisible jumps would let it propose an Extract Method that silently+changes control flow — a wrong suggestion, not a missing one. Kotlin therefore+stays at "no dataflow signal", which is the correct degradation. Reviving this+needs either a grammar upgrade or a text-based jump seam plus positional+body/else resolution in the CFG core.+⁹ Shell gets function-level complexity only (CCN / nesting / cognitive / NLOC).`&&` / `||` command lists count toward CCN (`cmd || exit 1` is +1), which ishonest: shell branching is chained command lists. There are no classes,@@ -320,8 +336,8 @@ where a dialect isn't wired yet. Per-marker mechanics and precision hazards:| Dart | Good | Shipped: AST, health control-flow + class facts, perf dialect, Flutter edges. Next: riverpod/get_it dynamic hints, dataflow dialect || Scala | Full (health) | Shipped: complexity/class/assertion markers + perf dialect (JVM lexicon, `.r` recompile, sync-over-Future). Next: dataflow dialect, combinator (`.map`/`.foreach`) loop tracking via the shared `block_loop_body` hook Ruby established || Ruby | Full (health) | Shipped: complexity/class/assertion markers + perf dialect with block-iteration loops (`.each`/`.map` blocks) and the stratified ActiveRecord N+1 lexicon. Next: dataflow dialect, LCOM4 via `@ivar` grouping |-| Kotlin | Full (health) | Shipped: complexity/class/assertion markers + perf dialect (JVM lexicon, Exposed, combinator loops via `block_loop_body`, `suspend` sync-in-async). Next: dataflow dialect |-| C++ | Full (health) | Shipped: complexity/class/assertion markers + perf dialect (POSIX / `std::filesystem` / sqlite3 sinks, constant-pattern `std::regex` recompile, `lock_in_loop`). Next: dataflow dialect |+| Kotlin | Full (health) | Shipped: complexity/class/assertion markers + perf dialect (JVM lexicon, Exposed, combinator loops via `block_loop_body`, `suspend` sync-in-async). Dataflow is **blocked on the grammar**, not unstarted — see ¹³ |+| C++ | Full | Shipped: complexity/class/assertion markers, perf dialect (POSIX / `std::filesystem` / sqlite3 sinks, constant-pattern `std::regex` recompile, `lock_in_loop`), and the dataflow dialect powering Extract Method || C# | Full (health) | Dataflow dialect pending; perf shipped || Elixir | Good | Lightweight tier shipped; AST upgrade planned (`tree-sitter-elixir` available) || F# | Good | Lightweight tier shipped; AST upgrade planned (`tree-sitter-f-sharp` available) |diff --git a/packages/core/src/repowise/core/analysis/health/complexity/languages.py b/packages/core/src/repowise/core/analysis/health/complexity/languages.pyindex 2e0af0c02..372a1829f 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/languages.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/languages.py@@ -525,6 +525,20 @@ _CPP = LanguageNodeMap(# ``async_function_kinds`` stays empty and ``blocking_sync_in_async`` is# deliberately unimplemented rather than faked onto ``std::async``.call_kinds=frozenset({"call_expression", "new_expression"}),+ # ``x = …`` and ``x += …`` are both an ``assignment_expression`` (the+ # dialect tells them apart by the ``operator`` token, as in Java and Go), so+ # the augmented set stays empty. ``int x = 1, y = 2;`` is one+ # ``declaration`` nesting one ``init_declarator`` per bound name.+ # ``conditional_expression`` is in ``branch_kinds`` for CCN but NOT in+ # ``if_kinds``: a ternary is an expression, not a CFG statement.+ assignment_kinds=frozenset({"assignment_expression"}),+ local_decl_kinds=frozenset({"declaration"}),+ if_kinds=frozenset({"if_statement"}),+ block_kinds=frozenset({"compound_statement"}),+ return_kinds=frozenset({"return_statement"}),+ raise_kinds=frozenset({"throw_statement"}),+ break_kinds=frozenset({"break_statement"}),+ continue_kinds=frozenset({"continue_statement"}),)_CSHARP = LanguageNodeMap(diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/__init__.py b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/__init__.pyindex 4357ff262..19bff70d0 100644--- a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/__init__.py+++ b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/__init__.py@@ -14,6 +14,7 @@ def/use pass is silent for it (no dialect = no signal), the safe default.from __future__ import annotations+from . import cpp as _cppfrom . import go as _gofrom . import java as _javafrom . import python as _python@@ -41,6 +42,7 @@ _REGISTER: tuple[tuple[str, BaseDefUseDialect], ...] = (("jsx", _ts_js.DIALECT),("java", _java.DIALECT),("rust", _rust.DIALECT),+ ("cpp", _cpp.DIALECT),)for _tag, _dialect in _REGISTER:diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/cpp.py b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/cpp.pynew file mode 100644index 000000000..a5f6f6edf--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/cpp.py@@ -0,0 +1,260 @@+"""C++ ``DefUseDialect``.++Classifies each identifier in a statement as a write (def) or a read (use).+C++'s write sites are: a ``declaration`` (each nested ``init_declarator`` binds+one name, and a bare ``declarator`` binds an uninitialised one), plain and+compound assignments (both an ``assignment_expression``, told apart by the+``operator`` token ``=`` vs ``+=``, as in Java and Go), update expressions+(``x++`` / ``--x``, read-modify-write), the binder of a range-``for``+(``for (auto& v : xs)``) and the C-style ``for`` initializer. A ``catch``+clause's exception variable is deliberately NOT a def: the CFG never records a+handler binder as a head in any language, so it stays an unmatched *use* — the+conservative direction, matching the Java and Python dialects.++Field targets (``obj.f = …`` / ``this->f = …``) and subscript targets+(``arr[i] = …``) bind no *local*, so their base identifiers are reads — the+precision-first choice that keeps reaching definitions sound for the locals+they actually track. Pointer and reference declarators are transparent: ``int*+p = …`` and ``int& r = …`` both bind the inner ``identifier``.++Two grammar properties make the extraction simple and safe:++* a **type is never a bare ``identifier``** in tree-sitter-cpp (it is+ ``primitive_type`` / ``type_identifier`` / ``qualified_identifier`` /+ ``placeholder_type_specifier``), so "the first ``identifier`` descendant of a+ declarator" is unambiguously the bound name — no field threading needed for+ the reference/pointer wrappers, which label no field on their identifier;+* a ``call_expression``'s callee is its ``function`` field, so the called name+ is skipped while the receiver of a member callee (``db.execute()`` -> ``db``)+ is still read.++A ``switch`` stays a single CFG statement (no per-arm blocks), so a write inside+an arm is only a *may*-def: recorded as both a def and a use, which keeps the+promotion pass's must-def reasoning conservative — an uncertain write can only+ever refuse a promotion, never license one.+"""++from __future__ import annotations++from typing import TYPE_CHECKING++from .base import BaseDefUseDialect, Occurrence, StatementDefUse++if TYPE_CHECKING:+ from tree_sitter import Node++ from ...complexity.languages import LanguageNodeMap++# Write-site / structural node kinds (kept in lockstep with the C+++# ``LanguageNodeMap``; declared here so the traversal needs no lmap threading).+_ASSIGN_KINDS = frozenset({"assignment_expression"})+_UPDATE_KINDS = frozenset({"update_expression"}) # ``x++`` / ``--x``+_DECL_KINDS = frozenset({"declaration"})+_INIT_DECLARATOR = "init_declarator"+_RANGE_FOR = "for_range_loop"++_CALL = "call_expression"+# Declarator wrappers that are transparent for binding (``int* p`` / ``int& r``+# / ``int a[8]`` / ``T f(x)`` — the most-vexing-parse form of a construction).+_DECLARATOR_WRAPPERS = frozenset(+ {"pointer_declarator", "reference_declarator", "array_declarator", "function_declarator"}+)+# Field (``obj.f``) and subscript (``arr[i]``) targets bind no local.+_FIELD_EXPRESSION = "field_expression"+_SUBSCRIPT_EXPRESSION = "subscript_expression"+# A ``switch`` is one CFG statement; writes inside its arms are may-defs.+_CONDITIONAL_KINDS = frozenset({"switch_statement", "conditional_expression"})+# Nested scopes whose identifiers belong to a different function.+_SCOPE_BOUNDARIES = frozenset({"lambda_expression"})+# Callee node kinds that name a function, not a variable.+_CALLEE_NAME_KINDS = frozenset({"identifier", "qualified_identifier", "template_function"})+++class CppDefUseDialect(BaseDefUseDialect):+ language = "cpp"+ member_access_kinds = frozenset({_FIELD_EXPRESSION})+ keyword_kinds = frozenset() # C++ has no keyword arguments.++ def _is_scope_boundary(self, node: Node) -> bool:+ return node.type in _SCOPE_BOUNDARIES++ def collect_reads(self, node: Node | None, out: list[Occurrence]) -> None:+ """Like the base collector, but a ``call_expression`` contributes only+ its receiver and arguments — never the called function's name."""+ if node is not None and node.type == _CALL:+ fn = node.child_by_field_name("function")+ if fn is not None and fn.type not in _CALLEE_NAME_KINDS:+ # A member / computed callee: the receiver is a real read.+ self.collect_reads(fn, out)+ self.collect_reads(node.child_by_field_name("arguments"), out)+ return+ super().collect_reads(node, out)++ # -- public contract ------------------------------------------------------++ def statement_def_use(+ self, node: Node, lmap: LanguageNodeMap, *, head_only: bool+ ) -> StatementDefUse:+ defs: list[Occurrence] = []+ uses: list[Occurrence] = []+ if head_only:+ self._head(node, lmap, defs, uses)+ else:+ self._process(node, defs, uses)+ return StatementDefUse(defs=tuple(defs), uses=tuple(uses))++ def parameter_defs(self, fn_node: Node) -> tuple[Occurrence, ...]:+ """Names bound by the signature.++ The parameter list hangs off the ``declarator`` chain+ (``function_definition -> function_declarator -> parameter_list``), not+ off the function node, so the chain is walked to find it.+ """+ params = self._parameter_list(fn_node)+ if params is None:+ return ()+ out: list[Occurrence] = []+ for child in params.named_children:+ name_node = self._binder_identifier(child)+ if name_node is not None:+ out.append(self._occ(name_node))+ return tuple(out)++ def _parameter_list(self, fn_node: Node) -> Node | None:+ node: Node | None = fn_node+ for _ in range(6):+ if node is None:+ return None+ params = node.child_by_field_name("parameters")+ if params is not None:+ return params+ node = node.child_by_field_name("declarator")+ return None++ def _binder_identifier(self, node: Node) -> Node | None:+ """The bound name inside a declarator. Safe to search for a bare+ ``identifier``: a C++ *type* is never one (see the module docstring)."""+ if node.type in self.identifier_kinds:+ return node+ declarator = node.child_by_field_name("declarator")+ if declarator is not None:+ found = self._binder_identifier(declarator)+ if found is not None:+ return found+ for child in node.named_children:+ if child.type in self.identifier_kinds:+ return child+ if child.type in _DECLARATOR_WRAPPERS:+ found = self._binder_identifier(child)+ if found is not None:+ return found+ return None++ # -- head (loop clause / if condition / catch binder) ---------------------++ def _head(+ self, node: Node, lmap: LanguageNodeMap, defs: list[Occurrence], uses: list[Occurrence]+ ) -> None:+ t = node.type+ if t == _RANGE_FOR: # ``for (auto& v : xs)``+ binder = self._binder_identifier(node.child_by_field_name("declarator"))+ if binder is not None:+ defs.append(self._occ(binder))+ self._process(node.child_by_field_name("right"), defs, uses)+ elif t in lmap.loop_kinds: # for: init/cond/update; while / do: cond+ self._process(node.child_by_field_name("initializer"), defs, uses)+ self._process(node.child_by_field_name("condition"), defs, uses)+ self._process(node.child_by_field_name("update"), defs, uses)+ elif t in lmap.branch_kinds:+ self._process(node.child_by_field_name("condition"), defs, uses)+ # NB: a C++ ``try`` has no head. The CFG records a try head only for the+ # ``resources`` field (Java's try-with-resources), and a ``catch``+ # clause's binder is never recorded as a head in any language — so an+ # exception variable is an unmatched *use*, the conservative direction,+ # exactly as in the Java and Python dialects.+ else:+ self._process(node, defs, uses)++ # -- the unified expression / statement walk ------------------------------++ def _process(self, node: Node | None, defs: list[Occurrence], uses: list[Occurrence]) -> None:+ if node is None:+ return+ t = node.type+ if t in _ASSIGN_KINDS:+ left = node.child_by_field_name("left")+ self._targets(left, defs, uses)+ op = node.child_by_field_name("operator")+ if op is not None and op.text not in (b"=", None): # compound: read too+ self.collect_reads(left, uses)+ self._process(node.child_by_field_name("right"), defs, uses)+ return+ if t in _UPDATE_KINDS: # ``x++`` / ``--x`` -- read-modify-write+ arg = node.child_by_field_name("argument")+ self._targets(arg, defs, uses)+ self.collect_reads(arg, uses)+ return+ if t in _DECL_KINDS:+ for child in node.named_children:+ if child.type == _INIT_DECLARATOR:+ binder = self._binder_identifier(child.child_by_field_name("declarator"))+ if binder is not None:+ defs.append(self._occ(binder))+ self._process(child.child_by_field_name("value"), defs, uses)+ elif child.type in self.identifier_kinds or child.type in _DECLARATOR_WRAPPERS:+ # ``int x;`` / ``int* p;`` — a binding with no initialiser.+ binder = self._binder_identifier(child)+ if binder is not None:+ defs.append(self._occ(binder))+ return+ if t == _CALL:+ self.collect_reads(node, uses)+ return+ if t in _CONDITIONAL_KINDS:+ self._process_may_def(node, defs, uses)+ return+ if t in self.member_access_kinds:+ self.collect_reads(node, uses) # receiver is a read; field name is not+ return+ if t in self.identifier_kinds:+ uses.append(self._occ(node))+ return+ if self._is_scope_boundary(node):+ return+ for child in node.named_children:+ self._process(child, defs, uses)++ def _process_may_def(self, node: Node, defs: list[Occurrence], uses: list[Occurrence]) -> None:+ """Process *node* whose writes execute only on some path (a switch arm).++ Each def found within is recorded as a def AND a use: the may-def keeps+ the variable in every "written in this region" set while its paired use+ stays upward-exposed, so a downstream must-def proof can only get more+ conservative, never less.+ """+ inner_defs: list[Occurrence] = []+ for child in node.named_children: # not the node itself: no re-dispatch+ self._process(child, inner_defs, uses)+ defs.extend(inner_defs)+ uses.extend(inner_defs)++ # -- write-target extraction ----------------------------------------------++ def _targets(self, node: Node | None, defs: list[Occurrence], uses: list[Occurrence]) -> None:+ if node is None:+ return+ t = node.type+ if t in self.identifier_kinds:+ defs.append(self._occ(node))+ return+ if t in (_FIELD_EXPRESSION, _SUBSCRIPT_EXPRESSION): # ``o.f =`` / ``a[i] =``+ self.collect_reads(node, uses)+ return+ if t == "pointer_expression": # ``*p = …`` writes through, not to, ``p``+ self.collect_reads(node, uses)+ return+ for child in node.named_children:+ self._targets(child, defs, uses)+++DIALECT = CppDefUseDialect()diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/slice.py b/packages/core/src/repowise/core/analysis/health/dataflow/slice.pyindex 3e538d040..c92a24956 100644--- a/packages/core/src/repowise/core/analysis/health/dataflow/slice.py+++ b/packages/core/src/repowise/core/analysis/health/dataflow/slice.py@@ -77,6 +77,15 @@ def find_extractions(analysis: FunctionAnalysis, lmap: LanguageNodeMap) -> list[fn_node = analysis.fn_nodeif fn_node is None:return []+ # A subtree tree-sitter could not parse is not a function whose statements+ # we understand, so no span in it is safe to lift. This fires on macro-heavy+ # C/C++ headers, where an unterminated function-like macro+ # (``ABSL_NAMESPACE_BEGIN``) makes the parser emit one bogus+ # ``function_definition`` spanning a whole class or namespace — proposing to+ # extract "statements" from that is a wrong suggestion, not a weak one.+ # Language-agnostic and strictly subtractive: a clean parse is unaffected.+ if fn_node.has_error:+ return []body = fn_node.child_by_field_name("body")if body is None:return []diff --git a/tests/unit/health/test_dataflow_langs.py b/tests/unit/health/test_dataflow_langs.pyindex 045481d49..fb24c8763 100644--- a/tests/unit/health/test_dataflow_langs.py+++ b/tests/unit/health/test_dataflow_langs.py@@ -1052,3 +1052,195 @@ def test_rust_match_conditional_write_refuses_promotion():""","HIT",)+++# == C++ ========================================================================++# Every C++ write shape in one function: declaration (with and without an+# initialiser, through pointer / reference / array declarators), plain and+# compound assignment, ``++``, the range-``for`` binder, the C-style ``for``+# initializer -- plus the target shapes that bind NO local.+_CPP_SHAPES = """+ int total(const std::vector<int>& input, int base, Config* cfg) {+ int acc = base;+ int a = 1, b = 2;+ int uninit;+ int* ptr = nullptr;+ int& ref = acc;+ int arr[8];+ for (const auto& item : input) {+ acc += item;+ }+ for (int i = 0; i < 10; i++) {+ acc = acc + i;+ }+ cfg->count = acc;+ obj.field = acc;+ arr[a] = b;+ *ptr = acc;+ acc++;+ auto lam = [&](int z) { return z + hidden; };+ return acc;+ }+"""+++def test_cpp_def_use_classification():+ fn = _first("cpp", _CPP_SHAPES)+ defs = _def_names(fn)+ # Declarations (initialised or not), through every declarator wrapper, plus+ # the two loop binders, are locals.+ assert {"acc", "a", "b", "uninit", "ptr", "ref", "arr", "item", "i", "lam"} <= defs+ assert {"input", "base", "cfg"} <= defs # parameters seeded as entry defs+ # Field / subscript / deref targets bind no local: their bases are reads.+ assert "count" not in defs+ assert "obj" not in defs+ assert "field" not in defs+ uses = _use_names(fn)+ assert {"base", "acc", "cfg", "obj", "item", "input", "i"} <= uses+ # A type is never a variable read, and neither is a called function's name.+ assert "vector" not in uses+ assert "Config" not in uses+++def test_cpp_reads_a_member_callee_receiver_but_not_the_method():+ fn = _first(+ "cpp",+ """+ int run(Database& db, int id) {+ int n = 0;+ n += db.execute(id);+ n += helper(id);+ return n;+ }+ """,+ )+ uses = _use_names(fn)+ assert "db" in uses # the receiver is a real read+ assert "execute" not in uses # the method name is not a variable+ assert "helper" not in uses # nor is a free function's name+++def test_cpp_lambda_body_is_a_separate_scope():+ fn = _first(+ "cpp",+ """+ int outer(int seed) {+ int kept = seed;+ auto lam = [&](int z) { return z + inner_only; };+ return kept;+ }+ """,+ )+ assert "inner_only" not in _use_names(fn)+ assert "z" not in _def_names(fn)+++def test_cpp_range_for_and_c_for_build_loop_headers():+ fn = _first(+ "cpp",+ """+ int walk(const std::vector<int>& xs) {+ int n = 0;+ for (auto x : xs) { n += x; }+ for (int i = 0; i < 4; i++) { n += i; }+ while (n > 100) { n--; }+ return n;+ }+ """,+ )+ kinds = [b.kind for b in fn.cfg.blocks]+ assert kinds.count("loop_header") == 3+ assert "loop_exit" in kinds+++def test_cpp_else_if_chain_branches():+ fn = _first(+ "cpp",+ """+ int pick(int x) {+ int r = 0;+ if (x > 10) { r = 1; }+ else if (x > 5) { r = 2; }+ else { r = 3; }+ return r;+ }+ """,+ )+ assert [b.kind for b in fn.cfg.blocks].count("branch") == 2+++def test_cpp_try_catch_builds_a_handler_block():+ fn = _first(+ "cpp",+ """+ int guarded(int x) {+ int r = 0;+ try { r = risky(x); }+ catch (const std::exception& e) { r = -1; }+ return r;+ }+ """,+ )+ assert any(b.kind == "handler" for b in fn.cfg.blocks)+++def test_cpp_switch_writes_are_may_defs():+ # A switch is one CFG statement, so an arm's write is recorded as a def AND+ # a use -- keeping the must-def reasoning conservative.+ fn = _first(+ "cpp",+ """+ int classify(int x) {+ int r = 0;+ switch (x) {+ case 1: r = 10; break;+ default: r = 20;+ }+ return r;+ }+ """,+ )+ assert "r" in _def_names(fn)+ assert "r" in _use_names(fn)+++def test_cpp_extract_method_fires():+ fn = _first(+ "cpp",+ """+ int report(const std::vector<int>& xs, int base) {+ int sum = base;+ int count = 0;+ for (auto& item : xs) {+ if (item > 0) { sum += item; count++; }+ else if (item < -5) { sum -= item; }+ else { count--; }+ }+ int avg = count > 0 ? sum / count : 0;+ int scaled = avg * 2;+ int shifted = scaled + base;+ int clamped = shifted > 100 ? 100 : shifted;+ if (clamped < 0) { clamped = 0; }+ return clamped;+ }+ """,+ )+ lmap = get_language_map("cpp")+ assert lmap is not None+ extractions = find_extractions(fn, lmap)+ assert extractions+ # Deterministic ordering: re-running yields the identical best candidate.+ assert [(e.start_line, e.end_line) for e in find_extractions(fn, lmap)] == [+ (e.start_line, e.end_line) for e in extractions+ ]+++def test_cpp_extraction_never_spans_a_jump():+ # ``break`` / ``continue`` / ``return`` / ``throw`` all have dedicated node+ # types in tree-sitter-cpp, so the slicer's single-exit gate sees them.+ lmap = get_language_map("cpp")+ assert lmap is not None+ assert {"break_statement", "continue_statement"} <= lmap.break_kinds | lmap.continue_kinds+ assert "return_statement" in lmap.return_kinds+ assert "throw_statement" in lmap.raise_kinds