Skip to content

fix(c/cpp): keep #elif/#else calls after a return in a #if branch (stacked on #5338) - #5365

Open
Deepjyoti-Sarmah wants to merge 5 commits into
Graphify-Labs:v8from
Deepjyoti-Sarmah:fix/5357-preproc-else-reachability
Open

Deepjyoti-Sarmah wants to merge 5 commits into
Graphify-Labs:v8from
Deepjyoti-Sarmah:fix/5357-preproc-else-reachability

Conversation

@Deepjyoti-Sarmah

@Deepjyoti-Sarmah Deepjyoti-Sarmah commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

Fixes #5357. Stacked on #5338. With #5338, a return inside one #if branch also dropped the calls in that block's #elif and #else branches. Those calls are now kept. Dead code after the return inside the same branch is still dropped.

The issue's repro, with an #elif branch added:

void f(void) {
#if FEATURE
  a();
  return;
  dead();
#elif OTHER
  c();
#else
  b();
#endif
  after();
}
#5338 tip   f() calls a(), after()                 warning: skipped 3 call expression(s)
this PR     f() calls a(), after(), b(), c()       warning: skipped 1 call expression(s)  (dead())

tree-sitter nests the alternate branches inside the preproc_if node, after the #if branch's own statements:

preproc_if
  #if  FEATURE
  a();  return;  dead();
  preproc_elif               <- a sibling after the return
    #elif OTHER  c();
    preproc_else
      #else  b();

#5338 walks a block's children in order and stops at the first return. So preproc_elif and preproc_else look like dead code after the return. They are other build configurations: when FEATURE is off, #if's return is not compiled at all.

The fix uses the mechanism #5338 already has for switch, where each case is its own entry point, as the issue suggests:

 _c_block_seed_indices(node, children)
   switch body  -> seed every case_statement   (unchanged)
   otherwise    -> seed [0]
+  preproc_if / preproc_ifdef / preproc_elif
+               -> also seed each preproc_elif / preproc_else child

Each branch is then walked with the same rules. A return inside an #elif still drops the dead code after it in that #elif.

Stacking on #5338

This branch is #5338 rebased onto current v8 b582ad40, plus two commits:

