Skip to content

Claude/fix 896 1081 byref writeback placement - #1317

Merged
GrahamTheCoder merged 25 commits into
icsharpcode:masterfrom
GrahamTheCoder:claude/fix-896-1081-byref-writeback-placement
Nov 18, 2026
Merged

GrahamTheCoder merged 25 commits into
icsharpcode:masterfrom
GrahamTheCoder:claude/fix-896-1081-byref-writeback-placement

Conversation

@GrahamTheCoder

@GrahamTheCoder GrahamTheCoder commented Nov 16, 2026 •

Copy link
Copy Markdown
Member

Fixes #896
Fixes #1081

Both issues come from the same gap. When a ByRef argument needs a temp (a property, a method result, an omitted Optional ByRef), VB copies the temp back straight after the call. Roslyn's LocalRewriter_Call.vb lowers the call to a sequence: the call's value, then the copy-backs as side effects. The converter instead emits the write-back after the whole converted statement. For field initializers there is no statement at all.

Root causes

  • VB -> C#: out param is set after return #896, return/throw/yield: PerScopeState.CreateLocalsAsync adds write-backs (AdditionalAssignment) after the statement. After return or throw they can never run. After yield return they only run when the consumer resumes.
  • Block headers (Select Case, Case, For start/bound, For Each, Using, SyncLock, With, Catch … When): the "statement" is the whole block, so the body saw the old value. For a later Case clause, the write-back ran even when the clause was never evaluated. NextStatementDefinitelyExecutedAfter treated these headers like plain statements. If/ElseIf and loop conditions were already handled.
  • VB -> C#: Byref optional parameters to New field initializer can throw nullref #1081: DeclarationNodeVisitor.CreateAdditionalLocalMembers read v.Initializer, which is null once an instance initializer has moved to the constructor. That threw a NullReferenceException. The same path dropped write-backs, left ph<guid> placeholders in constructors and initialX functions, and refused declarations with several variables or nested calls.
  • Found along the way: a partial class's initialX() function (used when the constructors are in another part) was always static. So any initializer that read an instance member failed with CS0120. The existing multi-file characterization initialAnArrayWithNonStaticInitializerReferencingOtherPart is one example.

Output by case (progressive fallback; the existing simple output is unchanged)

