Repository navigation
Conversation
|
Thanks for the pull request, @scarsnow. A maintainer will review it soon. Want to talk it through while it is in review? Come join us on our Discord server. For longer-form discussion there is also GitHub Discussions. A couple of things that speed up review: make sure the test suite passes on Python 3.11 and 3.13, and that the change keeps extraction deterministic. |
|
Thanks @scarsnow! One small thing: our changelog and release notes are built from PR titles, so we use the conventional-commits format, for example: Prefixes we use: |
There was a problem hiding this comment.
🟡 Changes recommended
Stopping traversal after a return drops call edges for code still reachable through goto labels in C and C++.
1 open issue
What changed in this PR
This PR refines C/C++ call extraction to prevent unreachable calls after an unconditional return from polluting the code graph and connection analysis.
Changes:
- Stops sibling traversal after direct returns in C/C++ compound statements.
- Preserves calls in return expressions and following conditional returns.
- Adds six regression cases across C and C++.
| File | Description |
|---|---|
| tests/test_c_return_reachability.py | Tests unreachable tails, conditional returns, and calls within return expressions. |
| graphify/extractors/engine.py | Adds return-aware pruning to C/C++ call traversal. |
Review effort: Balanced
There was a problem hiding this comment.
Graphify review 
No issues reported · High impact
C and C++ extraction now omits calls in statements the new reachability pass marks unreachable, while accounting for returns, jumps, switch cases, and certain infinite loops.
What this review covered
- Some lookups asked for files or lines that do not exist; the review was told and carried on.
- A changed file's diff was too long to show in full, so the review may not have seen every changed line in it; the in-depth pass still reviewed every changed file.
- 3 of 3 changed files inspected. This is scope, not a correctness guarantee.
Code graph · 5565 functions depend on this change
- 3 functions became more coupled.
extract()(1477 callers),_extract_generic()(23 callers),_targets_for()(22 callers). - 114 of 666 test files are affected by this change.
- Gate, test list and every flagged function: in the Graphify check.
Reviewed e3c94b5 · 2 earlier findings not re-checked
cb5b161 to
95e6b3c
Compare
tree-sitter-c tags true/TRUE as a true node even for variables or stdbool spellings, so only trust the true keyword in C++; C infinite loops stay while(1)/for(;;). Addresses Graphify-Labs#5338 graphify-labs P2. Co-authored-by: Cursor <[email protected]>
Stop fall-through after unconditional return and static infinite loops (while(1)/for(;;); C++ while(true) only — C does not trust true/TRUE spellings because tree-sitter-c cannot distinguish variables or stdbool macros). Resume at goto labels and switch case/default. Warn on skipped unreachable calls by default (API toggle only). Bumps AST cache schema. Co-authored-by: Cursor <[email protected]>
373cff4 to
eaadad9
Compare
Recognize while(2)/0xff/-1 etc. as static infinite loops, keep while(0) fall-through, and tighten unreachable-warning tests to assert the real default-on flag plus the assembler-jumps disclaimer phrase. Bump AST cache schema to 54. Co-authored-by: Cursor <[email protected]>
A return inside one #if branch ended fall-through for the whole preproc_if block, so its #elif/#else children were skipped as dead code. They are other build configurations, so seed them as entry points like switch cases (Graphify-Labs#5357).
Alternate-branch calls after a return change extraction output (Graphify-Labs#5357). Co-authored-by: Cursor <[email protected]>
|
Absorbed #5357 into this tip via Deepjyoti-Sarmah’s parallel-seed commits from #5365 (
Full rebase onto current |
Keep C/C++ reachability + Graphify-Labs#5357 parallel-seed extraction under schema 54; prior (53) is current origin/v8.
…ngine imports Keep both collections.deque (C/C++ reachability) and unicodedata.normalize (Python lambda shadowing). Bump AST cache schema to 56 on top of v8 schema 55.
Collect goto targets only along fall-through-reachable paths so a goto after return inside an if/compound cannot revive label calls. Walk case_statement with the same sibling terminal rules (brace-less case bodies). Schema 57; regressions for the Graphify-Labs#5338 P2 and dead-after-return in a case.
Classify while(1)/for(;;) as permanent only after body reachability so a break after return no longer reopens after-loop calls. Cover brace and if/else/nested layouts in regressions. Schema 58.
… 0.9.120 Fold the C/C++ reachability change (Graphify-Labs#5338, Graphify-Labs#5357) into one schema bump above v8: 57, keeping v8's schema 56 note as the prior entry. Co-Authored-By: Claude Opus 5.5 <[email protected]>
_resolve_merge_schema.py was a one-off conflict resolver for graphify/cache.py that slipped into the Graphify-Labs#5338 branch with an earlier v8 merge. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Replace the per-block sibling walk with one structured reachability pass per C/C++ function body (_CReachability); walk_calls skips the statements it proves unreachable. - A label opened by a reachable goto re-enters wherever it is nested, so a break it reaches leaves a static infinite loop, a loop entered through a label is reachable from its head via the back edge, and a backward goto is resolved by repeating the pass until no label is added (Graphify-Labs#5338 review: goto-reached break hiding calls after a loop). - GNU computed gotos (`goto *p;`, `goto *t[i];`) open every label whose address is taken with `&&` (Graphify-Labs#5338 review). - switch cases are entries whenever the switch is reachable, also when wrapped in #if; the old walk seeded only direct case children, which dropped every #if-wrapped case once a plain `default:` was present. - do { } while (1) without a break now cuts fall-through like while (1). - A statement right after preprocessor parse damage never ends fall-through: #if arms that split one if / else leave its real body as a bare always-returning block (seen in STM32 HAL sources). - Lambda bodies and GNU statement expressions are their own regions. Schema stays 57 (one bump over v8); its note now describes this pass. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… 0.9.121 v8 0.9.121 also lands schema 57 (Rust Graphify-Labs#5398, COBOL Graphify-Labs#5424-Graphify-Labs#5426). Bump _AST_CACHE_SCHEMA to 58 with the C/C++ reachability lead and keep v8's schema-57 text verbatim as "prior (57)". Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Status update. The branch is merged with current What changed since the last update:
Verification:
CI is waiting for maintainer approval, since the PR comes from a fork. |
…ions
A C++ lambda (or nested function) has labels of its own, but the label scan
walked into it, so a lambda's `&&L` counted for the enclosing function: an
outer computed goto then opened the outer, unreachable `L` (or, with no outer
address taken, was narrowed to the lambda's labels only).
A GNU statement expression shares the enclosing function's labels, but it was
analyzed only as a region of its own, so `({ if (x) goto fail; 1; })` never
opened the outer `fail:` and the calls there were dropped. A reachable
statement expression now opens every label its gotos name (computed gotos
open the address-taken set), without modeling the flow inside it.
Schema stays 58 (unreleased on this branch); only its note is extended.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
- cache.py: v8 is at schema 59, so _AST_CACHE_SCHEMA becomes 60 with the C/C++ reachability lead; v8's schema-59 text is kept verbatim as "prior (59)". - engine.py: the C/C++ unreachable-key pass and v8's TypeScript callable-scope block were added at the same spot; both are kept. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Statement expressions were analyzed as regions of their own, so a break or continue in one never left the enclosing loop (lost edges), and 7db220d collected their gotos without looking at the flow inside (extra edges). They are part of the enclosing function and are now walked in the same pass. tree-sitter misreads macros that carry control flow: the return in LWIP_ERROR("msg", cond, set_errno(e); return -1;) becomes a statement of its own and cut the rest of lwip_bind(), lwip_sendmsg() and others. A statement that may sit inside or behind such a macro, or around an #if the parser loses (a label right before #if, a condition with #if inside), no longer ends fall-through, and the jumps it hides are taken. A function whose brackets do not pair up is not cut after its first error. Also: asm goto labels are entries, and goto *t[i] / goto *(expr) end fall-through like goto *p. Checked against gcc -O0 on generated control flow (nothing gcc reaches is dropped) and on 8,819 vendor sources (3 cuts left, all real dead code). Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Correction to my earlier status comment. I wrote that no edge is lost on the HAL / CMSIS / LwIP sources, but that compared only with the previous tip. Compared with no cutting at all, both tips cut 39 edges there, and 30 of those were live: a That is fixed in d954d57: the remaining 9 cut edges are real dead code in |
Only _AST_CACHE_SCHEMA conflicted: v8 took 60, so this branch is 61 and keeps the v8 text verbatim as prior (60). Co-Authored-By: Claude Opus 5.5 <[email protected]>
…at throw/co_return Lost calls (reachable code was cut): - A macro used as a keyword, unbraced in an if / else / loop / label: how tree-sitter recovers depends on the macro's name and arguments, and it may leave the `return` behind the statement. The macro is now found at the tail of the statement in front. The same goes for `_Pragma`, `#pragma` and `__attribute__` after a condition. - A jump hidden in a macro, an #include or assembler: a goto to a label nothing visible names (or that the arguments name), and a break / continue out of an infinite loop. - A case or label hidden in a macro (`CASE(2) f();`, `OTHERWISE:`, `TARGET(OP)` behind a computed goto) or an #include. - C2y `break outer;` / `continue outer;`. - A bare `NAME;` parsed as a type, macro blocks parsed as nested functions, and blocks whose brackets the parser lost. Macros the file defines are known by the words in them and functions it declares are known not to be macros (_CFileNames); this only keeps code. A label that only dead gotos name stays dead, so an early `return;` in a USER CODE block still cuts what follows. Kept calls (unreachable code was extracted): `co_return`, `throw`, MSVC `__leave` and the code after a `__try` that never completes are handled now. Compared with gcc -O0 on 199,204 generated and about 19,500 random functions: no call gcc reaches is dropped. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…se error The pass had grown rules for how tree-sitter recovers from macros that carry control flow, from statements split by #if and from syntax the grammar lacks, and each new shape needed another one. They are replaced by one scope limit: if reachable code holds a parse error, nothing in the function is cut. An error behind an early `return;` is not reachable, so a USER CODE `return;` still cuts. Computed goto and GNU case ranges are known forms and do not count. 314 lines less in engine.py. The remaining gaps (macros of other files that parse cleanly) are listed in the comment above the pass. No change on a CubeMX project, its HAL / CMSIS / LwIP sources and 8,721 vendor sources. Compared with gcc -O0 on 199,204 generated and about 19,300 random functions: no call gcc reaches is dropped. Co-Authored-By: Claude Opus 5.5 <[email protected]>

Summary
C/C++ call extraction now skips calls that no execution path can reach. The motivating case is STM32CubeMX output: generated files only keep edits made inside
USER CODE BEGIN/END, so the usual way to switch generated code off is an earlyreturn;in a USER CODE block. The generated tail after it is dead, but it still producedcallsedges (for examplelow_level_init → Error_Handler).Closes #5357.
How it works
Before the call walk, a structured reachability pass (
_CReachabilityingraphify/extractors/engine.py) runs over each C/C++ function body and marks the statements no path enters.walk_callsskips those statements.Terminals:
return,goto,breakandcontinueend fall-through to the next statement; in C++ alsothrowandco_return, and MSVC__leave. Athrowlands in a handler, which is an entry whenever itstryis.__leavegoes to the end of its__try, and__finallyalways runs.Static infinite loops:
while/doon a nonzero integer literal (1,2,0xff,-1,1u, …),for (;;), and in C++ alsowhile (true). C does not trusttrue/TRUE, because tree-sitter-c cannot tell them from a variable or macro. These loops are left only by a reachablebreakaimed at them. Abreakafter areturndoes not count.Labels: unreachable code is still scanned. A label becomes an entry point once a reachable
gotonames it, at any nesting depth. From that label, reachability continues in order: through abreakout of the loop, through the loop's back edge to its head, and into the code after the loop. Labels are function-scoped and a latergotocan target an earlier label, so the pass repeats until no new label is activated. Gotos in unreachable code activate nothing.Computed goto (GNU):
goto *p;andgoto *table[i];activate every label whose address is taken (&&label) in the function, or every label if none is.Parallel entries:
switchcases are entries whenever the switch is reachable, including cases wrapped in#if. The previous tip seeded only the directcasechildren, so in LwIP'sswitch (...) { #if LWIP_RAW case NETCONN_RAW: ... #endif ... default: }every wrapped case was dropped. Each#elif/#elsearm is an entry whenever its#ifis, since it is another build configuration rather than code after the arm'sreturn(fix(c/cpp): seed preproc_else/elif as parallel reachability entries #5357). This parallel seeding comes from @Deepjyoti-Sarmah's fix(c/cpp): keep #elif/#else calls after a return in a #if branch (stacked on #5338) #5365; authorship is kept on those commits.Not evaluated:
ifconditions and#ifexpressions. Both arms are treated as possible.Nested functions: C++ lambda bodies and GNU nested functions are analyzed separately and keep their own labels, so a
returninside a lambda only ends the lambda.GNU statement expressions:
({ ... })is part of the enclosing function, so it is walked in place, in the same pass. Areturn,goto,breakorcontinuein it acts on the code around it. Where an operand may not be evaluated (right side of&&/||, one arm of?:, call or macro arguments,sizeof), not completing it does not cut what follows.Parse errors: nothing is cut in a function whose reachable code holds a parse error. Macros that carry control flow (
LWIP_ERROR("msg", cond, return -1;);,WHEN(x) return 0;,CASE(2) f();), statements split by#if(STM32 HAL), C2ybreak outer;and MSVC__asm { }all show up as one, and how tree-sitter recovers says nothing about the real flow. An error behind an earlyreturn;is not reachable, so thatreturn;still cuts. Computedgotoand GNU case ranges are known and do not count.Hidden jumps and entries: a macro may also parse cleanly. Macros the file defines are known by the words in them, and functions it declares are known not to be macros. Any other name:
gotoa label nothing visible names (CHECK(x);), or one its arguments name (CHECK(x, fail);)break/continueas a bareNAME;or as an all-capital statement (BREAK_IF(x);)caseof a reachableswitchas an all-capital label (OTHERWISE:), or a label when a reachablegotonames none that is visibleAn
#includeinside a function may do all of these. This is only used to keep calls, never to cut more. A label that only deadgotos name stays dead.Assembler: every label an
asm gotolists is an entry, and so is one that__asm("B L")names.Warnings: skipped calls are reported on stderr by default. The message notes that assembler jumps are not modeled. The warning can be toggled only through
set_c_cpp_unreachable_warnings()/get_c_cpp_unreachable_warnings(); there is no CLI or.graphifyrcoption.Cache:
_AST_CACHE_SCHEMA60 → 61, one bump on top of currentv8(0.9.124).Scope
The aim is plain control flow, as in the CubeMX case. These are left as they are on purpose:
#ifexpressions, or a single-configuration-Dmode.#endifwhen every arm is terminal, and after aswitchwhosedefaultis terminal.noreturncallees (Error_Handler,abort,exit) andlongjmp.if (0),if constexpr,while (!0), the back edge ofdo ... while (0).Known gap, where a call can still be lost: a macro of another file that parses cleanly and is the only way out of an infinite loop (lower-case
break_if(x);), jumps to a label a deadgotoalso names, is a case (CASE(2);), or opens or closes a block (BEGIN/END). None of these costs an edge in the sources below.Review notes
returnstay reachable when agototargets them (cleanup pattern).&&labelreviving an outer label with the same name; an unreachablegotoinside a statement expression reviving a dead label; Cwhile (true)as a variable; nonzero-constant loops;#else/#elifafter areturn(fix(c/cpp): seed preproc_else/elif as parallel reachability entries #5357); agotoafter areturnreviving a label; an unreachablebreakreopening the code after a loop. The two latest findings are also addressed: a goto-reached nestedbreakleaving an infinite loop, and computed gotos. Both are fixed by function-level label activation. Code afterco_return(kept although unreachable) is cut now, andthrowand__leavewith it._resolve_merge_schema.py, a merge helper script that had been committed by mistake.Test plan
uv run pytest tests/test_c_return_reachability.py -q→ 519 passed (C and C++)pytest -n auto -m "not serial"on Windows: the failure set matches a cleanv8run of the same command, so no failures are new. They are Windows-only problems (cp950UnicodeDecodeError, POSIX path and bash-hook tests).-O0(which drops blocks no path reaches) on generated control flow: every loop /switch/if/ label /#if/ statement-expression container nested two deep, with every jump, entered normally or bygoto, in C and C++ (199,204 functions gcc accepts), plus 7,438 random ones (about 50,000 on the previous tip). No call gcc reaches is dropped. Some unreachable calls are kept (see "Scope").throw/tryand#pragma: no call gcc reaches is dropped.#ifdamage: 0 of 2,108 functions lose a call (5 of 3,126 on the previous tip).callsedges are cut, all after the earlyreturns inlwip.c/ethernetif.c..cfiles): compared with no cutting at all, 9 edges are cut, all real dead code inppp/auth.c. Earlier tips of this PR also cut 30 live edges insockets.c/tcp.c(areturninsideLWIP_ERROR(...)); that is fixed.🤖 Generated with Claude Code