Skip to content

feat(csharp): type foreach loop variables for receiver resolution - #4423

Closed
nixvideojuego-ui wants to merge 1 commit into
Graphify-Labs:v8from
nixvideojuego-ui:feat/csharp-foreach-loop-variable-type
Closed

nixvideojuego-ui wants to merge 1 commit into
Graphify-Labs:v8from
nixvideojuego-ui:feat/csharp-foreach-loop-variable-type

Conversation

@nixvideojuego-ui

Copy link
Copy Markdown
Contributor

What does this PR do?

Closes #4420.

A C# foreach loop variable had no binding in _csharp_method_receiver_types, so a call on it, or a chain starting at it, never resolved across files. For example, foreach (var a in agents.Values) a.look.Animate(); produced no edge.

Changes:

  • Binding the loop variable. It is bound inside its loop (the foreach_statement range):
    • to its explicit type (foreach (Agent a in xs));
    • for var, to what the iterated class field or property yields.
  • What a field or property yields. This is recorded per class next to the existing name[] element entries (C#: calls through a member chain, through element access, or inside a constructor produce no edge (follow-up to #3797) #4246), under name{}, name.Values{} and name.Keys{}:
    • the element of a T[] or a sequence type (List, IList, IReadOnlyList, IEnumerable, ICollection, IReadOnlyCollection, HashSet, ISet, SortedSet, Queue, Stack, LinkedList);
    • a dictionary's value or key type for f.Values / f.Keys.
  • Shadowing. var loops are typed after the walk, once every local and parameter is bound. A loop over a name that a local or parameter shadows at that point stays untyped.

Type of change

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

Verification & Invariants

Invariant: a loop variable is typed only from evidence written in source, never guessed. The evidence is its declared type or the declared type of the field or property it iterates. Everything else stays untyped, so the existing no-binding / no-edge behavior is unchanged there.

  • Read the CONTRIBUTING.md guide.
  • Reproduced the issue and identified the invariant.
  • Made the smallest fix necessary.
  • Added tests in the new tests/test_csharp_foreach_loop_variable.py. The 4 positive tests fail on v8 (e8eb76e) and pass here. The 3 boundary tests pass on both:
    • a dictionary iterated directly stays untyped;
    • a shadowing local stays untyped;
    • the loop variable does not leak past its loop.
  • Kept the PR description synchronized with the final implementation.
  • Documented any limitations / unsupported cases explicitly.

Limitations: only class fields and properties are typed as the iterated source. A loop over a local, a parameter, a method result or a longer chain (s.modules) stays untyped, as today.

On a 1,512-file Unity C# codebase, this branch alone adds 58 calls edges and removes none. Examples:

  • foreach (var e in _spawned) e.Refresh() → MailEntry.Refresh();
  • entry.Deselect() → InventoryEntry.Deselect().

How was this tested?

uv run pytest tests/test_csharp_foreach_loop_variable.py        # 7 passed
uv run pytest tests -k "csharp or cs_ or dotnet or razor or unity"   # 444 passed, 13 skipped
uv run pytest tests                                             # 7612 passed, 15 failed, 247 skipped
uv run ruff check graphify/extractors/engine.py tests/test_csharp_foreach_loop_variable.py   # clean
uv run pyright graphify/extractors/engine.py graphify/extract.py      # no new diagnostics

All 15 full-suite failures also fail on an untouched v8 checkout on the same machine (Windows 11, Python 3.14), so they come from the environment: test_skillgen ×11, test_hooks ×1, the two *_memoization tests and one test_extract checkout-path test.

This PR is independent of #4418 / #4419 and passes on its own. All three also pass together (452 C# tests).

Graphify-specific checklist

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

🤖 Generated with Claude Code

A C# `foreach` loop variable had no binding in the method-scoped receiver
table, so a call on it (or a chain starting at it) never resolved across
files: `foreach (var a in agents.Values) a.look.Animate();` produced no edge.

The loop variable is now bound inside its loop: to its explicit type
(`foreach (Agent a in xs)`), or for `var` to what a class field or property
yields when iterated: the element of a `T[]` or of a sequence type, and a
dictionary's value or key type for `f.Values` / `f.Keys`. Iterating a
dictionary itself (KeyValuePair), nested collections, type parameters, and a
loop over a name that a local or parameter shadows stay untyped.

Closes Graphify-Labs#4420.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions

Copy link
Copy Markdown

Thanks for the pull request, @nixvideojuego-ui. 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.10 and 3.13, and that the change keeps extraction deterministic.

@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 reviewed this change.

No issues found by static checks — no coupling regressions or blocking issues in the code graph. That is not the same as safe to merge: see what was not checked.

Not checked: tests were not run; formal verification proved 0 of 2 changed function(s) (2 not verified).

Formal verification. PR-changed functions: 0/2 verified (0 proven, 0 may-equivalent, 0 distinguished) · 2 not verified (1 vacuous, 1 unsupported).

Not verified on this run: \_csharp\_method\_receiver\_types (vacuous: never exercised), \_extract\_generic (unsupported).


Graphify review — findings

Binds C# foreach loop variables so member calls on them resolve across files: an explicitly typed variable takes its declared type, and a var takes the element type of the class field or property it iterates (f, this.f, f.Values, f.Keys). _csharp_loop_element_types records those element types for arrays, single-argument sequence types, and dictionary keys/values. Iterating a dictionary directly (which yields KeyValuePair), nested collections, type parameters, and fields shadowed by a local or parameter leave the variable untyped, so no edge is emitted rather than a guessed one.

No blocking issues surfaced. 2 lower-confidence candidates did not survive cross-model review.

Analysis details — impact, health, verification

Impact & health

Graphify review

Impact — 917 functions depend on the 338 functions this change touches.

Health — this change adds coupling hotspots:

  • worse: walk() — 1 callers, 73 callees
  • worse: _csharp_method_receiver_types() — 1 callers, 7 callees

Verification — 917 functions in the blast radius were not formally verified this run (proofs are advisory here).

Gate & verification

graphify gate

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

Advisory (not blocking):

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

Test selection

Test selection

37 of 413 test file(s) selected (9%) via static blast radius.

  • tests/test_astro_extraction.py — impact
  • tests/test_build.py — impact
  • tests/test_cjs_module_extension.py — impact
  • tests/test_cpp_nested_and_cli.py — impact
  • tests/test_csharp_foreach_loop_variable.py — impact, changed-test
  • tests/test_csharp_partial_classes.py — impact
  • tests/test_dotnet.py — impact
  • tests/test_ejs_extractor.py — impact
  • tests/test_extract.py — impact
  • tests/test_extract_php_closures.py — impact
  • tests/test_import_extension_resolution.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_js_exported_scalar_bindings.py — impact
  • tests/test_languages.py — impact
  • tests/test_multilang.py — impact
  • tests/test_php_unparsed_casts.py — impact
  • tests/test_python_inherited_method_calls.py — impact
  • tests/test_python_property_reads.py — impact
  • tests/test_python_underscore_resolution.py — impact
  • tests/test_rationale.py — impact
  • tests/test_ruby_resolution.py — impact
  • tests/test_scala_context_bounds.py — impact
  • tests/test_scala_given_instances.py — impact
  • tests/test_scala_self_type.py — impact
  • tests/test_scala_top_level_binding.py — impact
  • tests/test_scala_type_definition.py — impact
  • tests/test_svelte_extraction.py — impact
  • tests/test_swift_computed_properties.py — impact
  • tests/test_swift_protocol_requirements.py — impact
  • tests/test_trailing_newline_not_a_syntax_error.py — impact
  • tests/test_ts_new_expression_calls.py — impact
  • tests/test_typescript_module_extensions.py — impact
  • tests/test_vue_extraction.py — impact

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.

Formal verification

Could not verify: Could not verify \_csharp\_method\_receiver\_types.

The verifier did not have enough to check \_csharp\_method\_receiver\_types, so it is saying so rather than guessing. No false assurance is the whole point.

Guarantee: No guarantee either way, this is an honest abstention, not a pass.

Note: Reason: no capturable inputs from the test suite; property tier: not verifiable: all 233 sampled inputs raised on both versions — the function never executed, so 'no divergence' would be vacuous (mostly AttributeError — names the real obstacle, not a sampling gap)

Could not verify: Could not verify \_extract\_generic.

The verifier did not have enough to check \_extract\_generic, so it is saying so rather than guessing. No false assurance is the whole point.

Guarantee: No guarantee either way, this is an honest abstention, not a pass.

Note: Reason: no capturable inputs from the test suite; property tier: parameter `config` is annotated `LanguageConfig` — outside the synthesizable primitive/collection set

· 2 more finding(s) on lines outside this diff (see the check run).

@nixvideojuego-ui

Copy link
Copy Markdown
Contributor Author

Ran the full suite on Python 3.10 and 3.13 as suggested (Windows 11, uv sync --frozen, no optional extras), next to an untouched v8 checkout (e8eb76e) on the same machine:

Python this branch untouched v8
3.10.21 7614 passed, 17 failed, 243 skipped 7607 passed, 17 failed, 243 skipped
3.13.15 7613 passed, 17 failed, 244 skipped 7606 passed, 17 failed, 244 skipped

The extra passes are this PR's 7 new tests. The 17 failures are the same tests on the branch and on untouched v8, on both versions, so they come from the Windows environment:

  • test_skillgen ×11 and test_skillgen_input_path_injection ×3;
  • the two *_memoization::test_absolute_path_lookup_skips_getcwd;
  • test_extract::test_c_include_out_of_root_target_id_is_deterministic_across_checkout_paths.

On determinism: the change only reads the parsed tree and the per-class field tables already built during extraction. It does not depend on the environment, filesystem order or anything nondeterministic.

safishamsi added a commit that referenced this pull request Oct 13, 2026
C# nameless / `new X()` / `foreach` receiver resolution (#4422, #4428,
#4423) and `_`/case-distinct node ids (#4416) change AST extraction
output, so warm caches must re-extract.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@safishamsi

Copy link
Copy Markdown
Member

Shipped in v0.9.90, just released to PyPI as graphifyy 0.9.90. Landed via an authorship-preserving cherry-pick (your commit keeps your name and counts on your contributor graph), which is why GitHub marks this closed rather than merged. Thanks @nixvideojuego-ui!

@safishamsi safishamsi closed this Oct 13, 2026
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.

[Feature]: C#: type foreach loop variables for receiver resolution

2 participants