VB C#
F(P) as a statement, x = F(P), Dim x = F(P) unchanged: temp, call, write-back after
any shape without a write-back (e.g. Return F(New X)) unchanged single statement
Return F(P) int argv = P; long ret = F(ref argv); P = argv; return ret;
Throw CreateEx(P) / Yield F(P) same shape, with throw ex; / yield return ret;
Select Case F(P), Case F(P), For i = 0 To F(P), For Each x In F(P), Using d = F(P), SyncLock F(P), With F(P), Catch When F(P) the existing local-function fallback (as for If): int localF() { int argv = P; var ret = F(ref argv); P = argv; return ret; }, then switch (localF()) etc.
Private Second As New Outer(First) with an omitted Optional ByRef (#1081), instance initializer constructor Second = initSecond();, plus an instance method Outer initSecond() { string argx = ""; return new Outer(First, x: ref argx); }
Private _a As Integer = Inc(P), instance _a = Inc__a(); in the constructor; Inc__a() declares, calls, writes back and returns
Private Shared _c As Integer = Inc(SP) / any initializer that stays on the field static int Inc__c() { … SP = argv; return ret; } and _c = Inc__c();, the existing Foo__p1 style, now with the write-back
Private _d, _e As New Outer(First), or A As Integer = Inc(C), B As Integer = Inc(C) one method per variable, each emitted once
Two(p.Value, p.Value) (two ByRef arguments writing back to the same place) write-backs last argument first, as VB does; a call nested in an argument still writes back before its outer call
P = F(P), x = F(h.Items(x)), h = F(h.P) (= to a plain name or Me.X that a write-back reads) string argv = P; var ret = F(ref argv); P = argv; P = ret;
h.P = F(h.P), x += F(h.Items(x)), h.P = h.P.Ext() (compound, or a target with a receiver or index, that a write-back reads) local-function fallback: string localF() { …; h.P = argv; return ret; } then h.P = localF();
any local-function case except a loop condition, in a Structure, when the call uses an instance member write-back after the statement, or the result-local form for a simple assignment target (a local function can't use this there); known gap
Q = F(P) (assignment target not read by any write-back) unchanged compact form
Dim a = Inc(P), b = Inc(P) each declarator except a lone one takes the local-function fallback, so b reads the value a's call wrote back
WithEvents W As New Src(P) the method is emitted, and W = initW(); goes in the constructor
Partial class with constructors in another part initialX() contains the temps, and is now an instance method

The jump result uses var only when the VB expression's own type is the type the jump needs. Otherwise the converted type is written out, e.g. long ret for a widening return.

Design

  • PerScopeState.WithWriteBacksBefore (extracted in a pure refactor commit): if the current scope has write-backs, evaluate into a uniquely named local, write back, then use the local. Otherwise keep the single statement.
  • Block headers reuse the existing local-function fallback through NextStatementDefinitelyExecutedAfter, so it's a single change. Capturing each header into a variable before the block would be a little prettier, but every visitor would need its own change. For Case clauses and Catch When it would also be wrong, because they're evaluated conditionally.
  • Field initializers:
    • Each field initializer is converted in its own scope (CommonConversions.SplitVariableDeclarationsAsync).
    • If anything was hoisted, PerScopeState.CreateReturnBlockAsync builds a method body with the same machinery as method bodies: unique names, temps, write-backs before the return, and local functions. It doesn't consume the scope, so each variable sharing an initializer gets its own body.
    • DeclarationNodeVisitor takes the hoisted methods from the field scope as it emits them, so each one is emitted exactly once, for WithEvents fields too.
  • The ByRef-specific code is in CodeConverter/CSharp/ByRefArguments/:
    • ByRefArgumentHoister: temps, write-backs, and VB's reverse order per call.
    • WriteBackPlacement: whether a call needs the local function, and building it.
    • README.md: each case mapped to the VB/C# rules, its code, its sources and the known gaps. CodeConverter/CSharp/README.md points to it.

Decisions (accepted in review)

  1. VB -> C#: Byref optional parameters to New field initializer can throw nullref #1081: a wrapper method, rather than temps inlined in the constructor.
    • Inlined temps would be the most idiomatic output. They aren't cheap to do safely, though:
      • The initializers are copied into every constructor, so temps from different fields, and constructor parameters or locals, would need unique names in each constructor (CS0128/CS0136).
      • A partial class whose constructors are in another part needs a function anyway.
    • An omitted Optional ByRef argument already has no write-back. C# still needs a variable for ref (out _ only works for out), so a temp is the simplest correct form.
  2. The method is static only when the initializer stays on the field. C# field initializers can't call instance methods. A constructor call needs an instance method to read instance members.
  3. WithObjectInitializerCanReadFromPropertiesOfObjectAsync expectation changed: var init = new SomeClass(); became SomeClass @init = new SomeClass();. This is the same naming a method body uses for the same initializer.
  4. Multi-file characterization PartialClassPart.cs (3 copies): static int[] initialAnArray…() lost static. It read an instance field, so it didn't compile before.

Review round 1

  • Fixed, test-first:
    • A hoisted method was emitted twice when a field declaration had several declarators or array bounds (CS0111/CS0121).
    • A WithEvents field's method was never emitted (CS0103).
  • Declined at the time and added to the README's Known gaps:
    • Reverse copy-back order. This was later fixed; see "Known gaps revisited".
    • ReadOnly auto-property write-back, which is still a gap.

Review round 2

Review converged after 2 blind rounds: round 2 found only nitpicks and quality items.

  • Fixed:
    • Generated initializer method names are now checked against existing members, using the same unique-name check as hoisted locals. Before, initW() beside a user initW(), or Inc_v() beside a field Inc_v, gave CS0111/CS0121/CS0102. Partial-class initialX() functions keep their fixed name, because another part calls them by it.
    • Removed the dead rename loop in CreateExtraMethodMembers (pure refactor).
  • Added to the README's Known gaps (they existed before this PR and are out of scope here).

Known gaps revisited

Following the rule "fix a gap if it's a small change within code this PR already changes", two more gaps are fixed, each test-first in its own commit:

  • 0cffd9b: VB copies back a call's ByRef arguments in reverse order. This follows Roslyn's copyBackArray.ReverseContents() in LocalRewriter_Call.vb.
    • WithWriteBacksInVbOrderAsync (now in ByRefArgumentHoister) collects each argument list's write-backs and hoists them last-first. A nested call has already hoisted its own by then.
    • Self-verifying tests: two arguments to the same target, a nested call, inside Return, and in a Select Case header.
    • Changed expectation: ConstructorTests.TestHoistedOutParameterLambdaUsingByRefParameterAsync now writes back i before x for F3(x, i), as VB does.
  • 9967913: in Dim a = Inc(P), b = Inc(P), b read a stale P, because every temp was hoisted before the declaration and every write-back after it.
    • Now a declarator that isn't the first doesn't count as "straight after the previous statement", and one that isn't the last isn't followed by the next statement. Both take the existing local-function fallback.
    • A single declarator is unchanged. Static locals are excluded, because their initializers become fields.

Assignment placement (found in PR #10's review; existed before this PR)

  • Bug: VB writes back straight after the call, before the enclosing assignment stores its result. The converter wrote back after the statement, so:
    • h.Plain = SetValueReturnOther(h.Plain) ended with the written-back value, not the call's result.
    • x = F(h.Items(x)) and h = F(h.Plain) wrote back through the newly assigned x / h.
  • Fix (912e14d, refined in 81f4e51): when the assigned symbol appears in an expression that's written back:
    • For = to a plain name or Me.X, the result goes through a local: var ret = call; write-backs; P = ret;. There's nothing to evaluate before the call, so this is VB's order. It's the simplest form, and it works in a struct.
    • For a compound assignment, or a target with a receiver or index, the call takes the local-function fallback. C# then evaluates the target, calls (writing back inside the call) and stores the result, in VB's order. The ret form would read the target, or its receiver, only after the write-back.
    • Assignments whose target no write-back reads keep the compact form.
  • Before / after:
    // P = F(P), before
    string argv = P;
    P = F(ref argv);
    P = argv;
    // P = F(P), after
    string argv = P;
    var ret = F(ref argv);
    P = argv;
    P = ret;
    // h.Q = F(h.Q), after
    string localF() { string argv = h.Q; var ret = F(ref argv); h.Q = argv; return ret; }
    
    h.Q = localF();
  • Tests: 4 self-verifying tests, plus the conversion test WritesBackBeforeAssignmentCompletesWhenItChangesTheWriteBackTargetAsync.
    • The target and index tests failed before the fix. So did the receiver test, but that red run also hit a bug in the test itself (since fixed), so I haven't re-run that red step.
    • The compound-assignment test is a control: it passed before and after.
  • Not detected: the same object reached through different names, e.g. h1.P = F(h2.P) when h1 Is h2.

Review round 3 (blind, 9967913..74a6a79)

Fixed, test-first, one commit each:

  • 47b99ef: a local function always declared var ret, which hid a parameter or local called ret that the argument used (CS0841). It now picks a free name, as the jump statements already do.
  • 81f4e51: P = F(P) in a Structure gave CS1673, because the local function can't use this. Simple targets now use the result-local form (see above).
  • d1d4226: in a Structure, block headers, Dim declarators, and compound or receiver-target assignments keep the statement placement from before this PR when the call uses an instance member. Before this, they gave CS1673. That placement is late but compiles, and it's documented. (Round 4 extended this to operands and conditions.)
  • a09e199: an extension method whose first parameter is ByRef (h.P = h.P.Ext()) had its receiver ignored by the assignment check.
  • 92e89b1: removed a BOM that 74a6a79 added to NameExpressionNodeVisitor.cs.

Not changed:

  • The comparison is by symbol only, so a.P = F(b.P) takes the local function even when a and b are different objects. There's no sound cheap rule for "different object": two names, or Me and a local, can always refer to the same instance.
  • ArgumentConverter.ByRefArgumentHoister stays a public property.

Added to the known gaps:

Review round 4 (blind, 74a6a79..a2a214d): no new bugs

Fixed, one commit each:

  • d22baa0 (existed before this PR, but in code it changes): in a Structure, a call in a binary operand or a condition that used an instance member still became a local function capturing this (CS1673). Examples: Me.P = F(Me.P) + 1, 1 + F(P), P = F(F(P)), If conditions.
    • RequiresLocalFunction now returns false for any such call outside a loop condition, so the write-back stays after the statement: late, but it compiles.
    • That one check replaces the per-case flag d1d4226 threaded through the placement rules.
    • Loop conditions still use the local function, because they need a fresh write-back on each evaluation.
    • Pinned by a conversion test that saw CS1673 first.
  • c8c3931: tests for the remaining uncovered branches:
    • self-verifying: a parenthesized right side, a last Dim declarator, a Mid assignment to the written-back property (VB gives "ZZcdef"), and a ByRef extension receiver in a loop condition
    • conversion: a late-bound target (o.X = F(P), Option Strict Off), which takes the local function. That output puts the assignment on the local function's line, so the test opts out of the automatic comment-order check.

Declined: nothing else was raised.

Refactors from upstream review (#1317)

  • c39d4ca: renamed IsInLocalDeclarationWithSeveralDeclarators to …WithMultipleDeclarators and changed "several" to "multiple" in the wording.
  • 74a6a79: extracted the ByRef code into CodeConverter/CSharp/ByRefArguments/ (pure refactor; the full suite is unchanged):
    • ByRefArgumentHoister.cs: HoistByRefDeclaration and WithWriteBacksInVbOrderAsync, from ArgumentConverter.
    • WriteBackPlacement.cs: RequiresLocalFunction and its helpers, IsLoopCondition, and HoistAndCallLocalFunctionAsync, from NameExpressionNodeVisitor.
    • README.md: moved here from CodeConverter/CSharp/README.md, which now has one-line pointers.
  • These stay where they are, because the split would be artificial:
    • the hoisted node types (AdditionalAssignment and the rest) and PerScopeState, which every hoisting feature uses
    • the jump handling in MethodBodyExecutableStatementVisitor
    • the field-initializer method in CommonConversions, which wraps any hoisted statement, not only ByRef ones
    • RefConversion / GetRefConversionForExpression, which are used widely.

Out of scope / known gaps (pre-existing, see CodeConverter/CSharp/ByRefArguments/README.md)

  • In a Structure, where the call uses an instance member, the cases that would need a local function write back after the statement instead: late, but it compiles. Loop conditions there still give CS1673, as before this PR.
  • Aliasing through two names (h1.P = F(h2.P) with h1 Is h2), a ByRef New argument in an assignment (WF = New W(WF.Name)), the receiver re-evaluated on write-back (F(GetH(h).P) calls GetH twice; left to VB -> C#: Property Getter is used instead of Setter for ref argument #909 / PR Convert whole projects in one go #10), and a setter with side effects on the written-back target.
  • ByRef arguments of New (object creation) in a block header still write back after the block. The local-function path only handles method calls (InvocationExpressionSyntax), and widening it means changing several signatures, besides giving constructors a function name and return type.
  • A non-constant For … Step is re-evaluated on every iteration. This is a separate For-conversion bug, not specific to ByRef.
  • A ReadOnly auto-property passed ByRef in a constructor or initializer is not written back. Fixing it needs VB's "assignable here" rule, and a C# target the initializer method can assign: a get-only auto-property can only be assigned in the constructor (CS0200).
  • A lambda parameter inside a ByRef argument (Function(x) Inc(x.P)): the local function is hoisted outside the lambda, which gives CS0103. The fix belongs in lambda hoisting, which this PR doesn't touch.
  • An auto-property initializer (Public Property X As Integer = Inc(P)) leaves a ph… placeholder, which gives CS0103. Properties have no way to emit an extra method, and instance-referencing property initializers aren't moved to the constructor at all, so this needs new plumbing.
  • Partial-class instance initializers run in part order, not in declaration order. Fixing that needs coordination across parts.

Tests

  • Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb: 43 self-verifying tests. They cover:

    • return, return with a widening or Object conversion, return when the name ret is taken, property getter, multi-line lambda, throw, yield
    • Select Case, Case clause, a later Case that's never reached, For start and bound, For Each, nested headers, Using, SyncLock, With, Catch When
    • the VB -> C#: Byref optional parameters to New field initializer can throw nullref #1081 repro, instance initializers in declaration order (including Inc(Counter) + Counter * 10), several variables in one declarator, several declarators with array bounds, a WithEvents field, a Shared initializer, a partial-class initializer
    • reverse write-back order (two arguments, a nested call, in Return, in a block header), and multiple Dim declarators
    • assignments that change what's written back (the target itself, an index, the receiver, an extension receiver, in a Structure), and a compound assignment
    • a local function's result name when ret is taken
    • a parenthesized right side, a last Dim declarator, Mid assignment, and an extension receiver in a loop condition
    • a control test for the unchanged shapes.

    Each fix was seen red first, for the expected reason, with two exceptions:

    • the receiver-assignment test, noted under "Assignment placement"
    • the Structure assignment test, whose CS1673 I didn't reproduce myself; the round 3 reviewer reproduced it on that input.
  • ByRefTests.cs: WritesBackBeforeJumpingIssue896Async, WritesBackBeforeBlockBodyAsync, OmittedOptionalRefInInstanceFieldInitializerIssue1081Async (the exact repro), FieldInitializersWriteBackAsync, FieldInitializerMethodNamesAvoidExistingMembersAsync, WritesBackBeforeAssignmentCompletesWhenItChangesTheWriteBackTargetAsync, StructureKeepsStatementPlacementWhereALocalFunctionWouldNeedThisAsync, StructureKeepsStatementPlacementForOperandsThatWouldNeedThisAsync and LateBoundAssignmentTargetTakesTheLocalFunctionAsync pin the output.

  • Every commit builds.

Suite vs baseline

  • Full suite (net10.0) at c8c3931: 1477 passed, 5 skipped, 0 failed.
  • Master baseline: 1425 passed, 5 skipped, 0 failed.
  • The difference is the 52 new tests. Existing expectations changed only where listed above.

Coverage of changed lines

I ran the full suite with XPlat Code Coverage before review round 1. Every changed line is covered except:

  • MethodBodyExecutableStatementVisitor.GetResultTypeSyntax: half the branches of typeInfo.Type is { } && Equals(...). The null-type branch is a guard, because a ByRef call's result always has a type.
  • CommonConversions.GetInitializerMethodName: its unqualified-name branch was unreachable and has been removed.

I haven't re-measured coverage for the commits after review round 1. Round 4 added tests for the branches its reviewer found uncovered.

🤖 Generated with Claude Code

https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg

…e#896)

VB copies a ByRef argument back to its property straight after the call.
The converter emits that write-back after the converted statement, which
after return/throw is unreachable, and after yield return only runs when
the consumer resumes.

When a jump statement has write-backs, evaluate its expression into a
local, write back, then jump with the local. Statements without
write-backs keep their single-statement form. The local uses var only
when the expression's own type is the one the jump needs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
A ByRef write-back is emitted after the converted statement. For a call
in a block header (Select Case, Case, For, For Each, Using, SyncLock,
With, Catch When) that statement is the whole block, so the body saw the
old value, and a later Case clause wrote back even when never evaluated.

These headers now take the same local-function fallback that If and
ElseIf conditions already use, so the write-back happens inside the call
site's own evaluation. Headers without write-backs keep their output.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
Pure refactor, so field initializers can reuse it. No output changes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
…#1081)

A ByRef argument that needs a temporary (e.g. an omitted Optional ByRef
parameter, or a property) hoists a declaration and maybe a write-back.
A field initializer has no statement to put them in. The old code moved
them into a static method, but read v.Initializer, which is null once an
instance initializer has moved to the constructor: NullReferenceException.
That path also dropped write-backs, left placeholder names in the
constructor and partial-class initial functions, and refused fields with
several variables or nested calls.

Now each field initializer is converted in its own scope. If anything was
hoisted, the initializer becomes a call to a method built with the same
statement machinery as method bodies: temporaries, the write-backs before
returning, and local functions. The method is static when the initializer
stays on the field, and an instance method when it moves to the
constructor. Initializers without temporaries are unchanged.

WithObjectInitializerCanReadFromPropertiesOfObjectAsync: the object
initializer's temporary now gets the same unique name and explicit type as
in a method body (`SomeClass @init`), instead of an unchecked `var init`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
When a type has constructors in another part, a non-static field
initializer becomes an initialX() function that the other part's
constructor calls. It was always emitted static, so any initializer
reading an instance member (which is why it isn't on the field) failed
to compile with CS0120, including one holding ByRef temporaries.

The multi-file characterization initialAnArrayWithNonStaticInitializer...
read the instance field anInt from a static method; it now compiles.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
Coverage showed the unqualified-name branch is never hit: invoked names
are qualified (e.g. Me.Foo) before conversion. Falling back to init<Field>
would still be a valid name. No output changes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
A field declaration's hoisted methods were emitted for every variable
group of every declarator, so `A As Integer = Inc(C), B As Integer =
Inc(C)` or `Arr(Inc(C)), Other As Integer` declared a method twice
(CS0111/CS0121). A WithEvents field never emitted the method its
constructor assignment calls (CS0103).

Take the functions from the field scope as they're emitted, and emit
them for WithEvents fields too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
Reverse copy-back order of a call's arguments, and ReadOnly
auto-properties written back in constructors and initializers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
Every caller now references these methods by their final name, so
replacing placeholder ids in the constructor initializers never changed
anything. Pure refactor, no output changes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
A generated method like initW() or Inc_v() clashed with a user member of
the same name (CS0111/CS0102/CS0121). Use the unique-name check already
used for hoisted locals. Partial-class initialX() functions keep their
fixed name, since another part calls them by it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
Several declarators in one Dim, lambda parameters in ByRef arguments,
auto-property initializers, and partial-class initializer order.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
Roslyn's LocalRewriter_Call.vb reverses each call's copy-backs
(copyBackArray.ReverseContents(), kept from Dev11), which is observable
when two arguments write back to the same place: Two(p.Value, p.Value)
leaves the first argument's value. The converter wrote back in argument
order.

ArgumentConverter now collects the write-backs of each argument list and
hoists them last-first once the list is converted. A call nested in an
argument has finished its own list by then, so it still writes back
before the outer call, and the result composes with the jump, block
header and field initializer placement.

TestHoistedOutParameterLambdaUsingByRefParameterAsync: F3(x, i) now
writes back i before x, as VB does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
VB evaluates `Dim a = Inc(p.X), b = Inc(p.X)` declarator by declarator,
writing back after each call. The converter hoisted every temporary
before the declaration and every write-back after it, so b read a stale
value.

A declarator that isn't the first is no longer definitely evaluated
straight after the previous statement, and one that isn't the last is no
longer followed by the next statement, so they take the existing
local-function fallback. A single declarator keeps its output. Static
locals are left as they were, since their initializers become fields.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
Comment thread CodeConverter/CSharp/README.md Resolved
VB writes back a ByRef temp straight after its call, before the
enclosing assignment stores its result. The converter wrote back after
the statement, so `h.Plain = F(h.Plain)` ended with the written-back
value instead of the call's result, and `x = F(h.Items(x))` or
`h = F(h.Plain)` wrote back through the newly assigned x or h.

When the assigned symbol appears in an argument that's written back,
the call takes the existing local-function fallback. C# then evaluates
the assignment target, calls (writing back), and stores the result, in
VB's order; compound assignments still read their target first. A
`var ret = call; write-backs; target = ret;` form was not used: it would
read a compound target, or evaluate the target's receiver, after the
write-back. Assignments whose target isn't read by any write-back keep
the compact form.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
Pure rename: IsInLocalDeclarationWithSeveralDeclarators becomes
IsInLocalDeclarationWithMultipleDeclarators, and the README wording
matches. No behaviour change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
Pure refactor, no output changes.

- ByRefArgumentHoister: the temporary and write-back for a ByRef
  argument, and VB's reverse write-back order per call, moved from
  ArgumentConverter (which now exposes it as ByRefArgumentHoister).
- WriteBackPlacement: whether a call's write-backs can follow the
  statement or need a local function, and building that local function,
  moved from NameExpressionNodeVisitor.
- The ByRef README moves into the folder; CSharp/README.md points to it.

The hoisted node types and PerScopeState stay where they are, since every
hoisting feature uses them, as do the jump and field-initializer parts,
which extend MethodBodyExecutableStatementVisitor and CommonConversions.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
The extraction commit wrote the file back with a BOM it didn't have.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
HoistAndCallLocalFunctionAsync always declared `var ret`. When the
argument used a parameter or local called ret, the declaration hid it
(CS0841), e.g. `Return Increment(ret.Value) + 1`. Pick a name that's
free where the call is, as the jump statements already do. Each local
function is its own scope, so other local functions still use `ret`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
`P = F(P)` took the local-function fallback, which can't use `this` in
a struct (CS1673). When the target is a plain name or Me.X, there is
nothing to evaluate before the call, so
`var ret = F(ref argv); P = argv; P = ret;` keeps VB's order. It is
also simpler output, and works in a struct.

Compound assignments and targets with a receiver or index
(`h.P = F(h.P)`, `x += F(h.Items(x))`) still use the local function,
since C# must evaluate the target before the call as VB does.

WritesBackBeforeAssignmentCompletesWhenItChangesTheWriteBackTargetAsync:
`P = F(P)` and `h = G(h.P)` now use the result local; an `h.Q = F(h.Q)`
case pins the local function.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
A local function in a struct can't use `this` (CS1673). The block
header, Dim declarator and assignment placements added in this PR use
local functions, so in a struct they turned compiling code into a
compile error. Where the call uses an instance member of a struct,
they now keep writing back after the statement, as before this PR.
That's late, but it compiles; it's listed as a known gap.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
`h.P = h.P.Ext()` (the extension's first parameter is ByRef) wrote the
receiver back after the assignment, so h.P ended with the written-back
value instead of the call's result. The assignment check only looked
at the argument list. The receiver now counts as a written-back
expression, both for the local-function fallback and for the
result-local form (`P = P.Ext()`).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
Aliasing through two names, the conservative receiver comparison, a
ByRef constructor argument in an assignment, receivers re-evaluated on
write-back, and setters with side effects on the written-back target.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
In a Structure, a call in a binary operand or condition that uses an
instance member (`Me.P = F(Me.P) + 1`, `1 + F(P)`, `P = F(F(P))`, `If`
conditions) still became a local function capturing `this` (CS1673).
This existed before this PR, but it's in code the PR changes.

RequiresLocalFunction now returns false for any such call outside a
loop condition, so the write-back stays after the statement: late but
compiling, as for block headers. That covers every placement rule at
once, so the flag threaded into each of them is removed. Loop conditions
still need a fresh write-back per evaluation and keep the local
function.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
Self-verifying tests for a parenthesized call assigned to the property
it writes back, a last Dim declarator, a Mid assignment to the
written-back property, and a ByRef extension receiver in a loop
condition. A conversion test pins a late-bound target (`o.X = F(P)`
with Option Strict Off), which takes the local function. That output
puts the assignment on the local function's line, so the test opts out
of the automatic comment-order check.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
@GrahamTheCoder
GrahamTheCoder merged commit 3d19b46 into icsharpcode:master Nov 18, 2026
3 checks passed
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.

VB -> C#: Byref optional parameters to New field initializer can throw nullref VB -> C#: out param is set after return

2 participants