Skip to content

fix(c-cpp): skip calls in code no path can reach - #5338

Open
scarsnow wants to merge 19 commits into
Graphify-Labs:v8from
scarsnow:c-return-reachability
Open

scarsnow wants to merge 19 commits into
Graphify-Labs:v8from
scarsnow:c-return-reachability

Conversation

@scarsnow

@scarsnow scarsnow commented Nov 19, 2026 •

Copy link
Copy Markdown

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 early return; in a USER CODE block. The generated tail after it is dead, but it still produced calls edges (for example low_level_init → Error_Handler).

Closes #5357.

How it works

Before the call walk, a structured reachability pass (_CReachability in graphify/extractors/engine.py) runs over each C/C++ function body and marks the statements no path enters. walk_calls skips those statements.

  • Terminals: return, goto, break and continue end fall-through to the next statement; in C++ also throw and co_return, and MSVC __leave. A throw lands in a handler, which is an entry whenever its try is. __leave goes to the end of its __try, and __finally always runs.

  • Static infinite loops: while / do on a nonzero integer literal (1, 2, 0xff, -1, 1u, …), for (;;), and in C++ also while (true). C does not trust true / TRUE, because tree-sitter-c cannot tell them from a variable or macro. These loops are left only by a reachable break aimed at them. A break after a return does not count.

  • Labels: unreachable code is still scanned. A label becomes an entry point once a reachable goto names it, at any nesting depth. From that label, reachability continues in order: through a break out 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 later goto can 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; and goto *table[i]; activate every label whose address is taken (&&label) in the function, or every label if none is.

  • Parallel entries: switch cases are entries whenever the switch is reachable, including cases wrapped in #if. The previous tip seeded only the direct case children, so in LwIP's switch (...) { #if LWIP_RAW case NETCONN_RAW: ... #endif ... default: } every wrapped case was dropped. Each #elif / #else arm is an entry whenever its #if is, since it is another build configuration rather than code after the arm's return (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: if conditions and #if expressions. 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 return inside 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. A return, goto, break or continue in 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), C2y break outer; and MSVC __asm { } all show up as one, and how tree-sitter recovers says nothing about the real flow. An error behind an early return; is not reachable, so that return; still cuts. Computed goto and 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:

    • may goto a label nothing visible names (CHECK(x);), or one its arguments name (CHECK(x, fail);)
    • may break / continue as a bare NAME; or as an all-capital statement (BREAK_IF(x);)
    • may be a case of a reachable switch as an all-capital label (OTHERWISE:), or a label when a reachable goto names none that is visible

    An #include inside a function may do all of these. This is only used to keep calls, never to cut more. A label that only dead gotos name stays dead.

  • Assembler: every label an asm goto lists 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 .graphifyrc option.

  • Cache: _AST_CACHE_SCHEMA 60 → 61, one bump on top of current v8 (0.9.124).

Scope

The aim is plain control flow, as in the CubeMX case. These are left as they are on purpose:

  • Functions with a parse error in reachable code (above): not cut.
  • Evaluating #if expressions, or a single-configuration -D mode.
  • Cutting fall-through after #endif when every arm is terminal, and after a switch whose default is terminal.
  • noreturn callees (Error_Handler, abort, exit) and longjmp.
  • Conditions other than a literal infinite loop: if (0), if constexpr, while (!0), the back edge of do ... 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 dead goto also 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

  • Copilot: labels after a return stay reachable when a goto targets them (cleanup pattern).
  • Graphify review findings addressed: a lambda's &&label reviving an outer label with the same name; an unreachable goto inside a statement expression reviving a dead label; C while (true) as a variable; nonzero-constant loops; #else / #elif after a return (fix(c/cpp): seed preproc_else/elif as parallel reachability entries #5357); a goto after a return reviving a label; an unreachable break reopening the code after a loop. The two latest findings are also addressed: a goto-reached nested break leaving an infinite loop, and computed gotos. Both are fixed by function-level label activation. Code after co_return (kept although unreachable) is cut now, and throw and __leave with it.
  • Removed _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++)
  • Full suite pytest -n auto -m "not serial" on Windows: the failure set matches a clean v8 run of the same command, so no failures are new. They are Windows-only problems (cp950 UnicodeDecodeError, POSIX path and bash-hook tests).
  • Compared with gcc 16 -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 by goto, 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").
  • The same comparison on 9,790 random functions with jumps, cases and labels hidden in macros (macros visible to gcc only, or defined in the file), named loops, throw / try and #pragma: no call gcc reaches is dropped.
  • Random macro / #if damage: 0 of 2,108 functions lose a call (5 of 3,126 on the previous tip).
  • Real CubeMX project (STM32H7 + LwIP), 53 project files: compared with no cutting at all, 5 calls edges are cut, all after the early returns in lwip.c / ethernetif.c.
  • Its STM32 HAL, CMSIS and LwIP sources (1058 .c files): compared with no cutting at all, 9 edges are cut, all real dead code in ppp/auth.c. Earlier tips of this PR also cut 30 live edges in sockets.c / tcp.c (a return inside LWIP_ERROR(...)); that is fixed.
  • 8,721 distinct vendor sources (STM32Cube H7, Keil packs): 3 places cut, all real dead code.
  • CI on this PR