2a5e08fe  scarsnow   fix(c/cpp): skip call extraction after unconditional return            (#5338)
aca57a90  scarsnow   fix(c/cpp): also stop after return inside preproc_if bodies            (#5338)
b2e27179  scarsnow   fix(c/cpp): resume call extraction at goto/case after return           (#5338)
4e484df8  this PR    test(5357): pin #elif/#else calls after a return in a #if branch
551874a8  this PR    fix(c/cpp): seed preproc_else/elif as parallel reachability entries

Only the last two are new. The rebase made two changes to #5338's commits, both inside b2e27179. scarsnow's authorship is kept:

If #5338 lands first, this PR shrinks to 4e484df8 and 551874a8.

Type of change

  • Bug fix
  • New feature
  • Documentation
  • Tests or CI
  • Refactor
  • Security fix

Verification & Invariants

Invariant: a call is dropped as unreachable only if no build configuration reaches it by falling through. Each #if/#elif/#else branch is a separate starting point.

  • Read the CONTRIBUTING.md guide.
  • Reproduced the issue and identified the invariant.
  • Made the smallest fix necessary.
  • Added a regression test (if bug fix) or isolated boundary test.
  • Kept the PR description synchronized with the final implementation.
  • Documented any limitations / unsupported cases explicitly.

Merge Danger

Door: two-way. Reverting 551874a8 restores #5338's behaviour. The cache schema bump forces one re-extraction.

Blast Radius: small.

  • It only affects C/C++ functions where a return, goto or static infinite loop sits inside an #if/#ifdef/#elif branch that has an #elif/#else after it.
  • Those functions gain the calls edges in their alternate branches, which v8 had before fix(c-cpp): skip calls in code no path can reach #5338. The unreachable-call warning counts fewer calls.
  • _AST_CACHE_SCHEMA goes 50 -> 51, so every cached file re-extracts once.

Limitations

How was this tested?

There's one new test in tests/test_c_return_reachability.py, using that file's helpers. It checks that the live calls and after() are present, and that dead()/dead2() are absent:

test_return_in_preproc_branch_keeps_alternate_branches   (.c and .cpp)
  else         #if: a(); return; dead();  #else: b();                     -> a, b, after
  elif-chain   #if ... #elif: c(); return; dead2();  #else: b();          -> a, b, c, after
  ifdef-else   #ifdef: a(); return; dead();  #else: b();                  -> a, b, after

tests/test_c_return_reachability.py:

tree result
#5338 tip cb5b161c (before rebase) 6 failed, 28 passed (the 6 new cases)
551874a8 34 passed

Full suite, v8 and this branch run at the same time in the same venv:

tree failed passed
v8 b582ad40 76 11684
551874a8 76 11718

The 76 failures are identical on both trees. The 34 extra passes are tests/test_c_return_reachability.py: 28 from #5338 and the 6 new cases.

ruff check graphify/extractors/engine.py graphify/cache.py tests/test_c_return_reachability.py  -> All checks passed!

Not tested: Windows.

Graphify-specific checklist

  • I updated generated skill artifacts (uv run python -m tools.skillgen --bless) when changing their source fragments. (N/A: no skill fragments touched.)
  • I confirmed that AST/structural extraction remains deterministic (no ambient state dependencies like ENV variables). (Seeding depends only on the parse tree.)
  • I reviewed changes for security implications (no unsafe interpolation into shell/Python).
  • I confirmed no API keys or local-only graph data are included.
  • (If applicable) I disclosed AI authorship in my commit messages. (No trailer in the commit messages.)

@github-actions

Copy link
Copy Markdown

Thanks for the pull request, @Deepjyoti-Sarmah. 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 github-actions Bot added needs:title PR title should follow the conventional-commit format contributor Pull request from a returning community contributor labels Nov 20, 2026
@github-actions

Copy link
Copy Markdown

Thanks @Deepjyoti-Sarmah! 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.

@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 code review View in Graphify

Review completed · 551874a88f9c

Warning

Merge confidence: 3/5 · Review before merging · 🟠 High impact
1 P2 bugs, 1 unranked · 6 possible issues not confirmed
6 not re-checked

The change limits C/C++ call extraction to code reachable by fall-through, goto, and switch cases.

Full summary

The change limits C/C++ call extraction to code reachable by fall-through, goto, and switch cases. It also adds optional stderr warnings for calls skipped as unreachable.

Bugs (2)

P2 · Check whether true is a constant before treating it as an always-true condition: in C, int true = 0; while (true) {} can make the extractor omit calls after the loop. Inspect source

Detailed review · checked against the code

A false C variable named true hides calls after the loop

In C, declaring int true = 0; is valid, but calls after while (true) {} are omitted from the graph.

Expected: The extractor should recognize that the C identifier evaluates to zero and include the following call as reachable.
Actually: The identifier spelling is treated as proof of a constant-true condition, so the loop is marked terminal and the following call is omitted.

In C, true can be an identifier. _c_is_constant_true_condition returns true whenever the condition is an identifier spelled true, without checking its value. Thus for int true = 0; while (true) {}, the extractor classifies the loop as static infinite if it has no exiting break. The reachable-children walker then treats that loop as terminal and does not walk following siblings, so a call after the loop is omitted from the graph.

  • Independent source review: Checked the C/C++ reachability walker and its invocation from walk_calls: it skips siblings after a terminal loop, and the invocation applies to C as well as C++. No guard on this route distinguishes a C identifier from C++ true. Searches did not locate a matching test; test behavior was not inspected.

Resume the walk in the outer block after a nested block containing a goto target: the current walk can find calls inside that block but omit calls after it, such as after(). Inspect source

Detailed review · checked against the code

A goto into a nested block can hide calls after that block

A goto to a label inside a nested block can make execution continue after the enclosing block, but the call walker only resumes within the label’s immediate parent block. Calls after the nested block are then missing from the graph.

The new walker records reachable outer siblings, then separately rewalks a nested label’s immediate parent block with that label as its seed. That rewalk can visit calls inside the nested block but does not resume in the outer block after the enclosing statement. In the stated pattern, a legal goto reaches the label, execution can finish the nested block and continue to after(), but the walker omits after() from the call graph.

  • Independent source review: The existing nested-goto test asserts calls inside the label’s block and excludes a call before the label; it does not include or assert a call after the enclosing block. The walk_calls dispatch invokes the reachability walker on C/C++ compound blocks, so the affected path is reachable during extraction.

  • The example relies on a legal goto into a nested block; jumps that violate C/C++ restrictions on entering scopes are not covered by this finding.

Not confirmed (6 possible issues)

Leads worth a look; we didn't double-check these. They don't change the score.

Not confirmed · The default-on warning test forces the flag on, so the default value is never checked Inspect source

Detailed review · not confirmed

The test name says the unreachable-code warning is on by default, but line 457 sets the flag to True before extracting. A regression that turned the warning off by default would not fail this test.

Line 457 calls set_c_cpp_unreachable_warnings(True) before the first extract, so the first assertion block at lines 458-461 tests the explicit setting rather than the default. The autouse fixture at lines 42-47 also sets True before each test, so nothing in this test checks the default state.

  • The module's real default value is not read or asserted anywhere in this file.

  • Found by the per-file sweep; not double-checked.

Not confirmed · Warning test accepts any stderr that contains 'asm', so it does not confirm the expected unreachable-code message Inspect source

Detailed review · not confirmed

The second assertion passes if stderr contains the phrase 'assembler jumps' or any text with 'asm' in any case. That loose match is weaker than the first check, which requires the 'fall-through-unreachable' marker.

Line 460 checks the stable marker 'fall-through-unreachable', but line 461 joins an alternative with 'or' and matches 'asm' as a loose substring of lowercased stderr. Because the 'or' clause is satisfied by any stray 'asm' text, the check does not verify the assembler-jump hint that the test name and intent refer to.

  • The exact wording of the emitted assembler hint is not visible in this file, so the correct expected string cannot be confirmed here.

  • Found by the per-file sweep; not double-checked.

Not confirmed · Statements after a braced { return; } or a labeled return are still treated as reachable, so their calls are still recorded Inspect source

Detailed review · not confirmed

Only a bare return or goto directly in a block ends fall-through. A return wrapped in braces or carrying a label does not, so code after it still produces call edges.

_c_is_sibling_terminal (lines 8137-8145) checks only node.type == "return_statement" and goto_statement. A compound_statement or labeled_statement that wraps a return is not terminal, so the BFS in _c_cpp_walk_reachable_children at line 8234 enqueues the next sibling.

  • Not run against a real tree-sitter parse, so the exact node shapes for labeled and braced returns are inferred from the code, not observed.

  • Found by the per-file sweep; not double-checked.

Not confirmed · Reachability walk rescans whole subtrees for every goto target and child, which can make extraction of goto-heavy C files very slow Inspect source

Detailed review · not confirmed

Label lookup and containment checks walk the full subtree repeatedly, once per goto target and per reachable child, at every nested block level.

_c_find_labeled_statement (line 8024) scans the whole block subtree for each goto target at line 8244. _c_node_contains (line 8247) rescans each reachable child for each nested label. Both run at each nested block level, so cost grows with gotos times subtree size.

  • No timing was measured; the slowdown is inferred from the loops, and the size of real files is unknown.

  • Found by the per-file sweep; not double-checked.

Not confirmed · Unreachable-call warnings are printed to stderr by default, so ordinary C/C++ extraction runs now print warnings unless users turn them off Inspect source

Detailed review · not confirmed

The change enables stderr warnings by default with no CLI or config switch to disable them. The PR description is empty, so the intent of this default is unstated.

_C_CPP_WARN_UNREACHABLE is True at line 7970, and _c_warn_unreachable_calls prints whenever skipped calls exist (lines 8149-8168). The comments say there is no CLI or config toggle, so the only way to disable the output is a Python-level call.

  • Whether the default is intended is not stated in the PR, because its description is empty.

  • Found by the per-file sweep; not double-checked.

Not confirmed · The two static infinite-loop tests are near copies that differ only in the loop header Inspect source

Detailed review · not confirmed

test_static_infinite_while_skips_following_calls and test_static_infinite_for_skips_following_calls use the same files, calls and assertions. They differ only in the loop line, so they could be one test parametrized over the loop form.

Lines 261-284 and 288-311 repeat the same main/body setup, extract call, and assertions, with only 'while (1) {' and 'for (;;) {' differing in the body text.

  • The two loop forms may be kept separate on purpose to show that both spellings are handled, which is not stated in the file.

  • Reference checks do not establish safe deletion for dynamic or external consumers.

  • Found by the per-file sweep; not double-checked.

Code graph and static checks · 4994 functions depend on this change

Impact & health

Impact — 4994 functions depend on the 652 functions this change touches.

Health — this change adds coupling hotspots:

  • worse: extract() — 1337 callers, 79 callees
  • worse: walk_calls() — 1 callers, 49 callees
  • new: _c_cpp_walk_reachable_children() — 1 callers, 10 callees

Formal checks — 4994 functions this change can affect weren't formally checked in this review. Formal checks are informational only.

Gate & verification

✅ PASS — objectively clean (no health regressions, tests not run — proofs not run this pass (advisory)). Grounded, not self-assessed.

Advisory (not blocking):

  • verification_scope: 3293 function(s) in the blast radius were not formally verified this run

Test selection

102 of 608 test file(s) selected (17%) via static blast radius.

  • tests/test_4992_ts_import_types.py — impact
  • tests/test_astro_extraction.py — impact
  • tests/test_binary_media_words.py — impact
  • tests/test_build.py — impact
  • tests/test_c_return_reachability.py — impact, changed-test
  • tests/test_cache.py — impact
  • tests/test_cache_long_paths.py — impact
  • tests/test_cache_stale_import_target.py — impact
  • tests/test_cache_windows_case_4925.py — impact
  • tests/test_charmap_encoding.py — impact
  • tests/test_chunking.py — impact
  • tests/test_cjs_module_extension.py — impact
  • tests/test_code_only_scope_4923.py — impact
  • tests/test_cpp_alias_member_resolution.py — impact
  • tests/test_cpp_conditional_initializers.py — impact
  • tests/test_cpp_inherited_member_resolution.py — impact
  • tests/test_cpp_nested_and_cli.py — impact
  • tests/test_cpp_template_members.py — impact
  • tests/test_csharp_extension_calls.py — impact
  • tests/test_csharp_extension_metadata.py — impact
  • tests/test_csharp_extension_resolution.py — impact
  • tests/test_csharp_partial_classes.py — impact
  • tests/test_dart.py — impact
  • tests/test_dart_typedef.py — impact
  • tests/test_definition_file_portability.py — impact
  • tests/test_detect.py — impact
  • tests/test_dotnet.py — impact
  • tests/test_ejs_extractor.py — impact
  • tests/test_ext_tagged_id_clash.py — impact
  • tests/test_extract.py — impact
  • tests/test_extract_cache_location.py — impact
  • tests/test_extract_cli.py — impact
  • tests/test_extract_php_closures.py — impact
  • tests/test_grammar_cache_key.py — impact
  • tests/test_hook_content_freshness.py — impact
  • tests/test_ignore_file_encoding.py — impact
  • tests/test_import_extension_resolution.py — impact
  • tests/test_incremental_mtime_collision.py — impact
  • tests/test_indirect_call_block_scoped_shadow.py — impact
  • tests/test_indirect_dispatch.py — impact
  • tests/test_indirect_dispatch_assign_return.py — impact
  • tests/test_indirect_dispatch_getattr.py — impact
  • tests/test_java_member_calls.py — impact
  • tests/test_java_nested_type_identity.py — impact
  • tests/test_js_exported_scalar_bindings.py — impact
  • tests/test_js_member_collisions.py — impact
  • tests/test_language_override_lifecycle.py — impact
  • tests/test_language_overrides.py — impact
  • tests/test_languages.py — impact
  • tests/test_linked_worktree_reconcile.py — impact
  • … and 52 more

Selection is safe under the controlled-regression assumption; always-run tests + a periodic full run are the backstops. Advisory — it never changes the check verdict.

Every flagged function

  • extract() in graphify/extract.py:11900 · 1337 callers, 79 callees: fans out to 79 callees (efferent coupling); 1337 callers depend on it (afferent coupling)
  • walk_calls() in graphify/extractors/engine.py:11911 · 1 callers, 49 callees: fans out to 49 callees (efferent coupling)
  • _c_cpp_walk_reachable_children() in graphify/extractors/engine.py:8190 · 1 callers, 10 callees: fans out to 10 callees (efferent coupling)

scarsnow and others added 5 commits November 21, 2026 05:30
Stop walk_calls sibling traversal in compound_statement after
return_statement so unreachable CubeMX tails do not become calls edges.

Co-authored-by: Cursor <[email protected]>
CubeMX wraps ETH init in #if LWIP_ARP || LWIP_ETHERNET, so return and
unreachable Error_Handler() are siblings under preproc_if, not the
function compound_statement.

Co-authored-by: Cursor <[email protected]>
Replace simple sibling break-after-return with block reachability so
CubeMX dead tails stay omitted while goto labels, switch cases, and
static infinite loops (break-only fall-through) are handled correctly.
Warn on skipped unreachable calls by default (toggle API only).

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).
@scarsnow

Copy link
Copy Markdown

Thanks again for this fix. Both of your commits (d3f512ec, c0a57311) are now part of #5338 with authorship and SHAs unchanged, and they carry through the latest v8 merge. Since #5338 closes #5357, this PR can be closed once #5338 lands, or earlier if you prefer. I'd rather leave that call to you.

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

contributor Pull request from a returning community contributor needs:title PR title should follow the conventional-commit format

Projects

None yet

Development

Successfully merging this pull request may close these issues.

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

2 participants