Repository navigation
Place ByRef write-backs where VB runs them (return/throw/yield, block headers, field initializers) - #9
Closed
GrahamTheCoder wants to merge 12 commits into
Closed
Place ByRef write-backs where VB runs them (return/throw/yield, block headers, field initializers)#9GrahamTheCoder wants to merge 12 commits into
GrahamTheCoder wants to merge 12 commits into
Conversation
…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
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
GrahamTheCoder
force-pushed
the
claude/fix-896-1081-byref-writeback-placement
branch
from
November 12, 2026 01:24
a7363ef to
7377689
Compare
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
Owner
Author
|
PRed upstream as icsharpcode#1317 |
GrahamTheCoder
pushed a commit
that referenced
this pull request
Nov 17, 2026
Static locals, auto-property backing fields, every kind of write and intrinsic operators. #9's gap about re-evaluating a receiver is fixed here, and two pre-existing gaps are added. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
GrahamTheCoder
pushed a commit
that referenced
this pull request
Nov 18, 2026
Static locals, auto-property backing fields, every kind of write and intrinsic operators. #9's gap about re-evaluating a receiver is fixed here, and two pre-existing gaps are added. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
GrahamTheCoder
pushed a commit
that referenced
this pull request
Nov 18, 2026
Static locals, auto-property backing fields, every kind of write and intrinsic operators. #9's gap about re-evaluating a receiver is fixed here, and two pre-existing gaps are added. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
GrahamTheCoder
pushed a commit
that referenced
this pull request
Nov 18, 2026
Brings in #9's struct `ref this` local functions, With ref locals and ByRef parameters passed as ref parameters, and their tests. Conflicts: - ByRefTests.cs: both sides added tests at the end; kept both sets, and #10's BinaryExpressionRefParameterAsync expectation. - ByRefArguments/README.md: kept #10's gaps, dropped the Structure CS1673 gap that #9 fixed. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
GrahamTheCoder
pushed a commit
that referenced
this pull request
Nov 18, 2026
#9 now passes `ref this`, With ref locals and ByRef parameters to the write-back local function. Pin that a parameterized property's setter write-back and its index temporaries go through those: `self.set_Qr(tmp, ...)`, `self[i] = ...` for `Me(i)`, and `withBlock`/`s` for a With over a structure field or ByRef parameter, in If and While conditions and in an operand. No converter change was needed. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
GrahamTheCoder
pushed a commit
that referenced
this pull request
Nov 18, 2026
Brings in passing only the ByRef parameters the local function uses, and copying a With block's class reference instead of taking a ref to it. No conflicts; #10's expectations are unchanged by them. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
GrahamTheCoder
pushed a commit
that referenced
this pull request
Nov 18, 2026
Brings in taking the local function's ByRef parameter candidates from the VB operations, filtered by the names in the C# body, and #9's merge of master. No conflicts. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
GrahamTheCoder
pushed a commit
that referenced
this pull request
Nov 18, 2026
…assed test #9's new test expected `GetH(new H().Q).Q` read and then written back by calling `GetH` again. This branch's receiver temporaries evaluate it once, as VB does (UseTwiceRewriter), and write back to the same object: `var tmp = GetH(new H().Q); ... tmp.Q = argv1;`. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes icsharpcode#896
Fixes icsharpcode#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'sLocalRewriter_Call.vblowers 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
PerScopeState.CreateLocalsAsyncadds write-backs (AdditionalAssignment) after the statement. Afterreturnorthrowthey can never run. Afteryield returnthey only run when the consumer resumes.Select Case,Case,Forstart/bound,For Each,Using,SyncLock,With,Catch … When): the "statement" is the whole block, so the body saw the old value. For a laterCaseclause, the write-back ran even when the clause was never evaluated.NextStatementDefinitelyExecutedAftertreated these headers like plain statements. If/ElseIf and loop conditions were already handled.DeclarationNodeVisitor.CreateAdditionalLocalMembersreadv.Initializer, which is null once an instance initializer has moved to the constructor. That threw a NullReferenceException. The same path dropped write-backs, leftph<guid>placeholders in constructors andinitialXfunctions, and refused declarations with several variables or nested calls.initialX()function (used when the constructors are in another part) was alwaysstatic. So any initializer that read an instance member failed with CS0120. The existing multi-file characterizationinitialAnArrayWithNonStaticInitializerReferencingOtherPartis one example.Output by case (progressive fallback; the existing simple output is unchanged)
F(P)as a statement,x = F(P),Dim x = F(P)Return F(New X))Return F(P)int argv = P; long ret = F(ref argv); P = argv; return ret;Throw CreateEx(P)/Yield F(P)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)If):int localF() { int argv = P; var ret = F(ref argv); P = argv; return ret; }, thenswitch (localF())etc.Private Second As New Outer(First)with an omittedOptional ByRef(icsharpcode#1081), instance initializerSecond = initSecond();, plus an instance methodOuter 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 returnsPrivate Shared _c As Integer = Inc(SP)/ any initializer that stays on the fieldstatic int Inc__c() { … SP = argv; return ret; }and_c = Inc__c();, the existingFoo__p1style, now with the write-backPrivate _d, _e As New Outer(First), orA As Integer = Inc(C), B As Integer = Inc(C)Two(p.Value, p.Value)(two ByRef arguments writing back to the same place)P = F(P),x = F(h.Items(x)),h = F(h.P)(=to a plain name orMe.Xthat 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)string localF() { …; h.P = argv; return ret; }thenh.P = localF();If/ElseIf, loop conditions, block headers,Dimdeclarators, assignments) in aStructure, when the body usesthis(including throughWith Me)ref:int localF(ref S self) { int argv = self.P; var ret = F(ref argv); self.P = argv; return ret; }, thenif (localF(ref this) > 0)With structField(class or structure)withBlockref local is passed byref:int localF(ref T withBlock) { … }, thenlocalF(ref withBlock)With b, wherebis a ByRef parameterbis passed byref:int localF(ref Box b) { … }, thenlocalF(ref b); a ByRef parameter used only in a header that was evaluated intowithBlockisn't passed, and neither is a type with the parameter's name (H.Sbeside<Out> ByRef h As H)With bover a class-typed variablevar withBlock = b;(it wasref var withBlock = ref b;, which followed a reassignment ofbinside the block)Return Inc(P) + ValueOf(Me)in aStructure,ValueOf(ByRef s As S)Meis taken at the call:int localValueOf(ref S self) { var args = self; var ret = ValueOf(ref args); return ret; }Q = F(P)(assignment target not read by any write-back)Dim a = Inc(P), b = Inc(P)breads the valuea's call wrote backWithEvents W As New Src(P)W = initW();goes in the constructorinitialX()contains the temps, and is now an instance methodThe jump result uses
varonly when the VB expression's own type is the type the jump needs. Otherwise the converted type is written out, e.g.long retfor 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.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. ForCaseclauses andCatch Whenit would also be wrong, because they're evaluated conditionally.CommonConversions.SplitVariableDeclarationsAsync).PerScopeState.CreateReturnBlockAsyncbuilds 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.DeclarationNodeVisitortakes the hoisted methods from the field scope as it emits them, so each one is emitted exactly once, for WithEvents fields too.ref this(CS1673) and ref locals (CS8175) come from the body alone.Withreceiver to its expression). The body then drops any it no longer mentions.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.RefLocalReferences: marks references to ref locals so a local function can take them asrefparameters.README.md: each case mapped to the VB/C# rules, its code, its sources and the known gaps.CodeConverter/CSharp/README.mdpoints to it.Decisions (accepted in review)
ref(out _only works forout), so a temp is the simplest correct form.WithObjectInitializerCanReadFromPropertiesOfObjectAsyncexpectation changed:var init = new SomeClass();becameSomeClass @init = new SomeClass();. This is the same naming a method body uses for the same initializer.PartialClassPart.cs(3 copies):static int[] initialAnArray…()loststatic. It read an instance field, so it didn't compile before.Review round 1
ReadOnlyauto-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.
initW()beside a userinitW(), orInc_v()beside a fieldInc_v, gave CS0111/CS0121/CS0102. Partial-classinitialX()functions keep their fixed name, because another part calls them by it.CreateExtraMethodMembers(pure refactor).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'scopyBackArray.ReverseContents()inLocalRewriter_Call.vb.WithWriteBacksInVbOrderAsync(now inByRefArgumentHoister) collects each argument list's write-backs and hoists them last-first. A nested call has already hoisted its own by then.Return, and in aSelect Caseheader.ConstructorTests.TestHoistedOutParameterLambdaUsingByRefParameterAsyncnow writes backibeforexforF3(x, i), as VB does.9967913: inDim a = Inc(P), b = Inc(P),bread a staleP, because every temp was hoisted before the declaration and every write-back after it.Staticlocals are excluded, because their initializers become fields.Assignment placement (found in PR #10's review; existed before this PR)
h.Plain = SetValueReturnOther(h.Plain)ended with the written-back value, not the call's result.x = F(h.Items(x))andh = F(h.Plain)wrote back through the newly assignedx/h.912e14d, refined in81f4e51): when the assigned symbol appears in an expression that's written back:=to a plain name orMe.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.retform would read the target, or its receiver, only after the write-back.WritesBackBeforeAssignmentCompletesWhenItChangesTheWriteBackTargetAsync.h1.P = F(h2.P)whenh1 Is h2.Review round 3 (blind,
9967913..74a6a79)Fixed, test-first, one commit each:
47b99ef: a local function always declaredvar ret, which hid a parameter or local calledretthat the argument used (CS0841). It now picks a free name, as the jump statements already do.81f4e51:P = F(P)in aStructuregave CS1673, because the local function can't usethis. Simple targets now use the result-local form (see above).d1d4226: in aStructure, block headers,Dimdeclarators, and compound or receiver-target assignments kept the statement placement from before this PR when the call used an instance member, instead of giving CS1673. (Superseded by482b2b9, see "Structures".)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 that74a6a79added toNameExpressionNodeVisitor.cs.Not changed:
a.P = F(b.P)takes the local function even whenaandbare different objects. There's no sound cheap rule for "different object": two names, orMeand a local, can always refer to the same instance.ArgumentConverter.ByRefArgumentHoisterstays a public property.Added to the known gaps:
Newargument in an assignment (WF = New W(WF.Name))F(GetH(h).P)), left to VB -> C#: Property Getter is used instead of Setter for ref argument icsharpcode/CodeConverter#909 / PR Write back ByRef parameterized properties through the setter, evaluating receiver and indexes once #10Review round 4 (blind,
74a6a79..a2a214d): no new bugsFixed, one commit each:
d22baa0: in aStructure, a call in a binary operand or a condition that used an instance member still became a local function capturingthis(CS1673). It was made to write back after the statement: compiling, but late. (Superseded by482b2b9, see "Structures".)c8c3931: tests for the remaining uncovered branches:Dimdeclarator, aMidassignment to the written-back property (VB gives"ZZcdef"), and a ByRef extension receiver in a loop conditiono.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.
Structures: the local function takes
ref this(a116487,482b2b9)The pending decision on the late struct write-back is resolved: compiling code with the wrong timing is no longer emitted.
this(CS1673), but it can take the struct as arefparameter. Where the call uses an instance member, the local function now takesref S self, is called withref this, and its body usesselfforthis. Example:int localInc(ref S self) { int argv = self.P; var ret = Inc(ref argv); self.P = argv; return ret; }thenif (b && localInc(ref this) > x).If/ElseIf, block headers,Dimdeclarators and compound or receiver-target assignments. It also fixes struct loop conditions, which gave CS1673 before this PR.this, including generic and extension calls andMyClass, so replacingthiscovers them. A nested call's local function getsref self. The parameter's name avoids names in scope (e.g.self1beside a parameter calledself).ref thisis legal in struct methods, property and event accessors, indexers, constructors (including before every field is assigned, since C# 11 structs are auto-default), iterators and async methods. Non-static local functions can still capture other locals and parameters. The one illegal context, a readonly member (CS1605), can't come from VB. VB has no read-only members, doesn't allowMyBasein a structure (BC30044), and doesn't allowMein a structure's lambdas (BC36638). So no remaining case needs a conversion error.thisthere, so the local function stays parameterless.Ifcondition into a statement before theif(var ret = F(ref argv); P = argv; if (ret)). It would be prettier for classes and structs alike, but it changes class output in many existing tests and needs per-visitor changes. Withref this, structs now match the class shape.StructureBlockHeaderDeclaratorAndCompoundAssignmentPassThisToTheLocalFunctionAsyncandStructureOperandsPassThisToTheLocalFunctionAsync.Structurewith a logging property. They coverIf,ElseIfwithMe.Value, a short-circuitedAndAlsooperand (no get or set unless called),WhileandDo … Loop Until, an operand followed by other evaluation, aDimdeclarator followed by another, nested calls, an instance method that sees its own state, a constructor, a property getter, and a shared member.StructureConditionsPassThisToTheLocalFunctionAsync.Structures: review round 1 (blind,
c8c3931..482b2b9)Fixed, test-first, one commit each:
55b4b4d(nitpick, pure refactor): the enclosing symbol and the operation are looked up once inHoistAndCallLocalFunctionAsync.7a2e552(ugly output): aWithblock's implicit receiver counted as a use ofthis, soWith b : If Inc(.X) > 0on a local in aStructuregot an unusedref S self. OnlyContainingTypeInstancereferences count now. Conversion test:StructureWithBlockOnALocalDoesNotPassThisAsync. (This brokeWith Me; see round 2.)74c5ded(bug):With Inner, whereInneris a structure field, declaresref var withBlock = ref Inner;. A local function can't use a ref local (CS8175). This was already broken in a class; the struct change made structures reach it too.RefLocalReferences). The local function takes each one it uses as arefparameter of the same name, as it already did for the enclosing method's ByRef parameters:int localInc(ref T withBlock) { … }thenlocalInc(ref withBlock).Structure, and the conversion testWithBlockRefLocalIsPassedToTheLocalFunctionAsync(class and structure). The conversion test was red with CS8175 first.66c9f04(bug, existed before this PR): in aStructure,Return Inc(P) + ValueOf(Me)withValueOf(ByRef s As S)hoisted the copy ofMe(var args = this;) beforeInc's write-back. VB returned 2 and C# returned 1. The same happened afterAndAlso.Mewas never considered to need the local function. That's right for a class, where a copy is the same reference whenever it's taken, but not for a structure. A structure'sMenow takes the local function like any other temporary.+andAndAlso) and the conversion testStructureMePassedByRefAfterAWriteBackTakesTheLocalFunctionAsync, which was red first.44a635f: added these older gaps to the README; they're unchanged here:Inc(Item(0))writes back withget_Item(0) = argv(CS0131). VB -> C#: Property Getter is used instead of Setter for ref argument icsharpcode/CodeConverter#909 / PR Write back ByRef parameterized properties through the setter, evaluating receiver and indexes once #10 handles parameterized properties.Inc(InnerProp.P), whereInnerPropreturns a structure, gives CS1612.Select Case Inc(P)withCase Inc(P)gives CS0825 oncase var @case when.Structures: review round 2 (blind,
482b2b9..44a635f)Fixed, test-first, one commit each. Each test was red for the reported error first.
0b2cc99(bug, regression from7a2e552):With Mein aStructuregave CS1673. The implicit receiver there isthis, so the parameterless local function used it.thisbefore simplification, so it needsref S selfexactly when it contains athis. That's what triggers CS1673, so the two can't drift apart.With Mein the logging structure) and the conversion testStructureWithMePassesThisToTheLocalFunctionAsync.e762991(bug, regression from74c5ded): aWithover a structure field inside a lambda argument (If Apply(P, Function() … With Inner …) > 0) passedref withBlockto the local function, butwithBlockis only declared inside the lambda (CS0103). Now ref locals declared within the body are skipped.RefLocalDeclaredInsideTheLocalFunctionIsNotPassedAsync. That conversion test opts out of the comment-order check, because the multi-line lambda is emitted inside the local function, before theIf's line.067bc7f(bug, existed before this PR, sibling of CS8175):With b, wherebis a ByRef parameter (class or structure), reusesbdirectly as the receiver. The parameter reference is in theWithheader, so the local function used it without taking it (CS1628).Withblock's implicit receiver is resolved to theWithexpression's operations.WithByRefParameterIsPassedToTheLocalFunctionAsync.1f19e57(quality, pure refactor):RefLocalReferenceskeeps the ref local'sTypeSyntax, keyed by the annotation, instead of storing it as text and parsing it again.Declined, as the reviewer suggested:
ValueOf(Me) + ValueOf(Me)in a structure takes the local function for the second call even with no write-back. It's correct, and consistent with other non-variable arguments.Structures: review round 3 (blind,
44a635f..1f19e57): no runtime bugs in this PR's changesOne commit each:
879fd38(ugly output, regression from067bc7f): resolving aWithreceiver to the wholeWithexpression gave unusedrefparameters when the header had been evaluated intowithBlock, e.g.With arr(i)passedarrandWith GetBox(b)passedb.c15ced0combines it with the VB-side check.ByRefParameterOnlyInAWithHeaderIsNotPassedAsync, red with the unused parameters first.4645ea1(nitpick): a ref local reference without a recorded type now throws instead of giving a null type.553c78e(missing test):StructureSharedMemberDoesNotPassThisAsyncpinslocalInc()with noselffor a Shared member of aStructure. It's a characterization test, so it passed when added.bc8edc0(bug, existed before this PR, not ByRef-specific):With bover a class-typed variable that's reassigned inside the block emittedref var withBlock = ref b, which followed the reassignment. VB keeps the original object (VB "1,0", C# "0,1").Withconversion this PR already touches, so it's fixed rather than listed as a gap. Only a value type (or unconstrained type parameter) gets a ref local; a class reference is copied:var withBlock = b;.WithOverAReassignedClassVariableKeepsTheOriginalObject, red first.MethodStatementTests.WithBlockWithNullConditionalAccessAsync(ref var withBlock = ref _Data;becamevar withBlock = _Data;), andByRefParameterOnlyInAWithHeaderIsNotPassedAsync(var withBlock = arr[i];, so the local function takes nowithBlock).0d0ecc2: the suggested gapMyBase.GetHashCode()in a hoisted argument in aStructureisn't valid VB. I compiled it and the source gives BC30044 ("'MyBase' is not valid within a structure"), so there's nothing to convert. The README now says so instead of listing a gap.Structures: review round 4 (blind,
1f19e57..0d0ecc2)c15ced0(bug, regression from879fd38): matching parameter names case-insensitively in the converted body, whatever they bound to, counted a type named like a parameter as a use.Shared Function M(<Out> ByRef h As H)withIf Inc(H.S) > 0(a Shared property) gaveint localInc(ref H h) { int argv = H.S; … }, called aslocalInc(ref h).his unassigned at that call.ByRef h As IntegerwithInc(GetH(New H().Q).Q)passed an unusedref h.Withreceivers resolved to their expression (DescendantsResolvingWithReceiversis restored, without the precedence slip).withBlock.TypeNamedLikeAByRefParameterIsNotPassedAsynccovers both cases and was red with CS0269 and the unusedref h.OutParameterNamedLikeItsTypeIsNotPassedToTheLocalFunctionwas red with CS0269.3861a12: mergedorigin/master(no conflicts). This brings in master's MSBuild node-reuse hang fix.Out of scope / known gaps (pre-existing, see
CodeConverter/CSharp/ByRefArguments/README.md)h1.P = F(h2.P)withh1 Is h2), a ByRefNewargument in an assignment (WF = New W(WF.Name)), the receiver re-evaluated on write-back (F(GetH(h).P)callsGetHtwice; left to VB -> C#: Property Getter is used instead of Setter for ref argument icsharpcode/CodeConverter#909 / PR Write back ByRef parameterized properties through the setter, evaluating receiver and indexes once #10), and a setter with side effects on the written-back target.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.For … Stepis re-evaluated on every iteration. This is a separate For-conversion bug, not specific to ByRef.ReadOnlyauto-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).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.Public Property X As Integer = Inc(P)) leaves aph…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.Inc(Item(0)), CS0131; VB -> C#: Property Getter is used instead of Setter for ref argument icsharpcode/CodeConverter#909 / PR Write back ByRef parameterized properties through the setter, evaluating receiver and indexes once #10), a member of a structure returned by a property (Inc(InnerProp.P), CS1612), andSelect Case Inc(P)withCase Inc(P)(CS0825).Tests
Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb: 64 self-verifying tests. They cover:retis taken, property getter, multi-line lambda, throw, yieldInc(Counter) + Counter * 10), several variables in one declarator, several declarators with array bounds, a WithEvents field, a Shared initializer, a partial-class initializerReturn, in a block header), and multipleDimdeclaratorsStructure), and a compound assignmentretis takenDimdeclarator,Midassignment, and an extension receiver in a loop conditionStructure(see "Structures"),Withover a structure field in a class and in aStructure,With Mein aStructure, aWithinside a lambda argument,Withover ByRef parameters,Withover a reassigned class variable, anOutparameter named like its type, and a structure'sMepassed ByRef after a write-backEach fix was seen red first, for the expected reason, with two exceptions:
Structureassignment test, whose CS1673 I didn't reproduce myself; the round 3 reviewer reproduced it on that input.These
ByRefTests.cstests pin the output:WritesBackBeforeJumpingIssue896Async,WritesBackBeforeBlockBodyAsync,OmittedOptionalRefInInstanceFieldInitializerIssue1081Async(the exact repro),FieldInitializersWriteBackAsync,FieldInitializerMethodNamesAvoidExistingMembersAsyncWritesBackBeforeAssignmentCompletesWhenItChangesTheWriteBackTargetAsyncStructureBlockHeaderDeclaratorAndCompoundAssignmentPassThisToTheLocalFunctionAsync,StructureOperandsPassThisToTheLocalFunctionAsync,StructureConditionsPassThisToTheLocalFunctionAsync,StructureWithBlockOnALocalDoesNotPassThisAsync,StructureWithMePassesThisToTheLocalFunctionAsync,StructureSharedMemberDoesNotPassThisAsyncWithBlockRefLocalIsPassedToTheLocalFunctionAsync,RefLocalDeclaredInsideTheLocalFunctionIsNotPassedAsync,WithByRefParameterIsPassedToTheLocalFunctionAsync,ByRefParameterOnlyInAWithHeaderIsNotPassedAsync,TypeNamedLikeAByRefParameterIsNotPassedAsyncStructureMePassedByRefAfterAWriteBackTakesTheLocalFunctionAsync,LateBoundAssignmentTargetTakesTheLocalFunctionAsyncEvery commit builds.
Suite vs baseline
3861a12(after merging master;net10.0,--blame-hang): 1957 passed, 5 skipped, 0 failed, with no hang. I ran it twice: with and without a filter.origin/master(cd6dd93): 1926 passed, 5 skipped, 0 failed. Master already contains this branch's tests up toc8c3931. Counting[Fact]/[Theory]/<Fact>declarations, the tip adds 31 tests over master, and 1926 + 31 = 1957.Coverage of changed lines
I ran the full suite with
XPlat Code Coveragebefore review round 1. Every changed line is covered except:MethodBodyExecutableStatementVisitor.GetResultTypeSyntax: half the branches oftypeInfo.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.The struct
ref thisbranch inWriteBackPlacement.HoistAndCallLocalFunctionAsyncis covered by the ByRef conversion tests. Apart from that, 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