🤖 Generated with Claude Code

@scarsnow
scarsnow requested a review from safishamsi as a code owner November 19, 2026 09:49
Copilot AI balanced review requested due to automatic review settings November 19, 2026 09:49
@github-actions github-actions Bot added the needs:title PR title should follow the conventional-commit format label Nov 19, 2026
@github-actions

Copy link
Copy Markdown

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.

@github-actions

Copy link
Copy Markdown

Thanks @scarsnow! One small thing: our changelog and release notes are built from PR titles, so we use the conventional-commits format, for example:

fix(python): resolve a bare stdlib import correctly

Prefixes we use: feat, fix, docs, chore, refactor, test, perf, build, ci. Editing the PR title clears this automatically. This is just a nudge and does not block review.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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

Comment thread graphify/extractors/engine.py Resolved

@graphify-labs graphify-labs Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Graphify review View in Graphify

Looks safe to merge · Merge confidence 5/5

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

@scarsnow scarsnow changed the title fix(c/cpp): skip call extraction after unconditional return fix(c/cpp): resume call extraction at goto/case after return Nov 20, 2026
@scarsnow
scarsnow force-pushed the c-return-reachability branch from cb5b161 to 95e6b3c Compare November 23, 2026 07:27
Comment thread graphify/extractors/engine.py Resolved
scarsnow added a commit to scarsnow/graphify that referenced this pull request Nov 23, 2026
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]>
@scarsnow
scarsnow force-pushed the c-return-reachability branch from 373cff4 to eaadad9 Compare November 23, 2026 08:32
Comment thread graphify/extractors/engine.py Resolved
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]>
Comment thread graphify/extractors/engine.py Resolved
Deepjyoti-Sarmah and others added 3 commits November 24, 2026 11:09
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]>
@scarsnow

Copy link
Copy Markdown
Author

Absorbed #5357 into this tip via Deepjyoti-Sarmah’s parallel-seed commits from #5365 (d3f512ec / c0a57311) plus a schema bump to 55 (6d53e5c7).

tests/test_c_return_reachability.py: 57 passed. Multi-world union unchanged — #elif/#else are extra seeds like switch cases; #if expressions are still not evaluated.

Full rebase onto current v8 is still pending (merge conflicts + OAuth token lacks workflow scope to push CI workflow updates).

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.
Comment thread graphify/extractors/engine.py Resolved
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.
Comment thread graphify/extractors/engine.py Resolved
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.
Comment thread graphify/extractors/engine.py Resolved
Comment thread graphify/extractors/engine.py Resolved
scarsnow and others added 4 commits November 26, 2026 14:15
… 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]>
@scarsnow scarsnow changed the title fix(c/cpp): resume call extraction at goto/case after return fix(c-cpp): skip calls in code no path can reach Nov 27, 2026
@github-actions github-actions Bot removed the needs:title PR title should follow the conventional-commit format label Nov 27, 2026
@scarsnow

Copy link
Copy Markdown
Author

Status update. The branch is merged with current v8 (0.9.121); the only conflict was _AST_CACHE_SCHEMA, now 58.

What changed since the last update:

  • Reachability is one structured pass per function (_CReachability) instead of per-block helpers. Labels activate per function and the pass repeats until it stabilizes, which fixes the two latest review findings (goto-reached break out of an infinite loop, computed gotos). do { } while (1) now counts as a static infinite loop too.
  • switch cases wrapped in #if are entries now. The previous tip dropped them whenever the switch also had a direct case/default.
  • A statement right after preprocessor parse damage no longer ends fall-through. This came up in STM32 HAL, where #if arms split one if/else.

Verification:

  • tests/test_c_return_reachability.py: 111 passed
  • The C/C++ and extract tests fail the same way as a clean v8 run on Windows. All of those failures are Windows environment issues.
  • Real STM32CubeMX project: calls edges are identical to the previous tip. On its HAL, CMSIS and LwIP sources (1058 .c files), no edge is lost and 66 are gained, all from the #if-wrapped switch cases.

CI is waiting for maintainer approval, since the PR comes from a fork.

Comment thread graphify/extractors/engine.py Resolved
…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]>
Comment thread graphify/extractors/engine.py Resolved
scarsnow and others added 2 commits November 30, 2026 10:23
- 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]>
@scarsnow

Copy link
Copy Markdown
Author

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 return or goto inside a macro argument, such as LWIP_ERROR("msg", cond, set_errno(e); return -1;);, parses as a statement of its own and cut the rest of lwip_bind(), lwip_sendmsg() and others.

That is fixed in d954d57: the remaining 9 cut edges are real dead code in ppp/auth.c. To look for more of the same, I compared the pass with gcc -O0 on about 250,000 generated functions (loops, switch, labels, #if, statement expressions, C and C++). The generated matrix and random sets now lose no call that gcc reaches. The branch is also merged with v8 0.9.123, and _AST_CACHE_SCHEMA is now 60.

Comment thread graphify/extractors/engine.py Resolved
scarsnow and others added 3 commits December 1, 2026 10:38
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]>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(c/cpp): seed preproc_else/elif as parallel reachability entries

3 participants