From 9c3ed817810c08b27fdfe8c9cb869ffe20617977 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 11 Nov 2026 17:06:27 +0000 Subject: [PATCH 01/25] Write back ByRef arguments before return, throw and yield (#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 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- .../MethodBodyExecutableStatementVisitor.cs | 35 +++- CodeConverter/CSharp/PerScopeState.cs | 12 ++ Tests/CSharp/ExpressionTests/ByRefTests.cs | 80 +++++++++ .../VBToCS/ByRefWriteBackPlacementTests.vb | 155 ++++++++++++++++++ 4 files changed, 279 insertions(+), 3 deletions(-) create mode 100644 Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb diff --git a/CodeConverter/CSharp/MethodBodyExecutableStatementVisitor.cs b/CodeConverter/CSharp/MethodBodyExecutableStatementVisitor.cs index 6e9720622..2d5395558 100644 --- a/CodeConverter/CSharp/MethodBodyExecutableStatementVisitor.cs +++ b/CodeConverter/CSharp/MethodBodyExecutableStatementVisitor.cs @@ -492,7 +492,8 @@ private ExpressionStatementSyntax CreateNewArrayAssignment(VBSyntax.ExpressionSy public override async Task> VisitThrowStatement(VBSyntax.ThrowStatementSyntax node) { - return SingleStatement(SyntaxFactory.ThrowStatement(await node.Expression.AcceptAsync(_expressionVisitor))); + var csExpression = await node.Expression.AcceptAsync(_expressionVisitor); + return WithWriteBacksBeforeJump(node.Expression, csExpression, "ex", SyntaxFactory.ThrowStatement); } public override async Task> VisitReturnStatement(VBSyntax.ReturnStatementSyntax node) @@ -502,7 +503,34 @@ public override async Task> VisitReturnStatement(VBS var csExpression = await node.Expression.AcceptAsync(_expressionVisitor); csExpression = CommonConversions.TypeConversionAnalyzer.AddExplicitConversion(node.Expression, csExpression); - return SingleStatement(SyntaxFactory.ReturnStatement(csExpression)); + return WithWriteBacksBeforeJump(node.Expression, csExpression, "ret", SyntaxFactory.ReturnStatement); + } + + /// + /// VB copies a ByRef argument back to its property straight after the call, so it happens before the statement jumps away. + /// Write-backs are normally emitted after the converted statement, which here would be unreachable (or, for yield, delayed until the consumer resumes). + /// So when there are any, evaluate the expression into a local, write back, then jump with that local. + /// Without write-backs the single statement is kept. + /// + private SyntaxList WithWriteBacksBeforeJump(VBSyntax.ExpressionSyntax vbExpression, ExpressionSyntax csExpression, string resultPrefix, + Func createJump) + { + if (csExpression is null) return SingleStatement(createJump(null)); + var writeBacks = _perScopeState.TakeWriteBacks(); + if (!writeBacks.Any()) return SingleStatement(createJump(csExpression)); + + var result = _perScopeState.Hoist(new AdditionalDeclaration(resultPrefix, csExpression, GetResultTypeSyntax(vbExpression))); + return SyntaxFactory.List(writeBacks.Append(createJump(result.IdentifierName))); + } + + /// + /// var is only safe when the expression's own type is the one the jump needs: e.g. Nothing or a lambda has no natural type in C#. + /// + private TypeSyntax GetResultTypeSyntax(VBSyntax.ExpressionSyntax vbExpression) + { + var typeInfo = _semanticModel.GetTypeInfo(vbExpression); + var isNaturalType = typeInfo.Type is { } type && SymbolEqualityComparer.Default.Equals(type, typeInfo.ConvertedType); + return CommonConversions.GetTypeSyntax(typeInfo.ConvertedType, useImplicitType: isNaturalType); } public override async Task> VisitContinueStatement(VBSyntax.ContinueStatementSyntax node) @@ -513,7 +541,8 @@ public override async Task> VisitContinueStatement(V public override async Task> VisitYieldStatement(VBSyntax.YieldStatementSyntax node) { - return SingleStatement(SyntaxFactory.YieldStatement(SyntaxKind.YieldReturnStatement, await node.Expression.AcceptAsync(_expressionVisitor))); + var csExpression = await node.Expression.AcceptAsync(_expressionVisitor); + return WithWriteBacksBeforeJump(node.Expression, csExpression, "ret", e => SyntaxFactory.YieldStatement(SyntaxKind.YieldReturnStatement, e)); } public override async Task> VisitExitStatement(VBSyntax.ExitStatementSyntax node) diff --git a/CodeConverter/CSharp/PerScopeState.cs b/CodeConverter/CSharp/PerScopeState.cs index a49fff977..e49a93554 100644 --- a/CodeConverter/CSharp/PerScopeState.cs +++ b/CodeConverter/CSharp/PerScopeState.cs @@ -78,6 +78,18 @@ public IReadOnlyCollection GetDefaultInit return _hoistedNodesPerScope.Peek().OfType().ToArray(); } + /// + /// Removes the ByRef write-backs hoisted so far in the current scope, for a statement that would otherwise skip or delay them, + /// e.g. a jump statement, after which a write-back would be unreachable. + /// + public IReadOnlyCollection TakeWriteBacks() + { + var hoistedNodes = _hoistedNodesPerScope.Peek().HoistedNodes; + var writeBacks = hoistedNodes.OfType().ToArray(); + hoistedNodes.RemoveAll(n => n is AdditionalAssignment); + return writeBacks.Select(AdditionalAssignment.CreateAssignment).ToArray(); + } + private StatementSyntax[] GetPostStatements() { var scopeState = _hoistedNodesPerScope.Peek(); diff --git a/Tests/CSharp/ExpressionTests/ByRefTests.cs b/Tests/CSharp/ExpressionTests/ByRefTests.cs index 74b47b178..c3f686e9c 100644 --- a/Tests/CSharp/ExpressionTests/ByRefTests.cs +++ b/Tests/CSharp/ExpressionTests/ByRefTests.cs @@ -995,4 +995,84 @@ public void Bar() }"); } + [Fact] + public async Task WritesBackBeforeJumpingIssue896Async() + { + await TestConversionVisualBasicToCSharpAsync(@"Imports System.Collections.Generic +Public Class C + Public Property P As Integer + + Function Inc(ByRef v As Integer) As Integer + v += 1 + Return v + End Function + + Function CreateException(ByRef v As Integer) As Exception + Return New Exception() + End Function + + Function ReturnsWrittenBack() As Long + Return Inc(P) + End Function + + Function ReturnsWithoutWriteBack() As Integer + Return Inc(New Integer) + End Function + + Iterator Function YieldsWrittenBack() As IEnumerable(Of Integer) + Yield Inc(P) + End Function + + Sub ThrowsWrittenBack() + Throw CreateException(P) + End Sub +End Class", @"using System; +using System.Collections.Generic; + +public partial class C +{ + public int P { get; set; } + + public int Inc(ref int v) + { + v += 1; + return v; + } + + public Exception CreateException(ref int v) + { + return new Exception(); + } + + public long ReturnsWrittenBack() + { + int argv = P; + long ret = Inc(ref argv); + P = argv; + return ret; + } + + public int ReturnsWithoutWriteBack() + { + int argv = new int(); + return Inc(ref argv); + } + + public IEnumerable YieldsWrittenBack() + { + int argv = P; + var ret = Inc(ref argv); + P = argv; + yield return ret; + } + + public void ThrowsWrittenBack() + { + int argv = P; + var ex = CreateException(ref argv); + P = argv; + throw ex; + } +}"); + } } \ No newline at end of file diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb new file mode 100644 index 000000000..5227537f1 --- /dev/null +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb @@ -0,0 +1,155 @@ +Imports System +Imports System.Collections.Generic +Imports System.Runtime.InteropServices +Imports Xunit + +Public Class ByRefWriteBackPlacementTests + + Public Sub ReturnWritesBackBeforeReturningIssue896() + Dim testClass As New OutParamTestClass + Assert.Equal(2, testClass.Number) + Dim result = CallSubWithOutParam(testClass) + Assert.True(result) + Assert.Equal(1, testClass.Number) + End Sub + + Private Shared Function CallSubWithOutParam(testClass As OutParamTestClass) As Boolean + Return SubWithOutParam(testClass.Number) + End Function + + Private Shared Function SubWithOutParam( ByRef out_a As Integer) As Boolean + out_a = 1 + Return True + End Function + + Private Class OutParamTestClass + Friend Property Number As Integer = 2 + End Class + + + Public Sub ReturnWithConversionWritesBackOnce() + Dim probe As New Probe + Assert.Equal(1L, ReturnAsLong(probe)) + Assert.Equal("get,set", probe.LogText) + End Sub + + Private Shared Function ReturnAsLong(probe As Probe) As Long + Return Increment(probe.Value) + End Function + + + Public Sub ReturnFromPropertyGetterWritesBack() + Dim probe As New Probe + Assert.Equal(1, probe.IncrementedValue) + Assert.Equal(1, probe.Stored) + End Sub + + + Public Sub ReturnInMultiLineLambdaWritesBack() + Dim probe As New Probe + Dim f As Func(Of Integer) = Function() + Return Increment(probe.Value) + End Function + Assert.Equal(1, f()) + Assert.Equal(1, probe.Stored) + End Sub + + + Public Sub ThrowWritesBackBeforeThrowing() + Dim probe As New Probe + Dim ex = Assert.Throws(Of InvalidOperationException)(Sub() ThrowCreated(probe)) + Assert.Equal("1", ex.Message) + Assert.Equal(1, probe.Stored) + Assert.Equal("get,set", probe.LogText) + End Sub + + Private Shared Sub ThrowCreated(probe As Probe) + Throw CreateException(probe.Value) + End Sub + + Private Shared Function CreateException(ByRef value As Integer) As Exception + value += 1 + Return New InvalidOperationException(value.ToString()) + End Function + + + Public Sub YieldWritesBackBeforeTheConsumerResumes() + Dim probe As New Probe + For Each value In YieldIncremented(probe) + Assert.Equal(value, probe.Stored) + Next + Assert.Equal(2, probe.Stored) + End Sub + + Private Shared Iterator Function YieldIncremented(probe As Probe) As IEnumerable(Of Integer) + Yield Increment(probe.Value) + Yield Increment(probe.Value) + End Function + + + Public Sub ReturnWritesBackWhenResultNameIsTaken() + Dim probe As New Probe + Assert.Equal(42, ReturnWithLocalNamedRet(probe)) + Assert.Equal(42, probe.Stored) + End Sub + + Private Shared Function ReturnWithLocalNamedRet(probe As Probe) As Integer + Dim ret = 41 + probe.Stored = ret + Return Increment(probe.Value) + End Function + + + Public Sub ReturnToWiderTypeWritesBack() + Dim probe As New Probe + Assert.Equal(CObj(1), ReturnAsObject(probe)) + Assert.Equal(1, probe.Stored) + End Sub + + Private Shared Function ReturnAsObject(probe As Probe) As Object + Return Increment(probe.Value) + End Function + + + Public Sub UnchangedStatementShapesStillWriteBack() + Dim probe As New Probe + Increment(probe.Value) + Dim local = Increment(probe.Value) + local = Increment(probe.Value) + Assert.Equal(3, local) + Assert.Equal(3, probe.Stored) + End Sub + + Private Shared Function Increment(ByRef value As Integer) As Integer + value += 1 + Return value + End Function + + Private Class Probe + Public Stored As Integer + Public ReadOnly Log As New List(Of String) + + Public ReadOnly Property LogText As String + Get + Return String.Join(",", Log) + End Get + End Property + + Public Property Value As Integer + Get + Log.Add("get") + Return Stored + End Get + Set(value As Integer) + Log.Add("set") + Stored = value + End Set + End Property + + Public ReadOnly Property IncrementedValue As Integer + Get + Return Increment(Value) + End Get + End Property + End Class +End Class From be0f178d95a3532a8974dae2aca2b1623278a7fd Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 11 Nov 2026 17:20:09 +0000 Subject: [PATCH 02/25] Write back ByRef arguments in block headers before the body 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 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- .../CSharp/NameExpressionNodeVisitor.cs | 12 +- Tests/CSharp/ExpressionTests/ByRefTests.cs | 138 ++++++++++++++++++ .../VBToCS/ByRefWriteBackPlacementTests.vb | 137 +++++++++++++++++ 3 files changed, 286 insertions(+), 1 deletion(-) diff --git a/CodeConverter/CSharp/NameExpressionNodeVisitor.cs b/CodeConverter/CSharp/NameExpressionNodeVisitor.cs index eb6de7f58..8bc25b7cc 100644 --- a/CodeConverter/CSharp/NameExpressionNodeVisitor.cs +++ b/CodeConverter/CSharp/NameExpressionNodeVisitor.cs @@ -610,7 +610,9 @@ private bool MayThrow(VBSyntax.ExpressionSyntax expression) } /// - /// Conservative version of _semanticModel.AnalyzeControlFlow(invocation).ExitPoints to account for exceptions + /// Conservative version of _semanticModel.AnalyzeControlFlow(invocation).ExitPoints to account for exceptions. + /// A block's header statement is followed by its body, so a write-back placed after the converted block would run too late + /// (or, for a later Case clause, run when the clause was never evaluated). /// private static bool NextStatementDefinitelyExecutedAfter(VBSyntax.InvocationExpressionSyntax invocation) { @@ -626,6 +628,14 @@ private static bool NextStatementDefinitelyExecutedAfter(VBSyntax.InvocationExpr case VBSyntax.IfStatementSyntax _: case VBSyntax.ElseIfStatementSyntax _: case VBSyntax.SingleLineIfStatementSyntax _: + case VBSyntax.SelectStatementSyntax _: + case VBSyntax.CaseStatementSyntax _: + case VBSyntax.ForStatementSyntax _: + case VBSyntax.ForEachStatementSyntax _: + case VBSyntax.UsingStatementSyntax _: + case VBSyntax.SyncLockStatementSyntax _: + case VBSyntax.WithStatementSyntax _: + case VBSyntax.CatchStatementSyntax _: return false; case VBSyntax.ExpressionSyntax _: case VBSyntax.StatementSyntax _: diff --git a/Tests/CSharp/ExpressionTests/ByRefTests.cs b/Tests/CSharp/ExpressionTests/ByRefTests.cs index c3f686e9c..10352be6e 100644 --- a/Tests/CSharp/ExpressionTests/ByRefTests.cs +++ b/Tests/CSharp/ExpressionTests/ByRefTests.cs @@ -1073,6 +1073,144 @@ public void ThrowsWrittenBack() P = argv; throw ex; } +}"); + } + + [Fact] + public async Task WritesBackBeforeBlockBodyAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Public Class C + Public Property P As Integer + + Function Inc(ByRef v As Integer) As Integer + v += 1 + Return v + End Function + + Function Arr(ByRef v As Integer) As Integer() + Return New Integer() {v} + End Function + + Function D(ByRef v As Integer) As IDisposable + Return Nothing + End Function + + Function IsOne(ByRef v As Integer) As Boolean + Return v = 1 + End Function + + Sub BlockHeaders() + Select Case Inc(P) + Case 1 + Console.WriteLine(1) + End Select + For i = 0 To Inc(P) + Console.WriteLine(i) + Next + For Each item In Arr(P) + Console.WriteLine(item) + Next + Using dd = D(P) + Console.WriteLine(3) + End Using + SyncLock Arr(P) + Console.WriteLine(4) + End SyncLock + With Arr(P) + Console.WriteLine(.Length) + End With + Try + Catch ex As Exception When IsOne(P) + End Try + End Sub + + Sub BlockHeaderWithoutWriteBack() + Select Case Inc(New Integer) + Case 1 + Console.WriteLine(1) + End Select + End Sub +End Class", @"using System; + +public partial class C +{ + public int P { get; set; } + + public int Inc(ref int v) + { + v += 1; + return v; + } + + public int[] Arr(ref int v) + { + return new int[] { v }; + } + + public IDisposable D(ref int v) + { + return null; + } + + public bool IsOne(ref int v) + { + return v == 1; + } + + public void BlockHeaders() + { + int localInc() { int argv = P; var ret = Inc(ref argv); P = argv; return ret; } + + switch (localInc()) + { + case 1: + Console.WriteLine(1); + break; + } + int localInc1() { int argv1 = P; var ret = Inc(ref argv1); P = argv1; return ret; } + + for (int i = 0, loopTo = localInc1(); i <= loopTo; i++) + Console.WriteLine(i); + int[] localArr() { int argv2 = P; var ret = Arr(ref argv2); P = argv2; return ret; } + + foreach (var item in localArr()) + Console.WriteLine(item); + IDisposable localD() { int argv3 = P; var ret = D(ref argv3); P = argv3; return ret; } + + using (var dd = localD()) + { + Console.WriteLine(3); + } + int[] localArr1() { int argv4 = P; var ret = Arr(ref argv4); P = argv4; return ret; } + + lock (localArr1()) + Console.WriteLine(4); + int[] localArr2() { int argv5 = P; var ret = Arr(ref argv5); P = argv5; return ret; } + + { + var withBlock = localArr2(); + Console.WriteLine(withBlock.Length); + } + bool localIsOne() { int argv6 = P; var ret = IsOne(ref argv6); P = argv6; return ret; } + + try + { + } + catch (Exception ex) when (localIsOne()) + { + } + } + + public void BlockHeaderWithoutWriteBack() + { + int argv = new int(); + switch (Inc(ref argv)) + { + case 1: + Console.WriteLine(1); + break; + } + } }"); } } \ No newline at end of file diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb index 5227537f1..2b0f32e53 100644 --- a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb @@ -110,6 +110,143 @@ Public Class ByRefWriteBackPlacementTests Return Increment(probe.Value) End Function + + Public Sub SelectCaseBodySeesWrittenBackValue() + Dim probe As New Probe + Select Case Increment(probe.Value) + Case 1 + Assert.Equal(1, probe.Stored) + Case Else + Assert.Fail("Unexpected case") + End Select + Assert.Equal("get,set", probe.LogText) + End Sub + + + Public Sub CaseClauseWritesBackBeforeItsBody() + Dim probe As New Probe + Dim x = 1 + Select Case x + Case Increment(probe.Value) + Assert.Equal(1, probe.Stored) + Case Else + Assert.Fail("Unexpected case") + End Select + Assert.Equal("get,set", probe.LogText) + End Sub + + + Public Sub ForBoundWritesBackBeforeTheBody() + Dim probe As New Probe + Dim iterations = 0 + For i = 0 To Increment(probe.Value) + iterations += 1 + Assert.Equal(1, probe.Stored) + Next + Assert.Equal(2, iterations) + Assert.Equal("get,set", probe.LogText) + End Sub + + + Public Sub ForEachCollectionWritesBackBeforeTheBody() + Dim probe As New Probe + For Each item In New Integer() {Increment(probe.Value)} + Assert.Equal(1, probe.Stored) + Next + For Each item In Repeat(probe.Value) + Assert.Equal(2, probe.Stored) + Next + Assert.Equal(2, probe.Stored) + End Sub + + Private Shared Function Repeat(ByRef value As Integer) As Integer() + value += 1 + Return New Integer() {value} + End Function + + + Public Sub UsingResourceWritesBackBeforeTheBody() + Dim probe As New Probe + Using d = CreateDisposable(probe.Value) + Assert.Equal(1, probe.Stored) + End Using + Assert.Equal("get,set", probe.LogText) + End Sub + + Private Shared Function CreateDisposable(ByRef value As Integer) As IDisposable + value += 1 + Return New IO.MemoryStream() + End Function + + + Public Sub SyncLockWritesBackBeforeTheBody() + Dim probe As New Probe + SyncLock CreateLock(probe.Value) + Assert.Equal(1, probe.Stored) + End SyncLock + End Sub + + Private Shared Function CreateLock(ByRef value As Integer) As Object + value += 1 + Return New Object() + End Function + + + Public Sub WithWritesBackBeforeTheBody() + Dim probe As New Probe + With CreateLock(probe.Value) + Assert.Equal(1, probe.Stored) + End With + End Sub + + + Public Sub ForStartWritesBackBeforeTheBody() + Dim probe As New Probe + For i = Increment(probe.Value) To 1 + Assert.Equal(1, probe.Stored) + Next + Assert.Equal("get,set", probe.LogText) + End Sub + + + Public Sub CatchFilterWritesBackBeforeTheHandler() + Dim probe As New Probe + Try + Throw New InvalidOperationException() + Catch ex As InvalidOperationException When IncrementIsOne(probe.Value) + Assert.Equal(1, probe.Stored) + End Try + Assert.Equal("get,set", probe.LogText) + End Sub + + Private Shared Function IncrementIsOne(ByRef value As Integer) As Boolean + Return Increment(value) = 1 + End Function + + + Public Sub LaterCaseClauseIsOnlyEvaluatedWhenReached() + Dim probe As New Probe + Select Case 1 + Case 1 + Assert.Equal(0, probe.Stored) + Case Increment(probe.Value) + Assert.Fail("Unexpected case") + End Select + Assert.Equal("", probe.LogText) + End Sub + + + Public Sub NestedBlockHeadersWriteBackBeforeTheirBodies() + Dim probe As New Probe + For Each item In Repeat(probe.Value) + Select Case Increment(probe.Value) + Case 2 + Assert.Equal(2, probe.Stored) + End Select + Next + Assert.Equal(2, probe.Stored) + End Sub + Public Sub UnchangedStatementShapesStillWriteBack() Dim probe As New Probe From e5728f8f02ffa2e1b808e33fcf4b403a7552b2b1 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 11 Nov 2026 17:24:29 +0000 Subject: [PATCH 03/25] Move write-back-before-use into PerScopeState Pure refactor, so field initializers can reuse it. No output changes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- .../MethodBodyExecutableStatementVisitor.cs | 11 ++--------- CodeConverter/CSharp/PerScopeState.cs | 16 +++++++++++++--- 2 files changed, 15 insertions(+), 12 deletions(-) diff --git a/CodeConverter/CSharp/MethodBodyExecutableStatementVisitor.cs b/CodeConverter/CSharp/MethodBodyExecutableStatementVisitor.cs index 2d5395558..d8818142c 100644 --- a/CodeConverter/CSharp/MethodBodyExecutableStatementVisitor.cs +++ b/CodeConverter/CSharp/MethodBodyExecutableStatementVisitor.cs @@ -507,20 +507,13 @@ public override async Task> VisitReturnStatement(VBS } /// - /// VB copies a ByRef argument back to its property straight after the call, so it happens before the statement jumps away. - /// Write-backs are normally emitted after the converted statement, which here would be unreachable (or, for yield, delayed until the consumer resumes). - /// So when there are any, evaluate the expression into a local, write back, then jump with that local. - /// Without write-backs the single statement is kept. + /// Write-backs are normally emitted after the converted statement, which after a jump would be unreachable (or, for yield, delayed until the consumer resumes). /// private SyntaxList WithWriteBacksBeforeJump(VBSyntax.ExpressionSyntax vbExpression, ExpressionSyntax csExpression, string resultPrefix, Func createJump) { if (csExpression is null) return SingleStatement(createJump(null)); - var writeBacks = _perScopeState.TakeWriteBacks(); - if (!writeBacks.Any()) return SingleStatement(createJump(csExpression)); - - var result = _perScopeState.Hoist(new AdditionalDeclaration(resultPrefix, csExpression, GetResultTypeSyntax(vbExpression))); - return SyntaxFactory.List(writeBacks.Append(createJump(result.IdentifierName))); + return SyntaxFactory.List(_perScopeState.WithWriteBacksBefore(csExpression, resultPrefix, () => GetResultTypeSyntax(vbExpression), createJump)); } /// diff --git a/CodeConverter/CSharp/PerScopeState.cs b/CodeConverter/CSharp/PerScopeState.cs index e49a93554..7d7e49dc3 100644 --- a/CodeConverter/CSharp/PerScopeState.cs +++ b/CodeConverter/CSharp/PerScopeState.cs @@ -79,10 +79,20 @@ public IReadOnlyCollection GetDefaultInit } /// - /// Removes the ByRef write-backs hoisted so far in the current scope, for a statement that would otherwise skip or delay them, - /// e.g. a jump statement, after which a write-back would be unreachable. + /// VB copies a ByRef argument back to its property straight after the call, so before a statement that uses the result jumps away. + /// When there are write-backs, evaluate the expression into a local, write back, then use that local. Without any, the single statement is kept. /// - public IReadOnlyCollection TakeWriteBacks() + public IReadOnlyCollection WithWriteBacksBefore(ExpressionSyntax expression, string resultPrefix, Func getResultType, + Func createStatementUsingResult) + { + var writeBacks = TakeWriteBacks(); + if (!writeBacks.Any()) return new[] { createStatementUsingResult(expression) }; + + var result = Hoist(new AdditionalDeclaration(resultPrefix, expression, getResultType())); + return writeBacks.Append(createStatementUsingResult(result.IdentifierName)).ToArray(); + } + + private IReadOnlyCollection TakeWriteBacks() { var hoistedNodes = _hoistedNodesPerScope.Peek().HoistedNodes; var writeBacks = hoistedNodes.OfType().ToArray(); From d636135757059bdc2e03c0e78b959bb309979948 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 11 Nov 2026 17:53:24 +0000 Subject: [PATCH 04/25] Keep ByRef temporaries of field initializers in a method (#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 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- CodeConverter/CSharp/CommonConversions.cs | 53 ++++++++++- .../CSharp/DeclarationNodeVisitor.cs | 56 +---------- CodeConverter/CSharp/HoistedFunction.cs | 7 +- CodeConverter/CSharp/PerScopeState.cs | 21 ++++ CodeConverter/CSharp/ValidSyntaxFactory.cs | 4 +- Tests/CSharp/ExpressionTests/ByRefTests.cs | 95 +++++++++++++++++++ .../CSharp/ExpressionTests/ExpressionTests.cs | 4 +- .../VBToCS/ByRefWriteBackPlacementTests.vb | 57 +++++++++++ 8 files changed, 231 insertions(+), 66 deletions(-) diff --git a/CodeConverter/CSharp/CommonConversions.cs b/CodeConverter/CSharp/CommonConversions.cs index 3f37f1985..cfc699336 100644 --- a/CodeConverter/CSharp/CommonConversions.cs +++ b/CodeConverter/CSharp/CommonConversions.cs @@ -61,6 +61,22 @@ public record VariablesDeclaration(CSSyntax.VariableDeclarationSyntax Decl, ITyp public async Task<(IReadOnlyCollection Variables, IReadOnlyCollection Methods)> SplitVariableDeclarationsAsync( VariableDeclaratorSyntax declarator, HashSet symbolsToSkip = null, bool preferExplicitType = false) + { + if (!IsField(declarator)) return await SplitVariableDeclarationsInCurrentScopeAsync(declarator, symbolsToSkip, preferExplicitType); + + // A field initializer has no statement to hoist into, so it gets its own scope, which ConvertEqualsValueClauseSyntaxAsync moves into a method + _typeContext.PerScopeState.PushScope(); + try { + return await SplitVariableDeclarationsInCurrentScopeAsync(declarator, symbolsToSkip, preferExplicitType); + } finally { + _typeContext.PerScopeState.PopScope(); + } + } + + private static bool IsField(VariableDeclaratorSyntax declarator) => declarator.Parent.IsKind(SyntaxKind.FieldDeclaration); + + private async Task<(IReadOnlyCollection Variables, IReadOnlyCollection Methods)> SplitVariableDeclarationsInCurrentScopeAsync( + VariableDeclaratorSyntax declarator, HashSet symbolsToSkip, bool preferExplicitType) { var vbInitValue = GetInitializerToConvert(declarator); var initializerOrMethodDecl = await vbInitValue.AcceptAsync(TriviaConvertingExpressionVisitor); @@ -129,7 +145,7 @@ public bool ShouldPreferExplicitType(VBSyntax.ExpressionSyntax exp, { var csTypeSyntax = GetTypeSyntax(declaredSymbolType); - bool isField = vbDeclarator.Parent.IsKind(SyntaxKind.FieldDeclaration); + bool isField = IsField(vbDeclarator); bool declaredConst = declaredSymbol is IFieldSymbol fieldSymbol && fieldSymbol.IsConst || declaredSymbol is ILocalSymbol localSymbol && localSymbol.IsConst; @@ -144,15 +160,17 @@ public bool ShouldPreferExplicitType(VBSyntax.ExpressionSyntax exp, if (isField && !declaredSymbol.IsStatic && !SemanticModel.IsDefinitelyStatic(vbName, vbInitValue)) { if (!_typeContext.Initializers.HasInstanceConstructorsOutsideThisPart) { var lhs = SyntaxFactory.IdentifierName(ConvertIdentifier(vbName.Identifier, sourceTriviaMapKind: SourceTriviaMapKind.None)); - _typeContext.Initializers.AdditionalInstanceInitializers.Add(new Assignment(lhs, CSSyntaxKind.SimpleAssignmentExpression, adjustedInitializerExpr.WithoutSourceMapping())); + var initializer = await WithHoistedNodesInMethodAsync(vbName, adjustedInitializerExpr, csTypeSyntax, isStatic: false); + _typeContext.Initializers.AdditionalInstanceInitializers.Add(new Assignment(lhs, CSSyntaxKind.SimpleAssignmentExpression, initializer.WithoutSourceMapping())); equalsValueClauseSyntax = null; } else { - var returnBlock = SyntaxFactory.Block(SyntaxFactory.ReturnStatement(adjustedInitializerExpr)); - _typeContext.PerScopeState.Hoist(new HoistedFunction(GetInitialValueFunctionName(vbName), csTypeSyntax, returnBlock, SyntaxFactory.ParameterList())); + var returnBlock = await _typeContext.PerScopeState.CreateReturnBlockAsync(vbName, adjustedInitializerExpr, csTypeSyntax, SemanticModel); + _typeContext.PerScopeState.HoistToParent(new HoistedFunction(GetInitialValueFunctionName(vbName), csTypeSyntax, returnBlock, SyntaxFactory.ParameterList())); equalsValueClauseSyntax = null; } } else { - equalsValueClauseSyntax = SyntaxFactory.EqualsValueClause(convertedInitializer); + var initializer = isField ? await WithHoistedNodesInMethodAsync(vbName, convertedInitializer, csTypeSyntax, isStatic: true) : convertedInitializer; + equalsValueClauseSyntax = SyntaxFactory.EqualsValueClause(initializer); } } else if (isField || declaredSymbol != null && SemanticModel.IsDefinitelyAssignedBeforeRead(declaredSymbol, vbName)) @@ -168,6 +186,31 @@ public bool ShouldPreferExplicitType(VBSyntax.ExpressionSyntax exp, return equalsValueClauseSyntax; } + /// + /// Temporaries for ByRef arguments (and their write-backs) need statements, which a field initializer can't contain. + /// A method keeps them together with the initializer whether it stays on the field or moves to the constructor. + /// It must be static to be called from a field initializer, and an instance method to read instance members from the constructor. + /// + private async Task WithHoistedNodesInMethodAsync(VBSyntax.ModifiedIdentifierSyntax vbName, ExpressionSyntax initializer, TypeSyntax type, bool isStatic) + { + if (!_typeContext.PerScopeState.HasHoistedNodes) return initializer; + + var body = await _typeContext.PerScopeState.CreateReturnBlockAsync(vbName, initializer, type, SemanticModel); + var methodName = GetInitializerMethodName(initializer, ConvertIdentifier(vbName.Identifier).ValueText); + _typeContext.PerScopeState.HoistToParent(new HoistedFunction(methodName, type, body, SyntaxFactory.ParameterList(), isStatic)); + return SyntaxFactory.InvocationExpression(ValidSyntaxFactory.IdentifierName(methodName)); + } + + private static string GetInitializerMethodName(ExpressionSyntax initializer, string fieldName) + { + var invokedName = initializer is CSSyntax.InvocationExpressionSyntax { Expression: var invoked } ? invoked switch { + CSSyntax.SimpleNameSyntax name => name, + CSSyntax.MemberAccessExpressionSyntax memberAccess => memberAccess.Name, + _ => null + } : null; + return invokedName is null ? "init" + fieldName.UppercaseFirstLetter() : $"{invokedName.Identifier.ValueText}_{fieldName}"; + } + /// /// In CS we need to lift non-static initializers to the constructor. But for partial classes these can be in different files. /// Rather than re-architect to allow communication between files, we create an initializer function, and call it from the other part, and just hope the name doesn't clash. diff --git a/CodeConverter/CSharp/DeclarationNodeVisitor.cs b/CodeConverter/CSharp/DeclarationNodeVisitor.cs index 74a905a13..ae3660a4d 100644 --- a/CodeConverter/CSharp/DeclarationNodeVisitor.cs +++ b/CodeConverter/CSharp/DeclarationNodeVisitor.cs @@ -553,15 +553,7 @@ private IEnumerable CreateMemberDeclarations(IReadOnlyC foreach (var f in fieldDecls) yield return f; } else { foreach (var method in CreateExtraMethodMembers()) yield return method; - - if (AdditionalLocals.GetDeclarations().Any()) { - foreach (var additionalDecl in CreateAdditionalLocalMembers(thisFieldModifiers, attributes, variablesDecl.Decl)) { - yield return additionalDecl; - } - } else { - yield return CS.SyntaxFactory.FieldDeclaration(CS.SyntaxFactory.List(attributes), thisFieldModifiers, variablesDecl.Decl); - } - + yield return CS.SyntaxFactory.FieldDeclaration(CS.SyntaxFactory.List(attributes), thisFieldModifiers, variablesDecl.Decl); } } } @@ -586,52 +578,6 @@ private IEnumerable CreateWithEventsMembers(SyntaxToken return fieldDecls; } - private IEnumerable CreateAdditionalLocalMembers(SyntaxTokenList convertedModifiers, List attributes, VariableDeclarationSyntax decl) - { - if (decl.Variables.Count > 1) { - // Currently no way to tell which _additionalLocals would apply to which initializer - throw new NotImplementedException( - "Fields with multiple declarations and initializers with ByRef parameters not currently supported"); - } - - var v = decl.Variables.First(); - var invocations = v.Initializer.Value.DescendantNodesAndSelf().OfType().ToArray(); - if (invocations.Length > 1) { - throw new NotImplementedException( - "Field initializers with nested method calls not currently supported"); - } - - string newMethodName; - if (invocations.OnlyOrDefault() is { Expression: {} e} && e.ChildNodes().OfType().LastOrDefault() is {} sns) { - newMethodName = $"{sns?.Identifier.ValueText}_{v.Identifier.ValueText}"; - } else { - newMethodName = "init" + v.Identifier.ValueText.UppercaseFirstLetter(); - } - - var declarationInfo = AdditionalLocals.GetDeclarations(); - - var localVars = declarationInfo - .Select(al => CommonConversions.CreateLocalVariableDeclarationAndAssignment(al.Prefix, al.Initializer)) - .ToArray(); - - // This should probably use a unique name like in MethodBodyVisitor - a collision is far less likely here - var newNames = declarationInfo.ToDictionary(l => l.Id, l => l.Prefix); - var newInitializer = PerScopeState.ReplaceNames(v.Initializer.Value, newNames); - - var body = CS.SyntaxFactory.Block(localVars.Concat(CS.SyntaxFactory.ReturnStatement(newInitializer).Yield())); - // Method calls in initializers must be static in C# - Supporting this is #281 - var methodDecl = ValidSyntaxFactory.CreateParameterlessMethod(newMethodName, decl.Type, body); - yield return methodDecl; - - var newVar = - v.WithInitializer(CS.SyntaxFactory.EqualsValueClause( - CS.SyntaxFactory.InvocationExpression(ValidSyntaxFactory.IdentifierName(newMethodName)))); - var newVarDecl = - CS.SyntaxFactory.VariableDeclaration(decl.Type, CS.SyntaxFactory.SingletonSeparatedList(newVar)); - - yield return CS.SyntaxFactory.FieldDeclaration(CS.SyntaxFactory.List(attributes), convertedModifiers, newVarDecl); - } - private IReadOnlyCollection CreateExtraMethodMembers() { var methodsInfos = AdditionalLocals.GetParameterlessFunctions(); diff --git a/CodeConverter/CSharp/HoistedFunction.cs b/CodeConverter/CSharp/HoistedFunction.cs index cca1c0c83..6b02f3b7d 100644 --- a/CodeConverter/CSharp/HoistedFunction.cs +++ b/CodeConverter/CSharp/HoistedFunction.cs @@ -8,20 +8,23 @@ internal class HoistedFunction : IHoistedNode private readonly TypeSyntax _returnType; private readonly BlockSyntax _block; private readonly ParameterListSyntax _parameters; + private readonly bool _isStatic; public string Id { get; } public string Prefix { get; } - public HoistedFunction(string localFuncName, TypeSyntax returnType, BlockSyntax block, ParameterListSyntax parameters) + /// Only used when hoisted to a member: it must be an instance method to be called from an instance context such as a constructor + public HoistedFunction(string localFuncName, TypeSyntax returnType, BlockSyntax block, ParameterListSyntax parameters, bool isStatic = true) { Id = $"hs{Guid.NewGuid().ToString("N")}"; Prefix = localFuncName; _returnType = returnType; _block = block; _parameters = parameters; + _isStatic = isStatic; } public IdentifierNameSyntax TempIdentifier => ValidSyntaxFactory.IdentifierName(Id).WithAdditionalAnnotations(PerScopeState.AdditionalLocalAnnotation); public LocalFunctionStatementSyntax AsLocalFunction(string functionName) => SyntaxFactory.LocalFunctionStatement(_returnType, SyntaxFactory.Identifier(functionName)).WithParameterList(_parameters).WithBody(_block); - public MethodDeclarationSyntax AsInstanceMethod(string functionName) => ValidSyntaxFactory.CreateMethod(functionName, _returnType, _parameters, _block); + public MethodDeclarationSyntax AsInstanceMethod(string functionName) => ValidSyntaxFactory.CreateMethod(functionName, _returnType, _parameters, _block, _isStatic); } \ No newline at end of file diff --git a/CodeConverter/CSharp/PerScopeState.cs b/CodeConverter/CSharp/PerScopeState.cs index 7d7e49dc3..eefdfdcb8 100644 --- a/CodeConverter/CSharp/PerScopeState.cs +++ b/CodeConverter/CSharp/PerScopeState.cs @@ -68,6 +68,27 @@ public T HoistToTopLevel(T additionalField) where T : IHoistedNode return additionalField; } + public bool HasHoistedNodes => _hoistedNodesPerScope.Peek().HoistedNodes.Any(); + + /// + /// For an expression that has no statement of its own to hoist into, e.g. a field initializer. + /// Declares the temporaries hoisted for it and writes back ByRef arguments before returning, as a statement would. + /// Leaves the current scope as it was, since each variable sharing an initializer evaluates it separately. + /// + public async Task CreateReturnBlockAsync(VBasic.VisualBasicSyntaxNode vbNode, ExpressionSyntax expression, TypeSyntax resultType, SemanticModel semanticModel) + { + var currentScope = _hoistedNodesPerScope.Peek(); + _hoistedNodesPerScope.Push(currentScope with { HoistedNodes = currentScope.HoistedNodes.ToList() }); + try { + var generatedNames = new HashSet(); + var statements = WithWriteBacksBefore(expression, "ret", () => resultType, SyntaxFactory.ReturnStatement); + var withLocals = await CreateLocalsAsync(vbNode, statements, generatedNames, semanticModel); + return SyntaxFactory.Block(CreateStatements(vbNode, withLocals, generatedNames, semanticModel)); + } finally { + PopScope(); + } + } + public IReadOnlyCollection GetDeclarations() { return _hoistedNodesPerScope.Peek().OfType().ToArray(); diff --git a/CodeConverter/CSharp/ValidSyntaxFactory.cs b/CodeConverter/CSharp/ValidSyntaxFactory.cs index 38bd3bf26..563b15de7 100644 --- a/CodeConverter/CSharp/ValidSyntaxFactory.cs +++ b/CodeConverter/CSharp/ValidSyntaxFactory.cs @@ -79,9 +79,9 @@ public static MethodDeclarationSyntax CreateParameterlessMethod(string newMethod return CreateMethod(newMethodName, type, parameterList, body); } - public static MethodDeclarationSyntax CreateMethod(string newMethodName, TypeSyntax type, ParameterListSyntax parameterList, BlockSyntax body) + public static MethodDeclarationSyntax CreateMethod(string newMethodName, TypeSyntax type, ParameterListSyntax parameterList, BlockSyntax body, bool isStatic = true) { - var modifiers = SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.StaticKeyword)); + var modifiers = isStatic ? SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.StaticKeyword)) : SyntaxFactory.TokenList(); var typeConstraints = SyntaxFactory.List(); var methodAttrs = SyntaxFactory.List(); diff --git a/Tests/CSharp/ExpressionTests/ByRefTests.cs b/Tests/CSharp/ExpressionTests/ByRefTests.cs index 10352be6e..24c6569b3 100644 --- a/Tests/CSharp/ExpressionTests/ByRefTests.cs +++ b/Tests/CSharp/ExpressionTests/ByRefTests.cs @@ -1211,6 +1211,101 @@ public void BlockHeaderWithoutWriteBack() break; } } +}"); + } + + [Fact] + public async Task OmittedOptionalRefInInstanceFieldInitializerIssue1081Async() + { + await TestConversionVisualBasicToCSharpAsync(@"Public Class FieldInitializationTest + Private First As New Inner() + Private Second As New Outer(First) +End Class + +Public Class Inner +End Class + +Public Class Outer + Sub New(inner As Inner, Optional ByRef x As String = """") + End Sub +End Class", @"using System.Runtime.InteropServices; + +public partial class FieldInitializationTest +{ + private Inner First = new Inner(); + + public FieldInitializationTest() + { + Second = initSecond(); + } + Outer initSecond() + { + string argx = """"; + return new Outer(First, x: ref argx); + } + + private Outer Second; +} + +public partial class Inner +{ +} + +public partial class Outer +{ + public Outer(Inner inner, [Optional, DefaultParameterValue("""")] ref string x) + { + } +}"); + } + + [Fact] + public async Task FieldInitializersWriteBackAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Public Class C + Public Property P As Integer + Private Shared Property SP As Integer + Private _a As Integer = Inc(P) + Private Shared _c As Integer = Inc(SP) + + Shared Function Inc(ByRef v As Integer) As Integer + v += 1 + Return v + End Function +End Class", @" +public partial class C +{ + public int P { get; set; } + private static int SP { get; set; } + + public C() + { + _a = Inc__a(); + } + int Inc__a() + { + int argv = P; + int ret = Inc(ref argv); + P = argv; + return ret; + } + + private int _a; + static int Inc__c() + { + int argv = SP; + int ret = Inc(ref argv); + SP = argv; + return ret; + } + + private static int _c = Inc__c(); + + public static int Inc(ref int v) + { + v += 1; + return v; + } }"); } } \ No newline at end of file diff --git a/Tests/CSharp/ExpressionTests/ExpressionTests.cs b/Tests/CSharp/ExpressionTests/ExpressionTests.cs index ef68b4387..d2bc5c561 100644 --- a/Tests/CSharp/ExpressionTests/ExpressionTests.cs +++ b/Tests/CSharp/ExpressionTests/ExpressionTests.cs @@ -1379,8 +1379,8 @@ public partial class SomeClass public string SomeProperty; static SomeClass initInstance() { - var init = new SomeClass(); - return (init.SomeProperty = init.SomeProperty + nameof(init.SomeProperty), init).init; // Second line gets moved + SomeClass @init = new SomeClass(); + return (@init.SomeProperty = @init.SomeProperty + nameof(@init.SomeProperty), @init).@init; // Second line gets moved } // Third line gets moved public static SomeClass Instance = initInstance(); // First line gets moved diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb index 2b0f32e53..3b444e9c2 100644 --- a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb @@ -257,6 +257,63 @@ Public Class ByRefWriteBackPlacementTests Assert.Equal(3, probe.Stored) End Sub + + Public Sub InstanceFieldInitializerWithOmittedOptionalByRefIssue1081() + Dim initialized As New FieldInitializers + Assert.Same(initialized.First, initialized.Second.ReceivedInner) + Assert.Equal("", initialized.Second.ReceivedX) + End Sub + + + Public Sub InstanceFieldInitializersWriteBackInDeclarationOrder() + Dim initialized As New FieldInitializers + Assert.Equal(1, initialized.A) + Assert.Equal(22, initialized.C) + Assert.Equal(2, initialized.Counter) + End Sub + + + Public Sub EachVariableOfAFieldDeclarationGetsItsOwnTemporary() + Dim initialized As New FieldInitializers + Assert.NotSame(initialized.D, initialized.E) + Assert.Same(initialized.First, initialized.D.ReceivedInner) + Assert.Same(initialized.First, initialized.E.ReceivedInner) + End Sub + + + Public Sub SharedFieldInitializerWritesBack() + Assert.Equal(1, SharedFieldInitializer.B) + Assert.Equal(1, SharedFieldInitializer.SharedCounter) + End Sub + + Private Class FieldInitializers + Public Property Counter As Integer + Public ReadOnly First As New Inner() + Public ReadOnly Second As New Outer(First) + Public ReadOnly A As Integer = Increment(Counter) + Public ReadOnly C As Integer = Increment(Counter) + Counter * 10 + Public ReadOnly D, E As New Outer(First) + End Class + + Private Class SharedFieldInitializer + Public Shared Property SharedCounter As Integer + Public Shared ReadOnly B As Integer = Increment(SharedCounter) + End Class + + Private Class Inner + End Class + + Private Class Outer + Public ReadOnly ReceivedInner As Inner + Public ReadOnly ReceivedX As String + + Sub New(inner As Inner, Optional ByRef x As String = "") + ReceivedInner = inner + ReceivedX = x + x = "changed" + End Sub + End Class + Private Shared Function Increment(ByRef value As Integer) As Integer value += 1 Return value From 24fab8dc7ddbd7e8ad087d577e8292db4c30c8d5 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 12 Nov 2026 01:02:26 +0000 Subject: [PATCH 05/25] Make partial-class initial value functions instance methods 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 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- CodeConverter/CSharp/CommonConversions.cs | 2 +- .../VbLibrary/PartialClassPart.cs | 2 +- .../Prefix.VbLibrary/PartialClassPart.cs | 2 +- .../VbLibrary/PartialClassPart.cs | 2 +- .../VBToCS/ByRefWriteBackPlacementTests.vb | 17 +++++++++++++++++ 5 files changed, 21 insertions(+), 4 deletions(-) diff --git a/CodeConverter/CSharp/CommonConversions.cs b/CodeConverter/CSharp/CommonConversions.cs index cfc699336..bab4b4464 100644 --- a/CodeConverter/CSharp/CommonConversions.cs +++ b/CodeConverter/CSharp/CommonConversions.cs @@ -165,7 +165,7 @@ public bool ShouldPreferExplicitType(VBSyntax.ExpressionSyntax exp, equalsValueClauseSyntax = null; } else { var returnBlock = await _typeContext.PerScopeState.CreateReturnBlockAsync(vbName, adjustedInitializerExpr, csTypeSyntax, SemanticModel); - _typeContext.PerScopeState.HoistToParent(new HoistedFunction(GetInitialValueFunctionName(vbName), csTypeSyntax, returnBlock, SyntaxFactory.ParameterList())); + _typeContext.PerScopeState.HoistToParent(new HoistedFunction(GetInitialValueFunctionName(vbName), csTypeSyntax, returnBlock, SyntaxFactory.ParameterList(), isStatic: false)); equalsValueClauseSyntax = null; } } else { diff --git a/Tests/TestData/MultiFileCharacterization/VBToCSResults/ConvertVbLibraryOnly/VbLibrary/PartialClassPart.cs b/Tests/TestData/MultiFileCharacterization/VBToCSResults/ConvertVbLibraryOnly/VbLibrary/PartialClassPart.cs index f6a13e3a3..424a6ff69 100644 --- a/Tests/TestData/MultiFileCharacterization/VBToCSResults/ConvertVbLibraryOnly/VbLibrary/PartialClassPart.cs +++ b/Tests/TestData/MultiFileCharacterization/VBToCSResults/ConvertVbLibraryOnly/VbLibrary/PartialClassPart.cs @@ -6,7 +6,7 @@ namespace VbLibrary /// internal partial class AClass { - static int[] initialAnArrayWithNonStaticInitializerReferencingOtherPart() => new int[anInt + 1]; + int[] initialAnArrayWithNonStaticInitializerReferencingOtherPart() => new int[anInt + 1]; private int[] anArrayWithNonStaticInitializerReferencingOtherPart; } diff --git a/Tests/TestData/MultiFileCharacterization/VBToCSResults/ConvertWholeSolution/Prefix.VbLibrary/PartialClassPart.cs b/Tests/TestData/MultiFileCharacterization/VBToCSResults/ConvertWholeSolution/Prefix.VbLibrary/PartialClassPart.cs index 3f9874dde..d3e12b88a 100644 --- a/Tests/TestData/MultiFileCharacterization/VBToCSResults/ConvertWholeSolution/Prefix.VbLibrary/PartialClassPart.cs +++ b/Tests/TestData/MultiFileCharacterization/VBToCSResults/ConvertWholeSolution/Prefix.VbLibrary/PartialClassPart.cs @@ -6,7 +6,7 @@ namespace Prefix.VbLibrary /// internal partial class AClass { - static int[] initialAnArrayWithNonStaticInitializerReferencingOtherPart() => new int[anInt + 1]; + int[] initialAnArrayWithNonStaticInitializerReferencingOtherPart() => new int[anInt + 1]; private int[] anArrayWithNonStaticInitializerReferencingOtherPart; } diff --git a/Tests/TestData/MultiFileCharacterization/VBToCSResults/ConvertWholeSolution/VbLibrary/PartialClassPart.cs b/Tests/TestData/MultiFileCharacterization/VBToCSResults/ConvertWholeSolution/VbLibrary/PartialClassPart.cs index f6a13e3a3..424a6ff69 100644 --- a/Tests/TestData/MultiFileCharacterization/VBToCSResults/ConvertWholeSolution/VbLibrary/PartialClassPart.cs +++ b/Tests/TestData/MultiFileCharacterization/VBToCSResults/ConvertWholeSolution/VbLibrary/PartialClassPart.cs @@ -6,7 +6,7 @@ namespace VbLibrary /// internal partial class AClass { - static int[] initialAnArrayWithNonStaticInitializerReferencingOtherPart() => new int[anInt + 1]; + int[] initialAnArrayWithNonStaticInitializerReferencingOtherPart() => new int[anInt + 1]; private int[] anArrayWithNonStaticInitializerReferencingOtherPart; } diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb index 3b444e9c2..c4eae72e8 100644 --- a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb @@ -314,6 +314,23 @@ Public Class ByRefWriteBackPlacementTests End Sub End Class + + Public Sub PartialClassFieldInitializerWritesBack() + Dim initialized As New PartialFieldInitializers() + Assert.Equal(1, initialized.A) + Assert.Equal(1, initialized.Counter) + End Sub + + Partial Private Class PartialFieldInitializers + Public Property Counter As Integer + Public ReadOnly A As Integer = Increment(Counter) + End Class + + Partial Private Class PartialFieldInitializers + Public Sub New() + End Sub + End Class + Private Shared Function Increment(ByRef value As Integer) As Integer value += 1 Return value From b8426735ec00334e13ccddb54e97389ffc6fddb0 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 12 Nov 2026 01:02:46 +0000 Subject: [PATCH 06/25] Document where ByRef temporaries and write-backs are placed Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- CodeConverter/CSharp/README.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 CodeConverter/CSharp/README.md diff --git a/CodeConverter/CSharp/README.md b/CodeConverter/CSharp/README.md new file mode 100644 index 000000000..aef66ce5f --- /dev/null +++ b/CodeConverter/CSharp/README.md @@ -0,0 +1,28 @@ +# VB → C# conversion + +## ByRef arguments that need a temporary + +Sources: [passing arguments by value and by reference](https://learn.microsoft.com/dotnet/visual-basic/programming-guide/language-features/procedures/passing-arguments-by-value-and-by-reference) and Roslyn's VB lowering in [`LocalRewriter_Call.vb`](https://github.com/dotnet/roslyn/blob/main/src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_Call.vb): `RewriteByRefArgumentWithCopyBack` creates the temporary, and `VisitCall` wraps the call in a sequence whose side effects after the value are the copy-backs. Behaviour below is covered by `Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb`. + +### VB + +* A ByRef parameter accepts any expression. If it isn't a variable (a property, a method result, a constant, an omitted `Optional` argument), VB passes a temporary. +* For a writable property (or a `ReadOnly` auto-property inside its constructor), VB copies the temporary back **straight after the call returns**, before the rest of the enclosing expression or statement runs. + +### C# + +* `ref`/`out` need a variable, so the temporary must be declared in a statement before the call. +* There is no expression-level copy-back, so a write-back is a statement too. + +### Implementation + +`ArgumentConverter.HoistByRefDeclaration` hoists the temporary (`AdditionalDeclaration`) and, when VB copies back, the write-back (`AdditionalAssignment`) into the current `PerScopeState` scope. `PerScopeState.CreateLocalsAsync` emits them before and after the converted statement. The output takes the simplest form that keeps VB's timing: + +| Where the call is | C# | Code | +|---|---|---| +| A statement, as the last thing evaluated | temporary before, write-back after the statement | `PerScopeState.CreateLocalsAsync` | +| `Return`, `Throw`, `Yield` | `var ret = call; write-back; return ret;` (only when there is a write-back) | `PerScopeState.WithWriteBacksBefore` | +| Followed by other evaluation, or in a condition or block header (`If`, `ElseIf`, loops, `Select Case`, `Case`, `For`, `For Each`, `Using`, `SyncLock`, `With`, `Catch When`) | a local function that declares, calls and writes back, called in place | `NameExpressionNodeVisitor.RequiresLocalFunction`, `HoistAndCallLocalFunctionAsync` | +| A field initializer | a method that declares, writes back and returns, called from the field (static) or the constructor (instance) | `CommonConversions.WithHoistedNodesInMethodAsync`, `PerScopeState.CreateReturnBlockAsync` | + +Known gaps: arguments of `New` (object creation) in a block header still write back after the block, and a non-constant `For ... Step` is re-evaluated each iteration. From 7377689a1617518805f4127cc5937382ad9c7d5a Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 12 Nov 2026 01:21:58 +0000 Subject: [PATCH 07/25] Drop unreachable case when naming a field initializer method Coverage showed the unqualified-name branch is never hit: invoked names are qualified (e.g. Me.Foo) before conversion. Falling back to init would still be a valid name. No output changes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- CodeConverter/CSharp/CommonConversions.cs | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/CodeConverter/CSharp/CommonConversions.cs b/CodeConverter/CSharp/CommonConversions.cs index bab4b4464..76e6c24f2 100644 --- a/CodeConverter/CSharp/CommonConversions.cs +++ b/CodeConverter/CSharp/CommonConversions.cs @@ -203,12 +203,10 @@ private async Task WithHoistedNodesInMethodAsync(VBSyntax.Modi private static string GetInitializerMethodName(ExpressionSyntax initializer, string fieldName) { - var invokedName = initializer is CSSyntax.InvocationExpressionSyntax { Expression: var invoked } ? invoked switch { - CSSyntax.SimpleNameSyntax name => name, - CSSyntax.MemberAccessExpressionSyntax memberAccess => memberAccess.Name, - _ => null - } : null; - return invokedName is null ? "init" + fieldName.UppercaseFirstLetter() : $"{invokedName.Identifier.ValueText}_{fieldName}"; + // Names are qualified by the time they're converted, e.g. Me.Foo(...) + return initializer is CSSyntax.InvocationExpressionSyntax { Expression: CSSyntax.MemberAccessExpressionSyntax { Name: var invokedName } } + ? $"{invokedName.Identifier.ValueText}_{fieldName}" + : "init" + fieldName.UppercaseFirstLetter(); } /// From c34406ecf3bc7888ed95ace9b906cf25efc3cf42 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 12 Nov 2026 02:00:05 +0000 Subject: [PATCH 08/25] Emit each field initializer method once, including for WithEvents 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 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- .../CSharp/DeclarationNodeVisitor.cs | 4 +- CodeConverter/CSharp/PerScopeState.cs | 10 +++++ .../VBToCS/ByRefWriteBackPlacementTests.vb | 37 +++++++++++++++++++ 3 files changed, 49 insertions(+), 2 deletions(-) diff --git a/CodeConverter/CSharp/DeclarationNodeVisitor.cs b/CodeConverter/CSharp/DeclarationNodeVisitor.cs index ae3660a4d..032bf7f5f 100644 --- a/CodeConverter/CSharp/DeclarationNodeVisitor.cs +++ b/CodeConverter/CSharp/DeclarationNodeVisitor.cs @@ -548,11 +548,11 @@ private IEnumerable CreateMemberDeclarations(IReadOnlyC } } + foreach (var method in CreateExtraMethodMembers()) yield return method; if (isWithEvents) { var fieldDecls = CreateWithEventsMembers(thisFieldModifiers, attributes, variablesDecl.Decl); foreach (var f in fieldDecls) yield return f; } else { - foreach (var method in CreateExtraMethodMembers()) yield return method; yield return CS.SyntaxFactory.FieldDeclaration(CS.SyntaxFactory.List(attributes), thisFieldModifiers, variablesDecl.Decl); } } @@ -580,7 +580,7 @@ private IEnumerable CreateWithEventsMembers(SyntaxToken private IReadOnlyCollection CreateExtraMethodMembers() { - var methodsInfos = AdditionalLocals.GetParameterlessFunctions(); + var methodsInfos = AdditionalLocals.TakeParameterlessFunctions(); // In theory this should use a unique name like in MethodBodyVisitor // Unfortunately we can't change the name for these since the file containing the constructor of a partial class tries to call the method with exactly this name. diff --git a/CodeConverter/CSharp/PerScopeState.cs b/CodeConverter/CSharp/PerScopeState.cs index eefdfdcb8..d0273911e 100644 --- a/CodeConverter/CSharp/PerScopeState.cs +++ b/CodeConverter/CSharp/PerScopeState.cs @@ -134,6 +134,16 @@ public IReadOnlyCollection GetParameterlessFunctions() return _hoistedNodesPerScope.Peek().OfType().ToArray(); } + /// + /// For a scope whose functions are emitted as they're found, e.g. one per variable of a field declaration, so each is emitted once. + /// + public IReadOnlyCollection TakeParameterlessFunctions() + { + var functions = GetParameterlessFunctions(); + _hoistedNodesPerScope.Peek().HoistedNodes.RemoveAll(n => n is HoistedFunction); + return functions; + } + public IReadOnlyCollection GetFields() { return _hoistedNodesPerScope.Peek().OfType().ToArray(); diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb index c4eae72e8..eaedbf316 100644 --- a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb @@ -331,6 +331,43 @@ Public Class ByRefWriteBackPlacementTests End Sub End Class + + Public Sub SeveralDeclaratorsInOneFieldDeclarationEachWriteBack() + Dim initialized As New SeveralDeclarators + Assert.Equal(1, initialized.A) + Assert.Equal(2, initialized.B) + Assert.Equal(4, initialized.Arr.Length) + Assert.Equal(3, initialized.Counter) + End Sub + + Private Class SeveralDeclarators + Public Property Counter As Integer + Public ReadOnly A As Integer = Increment(Counter), B As Integer = Increment(Counter) + Public Arr(Increment(Counter)), Other As Integer + End Class + + + Public Sub WithEventsFieldInitializerWritesBack() + Dim initialized As New WithEventsFieldInitializer + Assert.Equal(1, initialized.Counter) + Assert.Equal(1, initialized.Source.Received) + End Sub + + Private Class WithEventsFieldInitializer + Public Property Counter As Integer + Public WithEvents Source As New EventSource(Counter) + End Class + + Private Class EventSource + Public Event Changed() + Public ReadOnly Received As Integer + + Sub New(ByRef value As Integer) + value += 1 + Received = value + End Sub + End Class + Private Shared Function Increment(ByRef value As Integer) As Integer value += 1 Return value From e360affbbdf3cf8b78fd4e08846510d950a9c4b4 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 12 Nov 2026 02:00:17 +0000 Subject: [PATCH 09/25] Document remaining ByRef write-back gaps found in review 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 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- CodeConverter/CSharp/README.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/CodeConverter/CSharp/README.md b/CodeConverter/CSharp/README.md index aef66ce5f..47b13fccc 100644 --- a/CodeConverter/CSharp/README.md +++ b/CodeConverter/CSharp/README.md @@ -25,4 +25,8 @@ Sources: [passing arguments by value and by reference](https://learn.microsoft.c | Followed by other evaluation, or in a condition or block header (`If`, `ElseIf`, loops, `Select Case`, `Case`, `For`, `For Each`, `Using`, `SyncLock`, `With`, `Catch When`) | a local function that declares, calls and writes back, called in place | `NameExpressionNodeVisitor.RequiresLocalFunction`, `HoistAndCallLocalFunctionAsync` | | A field initializer | a method that declares, writes back and returns, called from the field (static) or the constructor (instance) | `CommonConversions.WithHoistedNodesInMethodAsync`, `PerScopeState.CreateReturnBlockAsync` | -Known gaps: arguments of `New` (object creation) in a block header still write back after the block, and a non-constant `For ... Step` is re-evaluated each iteration. +Known gaps: +* Arguments of `New` (object creation) in a block header still write back after the block. +* A non-constant `For ... Step` is re-evaluated each iteration (not ByRef-specific). +* VB copies back a call's arguments in reverse order (`copyBackArray.ReverseContents()` in `LocalRewriter_Call.vb`); the converter writes back in argument order. Only observable when two arguments write back to aliasing targets, e.g. `Two(p.Value, p.Value)`. A fix needs per-call grouping in `ArgumentConverter`, since nested calls write back before the outer call. +* A `ReadOnly` auto-property is assignable in its type's constructor and initializers, so VB writes it back there, but `GetRefConversionForExpression` treats every read-only property as not writable. A fix also needs the C# write-back target to be assignable from the field initializer method. From d7f02d1f843194a0b87b474f415c4dd8156ed385 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 12 Nov 2026 03:15:21 +0000 Subject: [PATCH 10/25] Drop dead renaming of hoisted initializer methods 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 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- CodeConverter/CSharp/DeclarationNodeVisitor.cs | 16 +++------------- 1 file changed, 3 insertions(+), 13 deletions(-) diff --git a/CodeConverter/CSharp/DeclarationNodeVisitor.cs b/CodeConverter/CSharp/DeclarationNodeVisitor.cs index 032bf7f5f..7a35d2ef9 100644 --- a/CodeConverter/CSharp/DeclarationNodeVisitor.cs +++ b/CodeConverter/CSharp/DeclarationNodeVisitor.cs @@ -580,19 +580,9 @@ private IEnumerable CreateWithEventsMembers(SyntaxToken private IReadOnlyCollection CreateExtraMethodMembers() { - var methodsInfos = AdditionalLocals.TakeParameterlessFunctions(); - - // In theory this should use a unique name like in MethodBodyVisitor - // Unfortunately we can't change the name for these since the file containing the constructor of a partial class tries to call the method with exactly this name. - // See GetInitialValueFunctionName - var newMethodNames = methodsInfos.ToDictionary(l => l.Id, l => l.Prefix); - for (int i = 0; i < _typeContext.Initializers.AdditionalInstanceInitializers.Count; i++) { - var (a, b, initializer, _) = _typeContext.Initializers.AdditionalInstanceInitializers[i]; - _typeContext.Initializers.AdditionalInstanceInitializers[i] = new Assignment(a, b, PerScopeState.ReplaceNames(initializer, newMethodNames)); - } - - return methodsInfos - .Select(al => al.AsInstanceMethod(newMethodNames[al.Id])) + // Callers reference these by their final name, so it's the prefix rather than a placeholder + return AdditionalLocals.TakeParameterlessFunctions() + .Select(al => al.AsInstanceMethod(al.Prefix)) .ToArray(); } From 5043b0fb9b21d1dfa0c9663907730bcd91262642 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 12 Nov 2026 03:18:36 +0000 Subject: [PATCH 11/25] Give field initializer methods names unused by other members 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 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- CodeConverter/CSharp/CommonConversions.cs | 3 +- Tests/CSharp/ExpressionTests/ByRefTests.cs | 59 ++++++++++++++++++++++ 2 files changed, 61 insertions(+), 1 deletion(-) diff --git a/CodeConverter/CSharp/CommonConversions.cs b/CodeConverter/CSharp/CommonConversions.cs index 76e6c24f2..dd19cdb98 100644 --- a/CodeConverter/CSharp/CommonConversions.cs +++ b/CodeConverter/CSharp/CommonConversions.cs @@ -196,7 +196,8 @@ private async Task WithHoistedNodesInMethodAsync(VBSyntax.Modi if (!_typeContext.PerScopeState.HasHoistedNodes) return initializer; var body = await _typeContext.PerScopeState.CreateReturnBlockAsync(vbName, initializer, type, SemanticModel); - var methodName = GetInitializerMethodName(initializer, ConvertIdentifier(vbName.Identifier).ValueText); + var baseMethodName = GetInitializerMethodName(initializer, ConvertIdentifier(vbName.Identifier).ValueText); + var methodName = NameGenerator.CS.GetUniqueVariableNameInScope(SemanticModel, new HashSet(), vbName, baseMethodName); _typeContext.PerScopeState.HoistToParent(new HoistedFunction(methodName, type, body, SyntaxFactory.ParameterList(), isStatic)); return SyntaxFactory.InvocationExpression(ValidSyntaxFactory.IdentifierName(methodName)); } diff --git a/Tests/CSharp/ExpressionTests/ByRefTests.cs b/Tests/CSharp/ExpressionTests/ByRefTests.cs index 24c6569b3..e96590161 100644 --- a/Tests/CSharp/ExpressionTests/ByRefTests.cs +++ b/Tests/CSharp/ExpressionTests/ByRefTests.cs @@ -1306,6 +1306,65 @@ public static int Inc(ref int v) v += 1; return v; } +}"); + } + + [Fact] + public async Task FieldInitializerMethodNamesAvoidExistingMembersAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Public Class C + Public Property P As Integer + Private w As Integer = Inc(P) + 1 + Private v As Integer = Inc(P) + Private Inc_v As Integer + + Function initW() As Integer + Return 0 + End Function + + Shared Function Inc(ByRef x As Integer) As Integer + x += 1 + Return x + End Function +End Class", @" +public partial class C +{ + public int P { get; set; } + + public C() + { + w = initW1(); + v = Inc_v1(); + } + int initW1() + { + int localInc() { int argx = P; var ret = Inc(ref argx); P = argx; return ret; } + + return localInc() + 1; + } + + private int w; + int Inc_v1() + { + int argx = P; + int ret = Inc(ref argx); + P = argx; + return ret; + } + + private int v; + private int Inc_v; + + public int initW() + { + return 0; + } + + public static int Inc(ref int x) + { + x += 1; + return x; + } }"); } } \ No newline at end of file From 9031b61c13e642030692b5855605a6c539bfdb98 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 12 Nov 2026 03:18:46 +0000 Subject: [PATCH 12/25] Document further pre-existing ByRef gaps found in review 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 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- CodeConverter/CSharp/README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CodeConverter/CSharp/README.md b/CodeConverter/CSharp/README.md index 47b13fccc..d7b22694e 100644 --- a/CodeConverter/CSharp/README.md +++ b/CodeConverter/CSharp/README.md @@ -29,4 +29,8 @@ Known gaps: * Arguments of `New` (object creation) in a block header still write back after the block. * A non-constant `For ... Step` is re-evaluated each iteration (not ByRef-specific). * VB copies back a call's arguments in reverse order (`copyBackArray.ReverseContents()` in `LocalRewriter_Call.vb`); the converter writes back in argument order. Only observable when two arguments write back to aliasing targets, e.g. `Two(p.Value, p.Value)`. A fix needs per-call grouping in `ArgumentConverter`, since nested calls write back before the outer call. +* `Dim a = Inc(P), b = Inc(P)` writes back after all declarators, so `b` reads a stale `P`. +* A lambda parameter inside a ByRef argument (`Function(x) Inc(x.P)`) hoists the local function outside the lambda, where `x` isn't in scope (CS0103). +* An auto-property initializer (`Public Property X As Integer = Inc(P)`) leaves a `ph…` placeholder (CS0103): it doesn't go through the field initializer path. +* Partial-class instance initializers run in part order rather than declaration order. * A `ReadOnly` auto-property is assignable in its type's constructor and initializers, so VB writes it back there, but `GetRefConversionForExpression` treats every read-only property as not writable. A fix also needs the C# write-back target to be assignable from the field initializer method. From 0cffd9b75d3f67997a33a17d0d77107364b10e8a Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 23:51:45 +0000 Subject: [PATCH 13/25] Write back a call's ByRef arguments in reverse order, like VB 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 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- CodeConverter/CSharp/ArgumentConverter.cs | 29 +++++++++- CodeConverter/CSharp/README.md | 4 +- Tests/CSharp/MemberTests/ConstructorTests.cs | 2 +- .../VBToCS/ByRefWriteBackPlacementTests.vb | 56 +++++++++++++++++++ 4 files changed, 87 insertions(+), 4 deletions(-) diff --git a/CodeConverter/CSharp/ArgumentConverter.cs b/CodeConverter/CSharp/ArgumentConverter.cs index 6eec58ac3..c48a72478 100644 --- a/CodeConverter/CSharp/ArgumentConverter.cs +++ b/CodeConverter/CSharp/ArgumentConverter.cs @@ -10,6 +10,11 @@ internal class ArgumentConverter private readonly SemanticModel _semanticModel; private CommentConvertingVisitorWrapper TriviaConvertingExpressionVisitor { get; } + /// + /// The write-backs of each argument list being converted, innermost call on top. + /// + private readonly Stack> _writeBacksPerCall = new(); + public ArgumentConverter(VisualBasicEqualityComparison visualBasicEqualityComparison, ITypeContext typeContext, SemanticModel semanticModel, CommonConversions commonConversions) { CommonConversions = commonConversions; @@ -54,7 +59,7 @@ public async Task ConvertSimpleArgumentAsync(VBSyntax.SimpleAr var invocationHasOverloads = invocationSymbol.HasOverloads(); var processedParameters = new HashSet(StringComparer.OrdinalIgnoreCase); - var argumentSyntaxs = (await node.Arguments.SelectAsync(ConvertArg)).Where(a => a != null); + var argumentSyntaxs = (await WithWriteBacksInVbOrderAsync(() => node.Arguments.SelectAsync(ConvertArg))).Where(a => a != null); return Enumerable.Concat(argumentSyntaxs, GetAdditionalRequiredArgs(node.Arguments, processedParameters, invocationSymbol, invocationHasOverloads)); async Task ConvertArg(VBSyntax.ArgumentSyntax arg, int argIndex) @@ -119,6 +124,24 @@ CSSyntax.ArgumentSyntax ConvertOmittedArgument(IParameterSymbol parameter) } + /// + /// VB copies back a call's ByRef arguments from the last to the first (copyBackArray.ReverseContents() in Roslyn's LocalRewriter_Call.vb), + /// which is observable when two arguments write back to the same place. + /// A nested call has already written back by then, so only this call's own write-backs are reversed. + /// + private async Task WithWriteBacksInVbOrderAsync(Func> convertArguments) + { + _writeBacksPerCall.Push(new List()); + T converted; + try { + converted = await convertArguments(); + } finally { + var writeBacks = _writeBacksPerCall.Pop(); + foreach (var writeBack in Enumerable.Reverse(writeBacks)) _typeContext.PerScopeState.Hoist(writeBack); + } + return converted; + } + internal CSSyntax.ExpressionSyntax HoistByRefDeclaration(VBSyntax.ExpressionSyntax node, CSSyntax.ExpressionSyntax refLValue, SemanticModelExtensions.RefConversion refType, string argName, RefKind refKind) { string prefix = $"arg{argName}"; @@ -138,7 +161,9 @@ internal CSSyntax.ExpressionSyntax HoistByRefDeclaration(VBSyntax.ExpressionSynt if (refType == SemanticModelExtensions.RefConversion.PreAndPostAssignment) { var convertedLocalIdentifier = CommonConversions.TypeConversionAnalyzer.AddExplicitConversion(node, local.IdentifierName, forceSourceType: expressionTypeInfo.ConvertedType, forceTargetType: expressionTypeInfo.Type); - _typeContext.PerScopeState.Hoist(new AdditionalAssignment(refLValue, convertedLocalIdentifier)); + var writeBack = new AdditionalAssignment(refLValue, convertedLocalIdentifier); + if (_writeBacksPerCall.Count > 0) _writeBacksPerCall.Peek().Add(writeBack); + else _typeContext.PerScopeState.Hoist(writeBack); } return local.IdentifierName; diff --git a/CodeConverter/CSharp/README.md b/CodeConverter/CSharp/README.md index d7b22694e..f10566ac7 100644 --- a/CodeConverter/CSharp/README.md +++ b/CodeConverter/CSharp/README.md @@ -8,6 +8,7 @@ Sources: [passing arguments by value and by reference](https://learn.microsoft.c * A ByRef parameter accepts any expression. If it isn't a variable (a property, a method result, a constant, an omitted `Optional` argument), VB passes a temporary. * For a writable property (or a `ReadOnly` auto-property inside its constructor), VB copies the temporary back **straight after the call returns**, before the rest of the enclosing expression or statement runs. +* One call copies back its arguments from the last to the first (`copyBackArray.ReverseContents()` in `LocalRewriter_Call.vb`). It's observable when two arguments write back to the same place, e.g. `Two(p.Value, p.Value)`. A call nested in an argument has already copied back by then. ### C# @@ -25,10 +26,11 @@ Sources: [passing arguments by value and by reference](https://learn.microsoft.c | Followed by other evaluation, or in a condition or block header (`If`, `ElseIf`, loops, `Select Case`, `Case`, `For`, `For Each`, `Using`, `SyncLock`, `With`, `Catch When`) | a local function that declares, calls and writes back, called in place | `NameExpressionNodeVisitor.RequiresLocalFunction`, `HoistAndCallLocalFunctionAsync` | | A field initializer | a method that declares, writes back and returns, called from the field (static) or the constructor (instance) | `CommonConversions.WithHoistedNodesInMethodAsync`, `PerScopeState.CreateReturnBlockAsync` | +Within each of these, one call's write-backs are hoisted after its whole argument list, last argument first, so a nested call's come before them: `ArgumentConverter.WithWriteBacksInVbOrderAsync`. + Known gaps: * Arguments of `New` (object creation) in a block header still write back after the block. * A non-constant `For ... Step` is re-evaluated each iteration (not ByRef-specific). -* VB copies back a call's arguments in reverse order (`copyBackArray.ReverseContents()` in `LocalRewriter_Call.vb`); the converter writes back in argument order. Only observable when two arguments write back to aliasing targets, e.g. `Two(p.Value, p.Value)`. A fix needs per-call grouping in `ArgumentConverter`, since nested calls write back before the outer call. * `Dim a = Inc(P), b = Inc(P)` writes back after all declarators, so `b` reads a stale `P`. * A lambda parameter inside a ByRef argument (`Function(x) Inc(x.P)`) hoists the local function outside the lambda, where `x` isn't in scope (CS0103). * An auto-property initializer (`Public Property X As Integer = Inc(P)`) leaves a `ph…` placeholder (CS0103): it doesn't go through the field initializer path. diff --git a/Tests/CSharp/MemberTests/ConstructorTests.cs b/Tests/CSharp/MemberTests/ConstructorTests.cs index 3de4d01e9..7bb6789c3 100644 --- a/Tests/CSharp/MemberTests/ConstructorTests.cs +++ b/Tests/CSharp/MemberTests/ConstructorTests.cs @@ -122,7 +122,7 @@ public void S([Optional, DefaultParameterValue(-1)] ref int x) int i = 0; bool localF1(ref int x) { object argo = i; var ret = F1(x, ref argo); i = Conversions.ToInteger(argo); return ret; } bool localF2(ref int x) { object argo1 = i; var ret = F2(ref x, ref argo1); i = Conversions.ToInteger(argo1); return ret; } - bool localF3(ref int x) { object argx = x; object argo2 = i; var ret = F3(ref argx, ref argo2); x = Conversions.ToInteger(argx); i = Conversions.ToInteger(argo2); return ret; } + bool localF3(ref int x) { object argx = x; object argo2 = i; var ret = F3(ref argx, ref argo2); i = Conversions.ToInteger(argo2); x = Conversions.ToInteger(argx); return ret; } if (localF1(ref x)) { diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb index eaedbf316..30dd35951 100644 --- a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb @@ -368,6 +368,62 @@ Public Class ByRefWriteBackPlacementTests End Sub End Class + + Public Sub CallWritesBackItsArgumentsInReverseOrder() + Dim probe As New Probe + Two(probe.Value, probe.Value) + Assert.Equal(1, probe.Stored) + Assert.Equal("get,get,set,set", probe.LogText) + End Sub + + + Public Sub NestedCallWritesBackBeforeTheOuterCallsReversedWriteBacks() + Dim probe As New Probe + Three(SetToNine(probe.Value), probe.Value, probe.Value) + Assert.Equal(1, probe.Stored) + End Sub + + + Public Sub ReturnWritesBackInReverseOrderBeforeReturning() + Dim probe As New Probe + Assert.Equal(3, ReturnTwo(probe)) + Assert.Equal(1, probe.Stored) + End Sub + + Private Shared Function ReturnTwo(probe As Probe) As Integer + Return TwoAndSum(probe.Value, probe.Value) + End Function + + + Public Sub BlockHeaderWritesBackInReverseOrderBeforeTheBody() + Dim probe As New Probe + Select Case TwoAndSum(probe.Value, probe.Value) + Case 3 + Assert.Equal(1, probe.Stored) + Case Else + Assert.Fail("Unexpected case") + End Select + End Sub + + Private Shared Sub Two(ByRef a As Integer, ByRef b As Integer) + a = 1 + b = 2 + End Sub + + Private Shared Function TwoAndSum(ByRef a As Integer, ByRef b As Integer) As Integer + Two(a, b) + Return a + b + End Function + + Private Shared Sub Three(x As Integer, ByRef a As Integer, ByRef b As Integer) + Two(a, b) + End Sub + + Private Shared Function SetToNine(ByRef value As Integer) As Integer + value = 9 + Return value + End Function + Private Shared Function Increment(ByRef value As Integer) As Integer value += 1 Return value From 9967913d21ee135ed3a757d7843fbf68d2745e10 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 00:00:37 +0000 Subject: [PATCH 14/25] Write back each Dim declarator before the next is evaluated 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 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- .../CSharp/NameExpressionNodeVisitor.cs | 20 +++++++++++++++++++ CodeConverter/CSharp/README.md | 3 +-- .../VBToCS/ByRefWriteBackPlacementTests.vb | 11 ++++++++++ 3 files changed, 32 insertions(+), 2 deletions(-) diff --git a/CodeConverter/CSharp/NameExpressionNodeVisitor.cs b/CodeConverter/CSharp/NameExpressionNodeVisitor.cs index 8bc25b7cc..dbf3be5dc 100644 --- a/CodeConverter/CSharp/NameExpressionNodeVisitor.cs +++ b/CodeConverter/CSharp/NameExpressionNodeVisitor.cs @@ -582,6 +582,9 @@ private bool DefinitelyExecutedAfterPreviousStatement(VBSyntax.InvocationExpress // Being the leftmost invocation of an unqualified method call ensures no other code is executed. Could add other cases here, such as a method call on a local variable name, or "this.". A method call on a property is not acceptable. if (argumentSyntax.Parent.Parent is VBSyntax.InvocationExpressionSyntax parentInvocation && parentInvocation.ArgumentList.Arguments.First() == argumentSyntax && FirstArgDefinitelyEvaluated(parentInvocation)) continue; else return false; + case VBSyntax.VariableDeclaratorSyntax declarator when IsInLocalDeclarationWithSeveralDeclarators(declarator, out var declarators): + if (declarators.First() == declarator) continue; + else return false; case VBSyntax.ElseIfStatementSyntax _: case VBSyntax.ExpressionSyntax _: return false; @@ -625,6 +628,9 @@ private static bool NextStatementDefinitelyExecutedAfter(VBSyntax.InvocationExpr case VBSyntax.BinaryExpressionSyntax binaryExpression: if (binaryExpression.Right == invocation) continue; else return false; + case VBSyntax.VariableDeclaratorSyntax declarator when IsInLocalDeclarationWithSeveralDeclarators(declarator, out var declarators): + if (declarators.Last() == declarator) continue; + else return false; case VBSyntax.IfStatementSyntax _: case VBSyntax.ElseIfStatementSyntax _: case VBSyntax.SingleLineIfStatementSyntax _: @@ -645,6 +651,20 @@ private static bool NextStatementDefinitelyExecutedAfter(VBSyntax.InvocationExpr } + /// + /// VB evaluates each declarator of Dim a = F(p.X), b = F(p.X) in turn, writing back before the next one starts, + /// but temporaries and write-backs are hoisted around the whole converted declaration. + /// A Static local's declarators become fields, where a local function couldn't be called, so those keep the old placement. + /// + private static bool IsInLocalDeclarationWithSeveralDeclarators(VBSyntax.VariableDeclaratorSyntax declarator, out SeparatedSyntaxList declarators) + { + declarators = declarator.Parent is VBSyntax.LocalDeclarationStatementSyntax localDeclaration && + !localDeclaration.Modifiers.Any(m => m.IsKind(VBasic.SyntaxKind.StaticKeyword)) + ? localDeclaration.Declarators + : default; + return declarators.Count > 1; + } + /// /// The pre-expansion phase should handle this for compiling nodes. /// This is mainly targeted at dealing with missing semantic info. diff --git a/CodeConverter/CSharp/README.md b/CodeConverter/CSharp/README.md index f10566ac7..21bc40eb1 100644 --- a/CodeConverter/CSharp/README.md +++ b/CodeConverter/CSharp/README.md @@ -23,7 +23,7 @@ Sources: [passing arguments by value and by reference](https://learn.microsoft.c |---|---|---| | A statement, as the last thing evaluated | temporary before, write-back after the statement | `PerScopeState.CreateLocalsAsync` | | `Return`, `Throw`, `Yield` | `var ret = call; write-back; return ret;` (only when there is a write-back) | `PerScopeState.WithWriteBacksBefore` | -| Followed by other evaluation, or in a condition or block header (`If`, `ElseIf`, loops, `Select Case`, `Case`, `For`, `For Each`, `Using`, `SyncLock`, `With`, `Catch When`) | a local function that declares, calls and writes back, called in place | `NameExpressionNodeVisitor.RequiresLocalFunction`, `HoistAndCallLocalFunctionAsync` | +| Followed by other evaluation, or in a condition or block header (`If`, `ElseIf`, loops, `Select Case`, `Case`, `For`, `For Each`, `Using`, `SyncLock`, `With`, `Catch When`), or in a `Dim` declarator that isn't the only one | a local function that declares, calls and writes back, called in place | `NameExpressionNodeVisitor.RequiresLocalFunction`, `HoistAndCallLocalFunctionAsync` | | A field initializer | a method that declares, writes back and returns, called from the field (static) or the constructor (instance) | `CommonConversions.WithHoistedNodesInMethodAsync`, `PerScopeState.CreateReturnBlockAsync` | Within each of these, one call's write-backs are hoisted after its whole argument list, last argument first, so a nested call's come before them: `ArgumentConverter.WithWriteBacksInVbOrderAsync`. @@ -31,7 +31,6 @@ Within each of these, one call's write-backs are hoisted after its whole argumen Known gaps: * Arguments of `New` (object creation) in a block header still write back after the block. * A non-constant `For ... Step` is re-evaluated each iteration (not ByRef-specific). -* `Dim a = Inc(P), b = Inc(P)` writes back after all declarators, so `b` reads a stale `P`. * A lambda parameter inside a ByRef argument (`Function(x) Inc(x.P)`) hoists the local function outside the lambda, where `x` isn't in scope (CS0103). * An auto-property initializer (`Public Property X As Integer = Inc(P)`) leaves a `ph…` placeholder (CS0103): it doesn't go through the field initializer path. * Partial-class instance initializers run in part order rather than declaration order. diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb index 30dd35951..5c42aa99f 100644 --- a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb @@ -424,6 +424,17 @@ Public Class ByRefWriteBackPlacementTests Return value End Function + + Public Sub EachDeclaratorOfALocalDeclarationWritesBackBeforeTheNext() + Dim probe As New Probe + Dim a = Increment(probe.Value), b = Increment(probe.Value), c = probe.Stored + Assert.Equal(1, a) + Assert.Equal(2, b) + Assert.Equal(2, c) + Assert.Equal(2, probe.Stored) + Assert.Equal("get,set,get,set", probe.LogText) + End Sub + Private Shared Function Increment(ByRef value As Integer) As Integer value += 1 Return value From 912e14dd5eab6ab9e4f975670a2623b8446e7c16 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 20:57:27 +0000 Subject: [PATCH 15/25] Write back before an assignment stores to what's written back 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 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- .../CSharp/NameExpressionNodeVisitor.cs | 24 ++++++- CodeConverter/CSharp/README.md | 4 +- Tests/CSharp/ExpressionTests/ByRefTests.cs | 51 +++++++++++++++ .../VBToCS/ByRefWriteBackPlacementTests.vb | 62 +++++++++++++++++++ 4 files changed, 138 insertions(+), 3 deletions(-) diff --git a/CodeConverter/CSharp/NameExpressionNodeVisitor.cs b/CodeConverter/CSharp/NameExpressionNodeVisitor.cs index dbf3be5dc..7a3815e51 100644 --- a/CodeConverter/CSharp/NameExpressionNodeVisitor.cs +++ b/CodeConverter/CSharp/NameExpressionNodeVisitor.cs @@ -542,7 +542,7 @@ invocation.Expression is VBSyntax.MemberAccessExpressionSyntax member && if (invocation.ArgumentList == null) return false; var definitelyExecutedAfterPrevious = DefinitelyExecutedAfterPreviousStatement(invocation); - var nextStatementDefinitelyExecuted = NextStatementDefinitelyExecutedAfter(invocation); + var nextStatementDefinitelyExecuted = NextStatementDefinitelyExecutedAfter(invocation) && !AssignmentChangesWhatIsWrittenBack(invocation, invocationSymbol); if (definitelyExecutedAfterPrevious && nextStatementDefinitelyExecuted) return false; var possibleInline = definitelyExecutedAfterPrevious ? RefConversion.PreAssigment : RefConversion.Inline; return invocation.ArgumentList.Arguments.Any(a => RequiresLocalFunction(possibleInline, invocation, invocationSymbol, a)); @@ -558,6 +558,28 @@ bool RequiresLocalFunction(RefConversion possibleInline, VBSyntax.InvocationExpr } } + /// + /// VB writes back straight after the call, before the enclosing assignment stores its result. + /// A write-back emitted after the assignment statement would overwrite the assigned target (h.P = F(h.P)), + /// or write to a different place if the assignment changes something the write-back target reads (x = F(h.Items(x)), h = F(h.P)). + /// Other assignments keep the write-back after the statement. + /// + private bool AssignmentChangesWhatIsWrittenBack(VBSyntax.InvocationExpressionSyntax invocation, IMethodSymbol invocationSymbol) + { + if (invocation.Ancestors().FirstOrDefault(n => n is VBSyntax.StatementSyntax or VBSyntax.LambdaExpressionSyntax) is not VBSyntax.AssignmentStatementSyntax assignment || + !assignment.Right.Span.Contains(invocation.Span)) { + return false; + } + + var assignedSymbol = _semanticModel.GetSymbolInfo(assignment.Left).Symbol ?? + (assignment.Left is VBSyntax.InvocationExpressionSyntax { Expression: var indexed } ? _semanticModel.GetSymbolInfo(indexed).Symbol : null); + var writtenBackExpressions = invocation.ArgumentList.Arguments.OfType() + .Where(a => CommonConversions.GetRefConversionType(a, invocation.ArgumentList, invocationSymbol.Parameters, out _, out _) == RefConversion.PreAndPostAssignment) + .Select(a => a.Expression); + return writtenBackExpressions.Any(e => assignedSymbol is null || + e.DescendantNodesAndSelf().OfType().Any(n => SymbolEqualityComparer.Default.Equals(_semanticModel.GetSymbolInfo(n).Symbol, assignedSymbol))); + } + private static bool IsLoopCondition(SyntaxNode node) { var containingStatement = node.Ancestors().FirstOrDefault(n => n is VBSyntax.StatementSyntax or VBSyntax.LambdaExpressionSyntax); diff --git a/CodeConverter/CSharp/README.md b/CodeConverter/CSharp/README.md index 21bc40eb1..bc2246eff 100644 --- a/CodeConverter/CSharp/README.md +++ b/CodeConverter/CSharp/README.md @@ -21,9 +21,9 @@ Sources: [passing arguments by value and by reference](https://learn.microsoft.c | Where the call is | C# | Code | |---|---|---| -| A statement, as the last thing evaluated | temporary before, write-back after the statement | `PerScopeState.CreateLocalsAsync` | +| A statement, as the last thing evaluated, including the right of an assignment whose target isn't read by the write-back (`Q = F(P)`) | temporary before, write-back after the statement | `PerScopeState.CreateLocalsAsync` | | `Return`, `Throw`, `Yield` | `var ret = call; write-back; return ret;` (only when there is a write-back) | `PerScopeState.WithWriteBacksBefore` | -| Followed by other evaluation, or in a condition or block header (`If`, `ElseIf`, loops, `Select Case`, `Case`, `For`, `For Each`, `Using`, `SyncLock`, `With`, `Catch When`), or in a `Dim` declarator that isn't the only one | a local function that declares, calls and writes back, called in place | `NameExpressionNodeVisitor.RequiresLocalFunction`, `HoistAndCallLocalFunctionAsync` | +| Followed by other evaluation, or in a condition or block header (`If`, `ElseIf`, loops, `Select Case`, `Case`, `For`, `For Each`, `Using`, `SyncLock`, `With`, `Catch When`), or in a `Dim` declarator that isn't the only one, or the right of an assignment to something the write-back reads (`P = F(P)`, `x = F(h.Items(x))`, `h = F(h.P)`): C# evaluates the assignment target first and stores last, as VB does, and the write-back happens in between | a local function that declares, calls and writes back, called in place | `NameExpressionNodeVisitor.RequiresLocalFunction`, `HoistAndCallLocalFunctionAsync` | | A field initializer | a method that declares, writes back and returns, called from the field (static) or the constructor (instance) | `CommonConversions.WithHoistedNodesInMethodAsync`, `PerScopeState.CreateReturnBlockAsync` | Within each of these, one call's write-backs are hoisted after its whole argument list, last argument first, so a nested call's come before them: `ArgumentConverter.WithWriteBacksInVbOrderAsync`. diff --git a/Tests/CSharp/ExpressionTests/ByRefTests.cs b/Tests/CSharp/ExpressionTests/ByRefTests.cs index e96590161..763b32f44 100644 --- a/Tests/CSharp/ExpressionTests/ByRefTests.cs +++ b/Tests/CSharp/ExpressionTests/ByRefTests.cs @@ -1365,6 +1365,57 @@ public static int Inc(ref int x) x += 1; return x; } +}"); + } + + [Fact] + public async Task WritesBackBeforeAssignmentCompletesWhenItChangesTheWriteBackTargetAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Public Class C + Public Property P As String + Public Property Q As String + + Function F(ByRef v As String) As String + Return v + End Function + + Function G(ByRef v As String) As C + Return New C + End Function + + Sub Assignments(h As C) + P = F(P) + h = G(h.P) + Q = F(P) + End Sub +End Class", @" +public partial class C +{ + public string P { get; set; } + public string Q { get; set; } + + public string F(ref string v) + { + return v; + } + + public C G(ref string v) + { + return new C(); + } + + public void Assignments(C h) + { + string localF() { string argv = P; var ret = F(ref argv); P = argv; return ret; } + + P = localF(); + C localG() { string argv1 = h.P; var ret = G(ref argv1); h.P = argv1; return ret; } + + h = localG(); + string argv = P; + Q = F(ref argv); + P = argv; + } }"); } } \ No newline at end of file diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb index 5c42aa99f..9c6adb6a9 100644 --- a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb @@ -435,6 +435,68 @@ Public Class ByRefWriteBackPlacementTests Assert.Equal("get,set,get,set", probe.LogText) End Sub + + Public Sub AssignmentToTheWrittenBackPropertyKeepsTheCallResult() + Dim h As New Holder + h.Plain = SetValueReturnOther(h.Plain) + Assert.Equal("result", h.Plain) + End Sub + + + Public Sub AssignmentToAnIndexOfTheWriteBackWritesBackAtTheOldIndex() + Dim h As New Holder + Dim x = 0 + x = SetValueReturnOne(h.Items(x)) + Assert.Equal(1, x) + Assert.Equal("changed", h.Items(0)) + Assert.Equal("b", h.Items(1)) + x += SetValueReturnOne(h.Items(x)) + Assert.Equal(2, x) + Assert.Equal("changed", h.Items(1)) + End Sub + + + Public Sub AssignmentToTheWriteBackReceiverWritesBackToTheOldReceiver() + Dim h As New Holder + Dim original = h + h = SetValueReturnHolder(h.Plain) + Assert.NotSame(original, h) + Assert.Equal("changed", original.Plain) + Assert.Equal("", h.Plain) + Dim second = h + h = SetValueReturnHolder(h.Items(1)) + Assert.Equal("changed", second.Items(1)) + Assert.Equal("b", h.Items(1)) + End Sub + + + Public Sub CompoundAssignmentReadsItsTargetBeforeTheCall() + Dim probe As New Probe + probe.Value += Increment(probe.Value) + Assert.Equal(1, probe.Stored) + Assert.Equal("get,get,set,set", probe.LogText) + End Sub + + Private Class Holder + Public Property Plain As String = "" + Public Property Items As New List(Of String) From {"a", "b"} + End Class + + Private Shared Function SetValueReturnOther(ByRef value As String) As String + value = "changed" + Return "result" + End Function + + Private Shared Function SetValueReturnOne(ByRef value As String) As Integer + value = "changed" + Return 1 + End Function + + Private Shared Function SetValueReturnHolder(ByRef value As String) As Holder + value = "changed" + Return New Holder + End Function + Private Shared Function Increment(ByRef value As Integer) As Integer value += 1 Return value From c39d4caa0ef331e2c180c37d4d23e7e7a6d268d8 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 20:57:53 +0000 Subject: [PATCH 16/25] Say "multiple" rather than "several" declarators Pure rename: IsInLocalDeclarationWithSeveralDeclarators becomes IsInLocalDeclarationWithMultipleDeclarators, and the README wording matches. No behaviour change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- CodeConverter/CSharp/NameExpressionNodeVisitor.cs | 6 +++--- CodeConverter/CSharp/README.md | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/CodeConverter/CSharp/NameExpressionNodeVisitor.cs b/CodeConverter/CSharp/NameExpressionNodeVisitor.cs index 7a3815e51..9b4a9b8c1 100644 --- a/CodeConverter/CSharp/NameExpressionNodeVisitor.cs +++ b/CodeConverter/CSharp/NameExpressionNodeVisitor.cs @@ -604,7 +604,7 @@ private bool DefinitelyExecutedAfterPreviousStatement(VBSyntax.InvocationExpress // Being the leftmost invocation of an unqualified method call ensures no other code is executed. Could add other cases here, such as a method call on a local variable name, or "this.". A method call on a property is not acceptable. if (argumentSyntax.Parent.Parent is VBSyntax.InvocationExpressionSyntax parentInvocation && parentInvocation.ArgumentList.Arguments.First() == argumentSyntax && FirstArgDefinitelyEvaluated(parentInvocation)) continue; else return false; - case VBSyntax.VariableDeclaratorSyntax declarator when IsInLocalDeclarationWithSeveralDeclarators(declarator, out var declarators): + case VBSyntax.VariableDeclaratorSyntax declarator when IsInLocalDeclarationWithMultipleDeclarators(declarator, out var declarators): if (declarators.First() == declarator) continue; else return false; case VBSyntax.ElseIfStatementSyntax _: @@ -650,7 +650,7 @@ private static bool NextStatementDefinitelyExecutedAfter(VBSyntax.InvocationExpr case VBSyntax.BinaryExpressionSyntax binaryExpression: if (binaryExpression.Right == invocation) continue; else return false; - case VBSyntax.VariableDeclaratorSyntax declarator when IsInLocalDeclarationWithSeveralDeclarators(declarator, out var declarators): + case VBSyntax.VariableDeclaratorSyntax declarator when IsInLocalDeclarationWithMultipleDeclarators(declarator, out var declarators): if (declarators.Last() == declarator) continue; else return false; case VBSyntax.IfStatementSyntax _: @@ -678,7 +678,7 @@ private static bool NextStatementDefinitelyExecutedAfter(VBSyntax.InvocationExpr /// but temporaries and write-backs are hoisted around the whole converted declaration. /// A Static local's declarators become fields, where a local function couldn't be called, so those keep the old placement. /// - private static bool IsInLocalDeclarationWithSeveralDeclarators(VBSyntax.VariableDeclaratorSyntax declarator, out SeparatedSyntaxList declarators) + private static bool IsInLocalDeclarationWithMultipleDeclarators(VBSyntax.VariableDeclaratorSyntax declarator, out SeparatedSyntaxList declarators) { declarators = declarator.Parent is VBSyntax.LocalDeclarationStatementSyntax localDeclaration && !localDeclaration.Modifiers.Any(m => m.IsKind(VBasic.SyntaxKind.StaticKeyword)) diff --git a/CodeConverter/CSharp/README.md b/CodeConverter/CSharp/README.md index bc2246eff..dd2f5254d 100644 --- a/CodeConverter/CSharp/README.md +++ b/CodeConverter/CSharp/README.md @@ -23,7 +23,7 @@ Sources: [passing arguments by value and by reference](https://learn.microsoft.c |---|---|---| | A statement, as the last thing evaluated, including the right of an assignment whose target isn't read by the write-back (`Q = F(P)`) | temporary before, write-back after the statement | `PerScopeState.CreateLocalsAsync` | | `Return`, `Throw`, `Yield` | `var ret = call; write-back; return ret;` (only when there is a write-back) | `PerScopeState.WithWriteBacksBefore` | -| Followed by other evaluation, or in a condition or block header (`If`, `ElseIf`, loops, `Select Case`, `Case`, `For`, `For Each`, `Using`, `SyncLock`, `With`, `Catch When`), or in a `Dim` declarator that isn't the only one, or the right of an assignment to something the write-back reads (`P = F(P)`, `x = F(h.Items(x))`, `h = F(h.P)`): C# evaluates the assignment target first and stores last, as VB does, and the write-back happens in between | a local function that declares, calls and writes back, called in place | `NameExpressionNodeVisitor.RequiresLocalFunction`, `HoistAndCallLocalFunctionAsync` | +| Followed by other evaluation, or in a condition or block header (`If`, `ElseIf`, loops, `Select Case`, `Case`, `For`, `For Each`, `Using`, `SyncLock`, `With`, `Catch When`), or in one of multiple `Dim` declarators, or the right of an assignment to something the write-back reads (`P = F(P)`, `x = F(h.Items(x))`, `h = F(h.P)`): C# evaluates the assignment target first and stores last, as VB does, and the write-back happens in between | a local function that declares, calls and writes back, called in place | `NameExpressionNodeVisitor.RequiresLocalFunction`, `HoistAndCallLocalFunctionAsync` | | A field initializer | a method that declares, writes back and returns, called from the field (static) or the constructor (instance) | `CommonConversions.WithHoistedNodesInMethodAsync`, `PerScopeState.CreateReturnBlockAsync` | Within each of these, one call's write-backs are hoisted after its whole argument list, last argument first, so a nested call's come before them: `ArgumentConverter.WithWriteBacksInVbOrderAsync`. From 74a6a7927ee74febb0915106de3af42504b8bef6 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 21:28:34 +0000 Subject: [PATCH 17/25] Extract ByRef argument handling into CSharp/ByRefArguments 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 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- CodeConverter/CSharp/ArgumentConverter.cs | 59 +---- .../ByRefArguments/ByRefArgumentHoister.cs | 68 ++++++ CodeConverter/CSharp/ByRefArguments/README.md | 37 +++ .../ByRefArguments/WriteBackPlacement.cs | 231 ++++++++++++++++++ .../CSharp/NameExpressionNodeVisitor.cs | 219 +---------------- CodeConverter/CSharp/README.md | 37 +-- 6 files changed, 353 insertions(+), 298 deletions(-) create mode 100644 CodeConverter/CSharp/ByRefArguments/ByRefArgumentHoister.cs create mode 100644 CodeConverter/CSharp/ByRefArguments/README.md create mode 100644 CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs diff --git a/CodeConverter/CSharp/ArgumentConverter.cs b/CodeConverter/CSharp/ArgumentConverter.cs index c48a72478..adf31ce65 100644 --- a/CodeConverter/CSharp/ArgumentConverter.cs +++ b/CodeConverter/CSharp/ArgumentConverter.cs @@ -1,4 +1,5 @@ -using Microsoft.VisualBasic; +using ICSharpCode.CodeConverter.CSharp.ByRefArguments; +using Microsoft.VisualBasic; namespace ICSharpCode.CodeConverter.CSharp; @@ -9,11 +10,7 @@ internal class ArgumentConverter private readonly ITypeContext _typeContext; private readonly SemanticModel _semanticModel; private CommentConvertingVisitorWrapper TriviaConvertingExpressionVisitor { get; } - - /// - /// The write-backs of each argument list being converted, innermost call on top. - /// - private readonly Stack> _writeBacksPerCall = new(); + public ByRefArgumentHoister ByRefArgumentHoister { get; } public ArgumentConverter(VisualBasicEqualityComparison visualBasicEqualityComparison, ITypeContext typeContext, SemanticModel semanticModel, CommonConversions commonConversions) { @@ -22,6 +19,7 @@ public ArgumentConverter(VisualBasicEqualityComparison visualBasicEqualityCompar _typeContext = typeContext; _semanticModel = semanticModel; TriviaConvertingExpressionVisitor = commonConversions.TriviaConvertingExpressionVisitor; + ByRefArgumentHoister = new ByRefArgumentHoister(typeContext, semanticModel, commonConversions); } public async Task ConvertSimpleArgumentAsync(VBSyntax.SimpleArgumentSyntax node) @@ -40,7 +38,7 @@ public async Task ConvertSimpleArgumentAsync(VBSyntax.SimpleAr var refType = CommonConversions.GetRefConversionType(node, argList, possibleParameters.Value, out var argName, out var refKind); token = CommonConversions.GetRefToken(refKind); if (refType != SemanticModelExtensions.RefConversion.Inline) { - convertedArgExpression = HoistByRefDeclaration(node.Expression, convertedArgExpression, refType, argName, refKind); + convertedArgExpression = ByRefArgumentHoister.HoistByRefDeclaration(node.Expression, convertedArgExpression, refType, argName, refKind); } else { convertedArgExpression = typeConversionAnalyzer.AddExplicitConversion(node.Expression, convertedArgExpression, defaultToCast: refKind != RefKind.None); } @@ -59,7 +57,7 @@ public async Task ConvertSimpleArgumentAsync(VBSyntax.SimpleAr var invocationHasOverloads = invocationSymbol.HasOverloads(); var processedParameters = new HashSet(StringComparer.OrdinalIgnoreCase); - var argumentSyntaxs = (await WithWriteBacksInVbOrderAsync(() => node.Arguments.SelectAsync(ConvertArg))).Where(a => a != null); + var argumentSyntaxs = (await ByRefArgumentHoister.WithWriteBacksInVbOrderAsync(() => node.Arguments.SelectAsync(ConvertArg))).Where(a => a != null); return Enumerable.Concat(argumentSyntaxs, GetAdditionalRequiredArgs(node.Arguments, processedParameters, invocationSymbol, invocationHasOverloads)); async Task ConvertArg(VBSyntax.ArgumentSyntax arg, int argIndex) @@ -124,51 +122,6 @@ CSSyntax.ArgumentSyntax ConvertOmittedArgument(IParameterSymbol parameter) } - /// - /// VB copies back a call's ByRef arguments from the last to the first (copyBackArray.ReverseContents() in Roslyn's LocalRewriter_Call.vb), - /// which is observable when two arguments write back to the same place. - /// A nested call has already written back by then, so only this call's own write-backs are reversed. - /// - private async Task WithWriteBacksInVbOrderAsync(Func> convertArguments) - { - _writeBacksPerCall.Push(new List()); - T converted; - try { - converted = await convertArguments(); - } finally { - var writeBacks = _writeBacksPerCall.Pop(); - foreach (var writeBack in Enumerable.Reverse(writeBacks)) _typeContext.PerScopeState.Hoist(writeBack); - } - return converted; - } - - internal CSSyntax.ExpressionSyntax HoistByRefDeclaration(VBSyntax.ExpressionSyntax node, CSSyntax.ExpressionSyntax refLValue, SemanticModelExtensions.RefConversion refType, string argName, RefKind refKind) - { - string prefix = $"arg{argName}"; - var expressionTypeInfo = _semanticModel.GetTypeInfo(node); - bool useVar = expressionTypeInfo.Type?.Equals(expressionTypeInfo.ConvertedType, SymbolEqualityComparer.IncludeNullability) == true && !CommonConversions.ShouldPreferExplicitType(node, expressionTypeInfo.ConvertedType, out var _); - var typeSyntax = CommonConversions.GetTypeSyntax(expressionTypeInfo.ConvertedType, useVar); - - if (refLValue is CSSyntax.ElementAccessExpressionSyntax eae) { - //Hoist out the container so we can assign back to the same one after (like VB does) - var tmpContainer = _typeContext.PerScopeState.Hoist(new AdditionalDeclaration("tmp", eae.Expression, ValidSyntaxFactory.VarType)); - refLValue = eae.WithExpression(tmpContainer.IdentifierName); - } - - var withCast = CommonConversions.TypeConversionAnalyzer.AddExplicitConversion(node, refLValue, defaultToCast: refKind != RefKind.None); - - var local = _typeContext.PerScopeState.Hoist(new AdditionalDeclaration(prefix, withCast, typeSyntax)); - - if (refType == SemanticModelExtensions.RefConversion.PreAndPostAssignment) { - var convertedLocalIdentifier = CommonConversions.TypeConversionAnalyzer.AddExplicitConversion(node, local.IdentifierName, forceSourceType: expressionTypeInfo.ConvertedType, forceTargetType: expressionTypeInfo.Type); - var writeBack = new AdditionalAssignment(refLValue, convertedLocalIdentifier); - if (_writeBacksPerCall.Count > 0) _writeBacksPerCall.Peek().Add(writeBack); - else _typeContext.PerScopeState.Hoist(writeBack); - } - - return local.IdentifierName; - } - private static CSSyntax.ExpressionSyntax LiteralOrDefault(object value, ITypeSymbol paramType) { if (value is null && paramType.IsValueType) { diff --git a/CodeConverter/CSharp/ByRefArguments/ByRefArgumentHoister.cs b/CodeConverter/CSharp/ByRefArguments/ByRefArgumentHoister.cs new file mode 100644 index 000000000..abd89565e --- /dev/null +++ b/CodeConverter/CSharp/ByRefArguments/ByRefArgumentHoister.cs @@ -0,0 +1,68 @@ +namespace ICSharpCode.CodeConverter.CSharp.ByRefArguments; + +/// +/// C# can only pass a variable by reference, so a ByRef argument that isn't one gets a temporary, and VB's copy-back becomes a write-back statement. +/// +internal class ByRefArgumentHoister +{ + private readonly ITypeContext _typeContext; + private readonly SemanticModel _semanticModel; + private CommonConversions CommonConversions { get; } + + /// + /// The write-backs of each argument list being converted, innermost call on top. + /// + private readonly Stack> _writeBacksPerCall = new(); + + public ByRefArgumentHoister(ITypeContext typeContext, SemanticModel semanticModel, CommonConversions commonConversions) + { + _typeContext = typeContext; + _semanticModel = semanticModel; + CommonConversions = commonConversions; + } + + /// + /// VB copies back a call's ByRef arguments from the last to the first (copyBackArray.ReverseContents() in Roslyn's LocalRewriter_Call.vb), + /// which is observable when two arguments write back to the same place. + /// A nested call has already written back by then, so only this call's own write-backs are reversed. + /// + public async Task WithWriteBacksInVbOrderAsync(Func> convertArguments) + { + _writeBacksPerCall.Push(new List()); + T converted; + try { + converted = await convertArguments(); + } finally { + var writeBacks = _writeBacksPerCall.Pop(); + foreach (var writeBack in Enumerable.Reverse(writeBacks)) _typeContext.PerScopeState.Hoist(writeBack); + } + return converted; + } + + public CSSyntax.ExpressionSyntax HoistByRefDeclaration(VBSyntax.ExpressionSyntax node, CSSyntax.ExpressionSyntax refLValue, SemanticModelExtensions.RefConversion refType, string argName, RefKind refKind) + { + string prefix = $"arg{argName}"; + var expressionTypeInfo = _semanticModel.GetTypeInfo(node); + bool useVar = expressionTypeInfo.Type?.Equals(expressionTypeInfo.ConvertedType, SymbolEqualityComparer.IncludeNullability) == true && !CommonConversions.ShouldPreferExplicitType(node, expressionTypeInfo.ConvertedType, out var _); + var typeSyntax = CommonConversions.GetTypeSyntax(expressionTypeInfo.ConvertedType, useVar); + + if (refLValue is CSSyntax.ElementAccessExpressionSyntax eae) { + //Hoist out the container so we can assign back to the same one after (like VB does) + var tmpContainer = _typeContext.PerScopeState.Hoist(new AdditionalDeclaration("tmp", eae.Expression, ValidSyntaxFactory.VarType)); + refLValue = eae.WithExpression(tmpContainer.IdentifierName); + } + + var withCast = CommonConversions.TypeConversionAnalyzer.AddExplicitConversion(node, refLValue, defaultToCast: refKind != RefKind.None); + + var local = _typeContext.PerScopeState.Hoist(new AdditionalDeclaration(prefix, withCast, typeSyntax)); + + if (refType == SemanticModelExtensions.RefConversion.PreAndPostAssignment) { + var convertedLocalIdentifier = CommonConversions.TypeConversionAnalyzer.AddExplicitConversion(node, local.IdentifierName, forceSourceType: expressionTypeInfo.ConvertedType, forceTargetType: expressionTypeInfo.Type); + var writeBack = new AdditionalAssignment(refLValue, convertedLocalIdentifier); + if (_writeBacksPerCall.Count > 0) _writeBacksPerCall.Peek().Add(writeBack); + else _typeContext.PerScopeState.Hoist(writeBack); + } + + return local.IdentifierName; + } +} diff --git a/CodeConverter/CSharp/ByRefArguments/README.md b/CodeConverter/CSharp/ByRefArguments/README.md new file mode 100644 index 000000000..69c1ff30b --- /dev/null +++ b/CodeConverter/CSharp/ByRefArguments/README.md @@ -0,0 +1,37 @@ +# VB → C# ByRef arguments that need a temporary + +Sources: [passing arguments by value and by reference](https://learn.microsoft.com/dotnet/visual-basic/programming-guide/language-features/procedures/passing-arguments-by-value-and-by-reference) and Roslyn's VB lowering in [`LocalRewriter_Call.vb`](https://github.com/dotnet/roslyn/blob/main/src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_Call.vb): `RewriteByRefArgumentWithCopyBack` creates the temporary, and `VisitCall` wraps the call in a sequence whose side effects after the value are the copy-backs. Behaviour below is covered by `Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb`. + +## VB + +* A ByRef parameter accepts any expression. If it isn't a variable (a property, a method result, a constant, an omitted `Optional` argument), VB passes a temporary. +* For a writable property (or a `ReadOnly` auto-property inside its constructor), VB copies the temporary back **straight after the call returns**, before the rest of the enclosing expression or statement runs. +* One call copies back its arguments from the last to the first (`copyBackArray.ReverseContents()` in `LocalRewriter_Call.vb`). It's observable when two arguments write back to the same place, e.g. `Two(p.Value, p.Value)`. A call nested in an argument has already copied back by then. + +## C# + +* `ref`/`out` need a variable, so the temporary must be declared in a statement before the call. +* There is no expression-level copy-back, so a write-back is a statement too. + +## Implementation + +`ByRefArgumentHoister.HoistByRefDeclaration` hoists the temporary (`AdditionalDeclaration`) and, when VB copies back, the write-back (`AdditionalAssignment`) into the current `PerScopeState` scope. `PerScopeState.CreateLocalsAsync` emits them before and after the converted statement. The output takes the simplest form that keeps VB's timing: + +| Where the call is | C# | Code | +|---|---|---| +| A statement, as the last thing evaluated, including the right of an assignment whose target isn't read by the write-back (`Q = F(P)`) | temporary before, write-back after the statement | `PerScopeState.CreateLocalsAsync` | +| `Return`, `Throw`, `Yield` | `var ret = call; write-back; return ret;` (only when there is a write-back) | `PerScopeState.WithWriteBacksBefore` | +| Followed by other evaluation, or in a condition or block header (`If`, `ElseIf`, loops, `Select Case`, `Case`, `For`, `For Each`, `Using`, `SyncLock`, `With`, `Catch When`), or in one of multiple `Dim` declarators, or the right of an assignment to something the write-back reads (`P = F(P)`, `x = F(h.Items(x))`, `h = F(h.P)`): C# evaluates the assignment target first and stores last, as VB does, and the write-back happens in between | a local function that declares, calls and writes back, called in place | `WriteBackPlacement.RequiresLocalFunction`, `HoistAndCallLocalFunctionAsync` | +| A field initializer | a method that declares, writes back and returns, called from the field (static) or the constructor (instance) | `CommonConversions.WithHoistedNodesInMethodAsync`, `PerScopeState.CreateReturnBlockAsync` | + +Within each of these, one call's write-backs are hoisted after its whole argument list, last argument first, so a nested call's come before them: `ByRefArgumentHoister.WithWriteBacksInVbOrderAsync`. + +The classes in this folder hold the ByRef-specific decisions. The placement mechanics stay with the code they extend: the hoisted node types and `PerScopeState` (the hoisting for every feature), `MethodBodyExecutableStatementVisitor` (jumps) and `CommonConversions` (field initializers, whose method wraps any hoisted statement, not only ByRef ones). + +Known gaps: +* Arguments of `New` (object creation) in a block header still write back after the block. +* A non-constant `For ... Step` is re-evaluated each iteration (not ByRef-specific). +* A lambda parameter inside a ByRef argument (`Function(x) Inc(x.P)`) hoists the local function outside the lambda, where `x` isn't in scope (CS0103). +* An auto-property initializer (`Public Property X As Integer = Inc(P)`) leaves a `ph…` placeholder (CS0103): it doesn't go through the field initializer path. +* Partial-class instance initializers run in part order rather than declaration order. +* A `ReadOnly` auto-property is assignable in its type's constructor and initializers, so VB writes it back there, but `GetRefConversionForExpression` treats every read-only property as not writable. A fix also needs the C# write-back target to be assignable from the field initializer method. diff --git a/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs b/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs new file mode 100644 index 000000000..5229088bf --- /dev/null +++ b/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs @@ -0,0 +1,231 @@ +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Operations; +using static ICSharpCode.CodeConverter.CSharp.SemanticModelExtensions; + +namespace ICSharpCode.CodeConverter.CSharp.ByRefArguments; + +/// +/// Decides whether a call's ByRef temporaries can be declared before, and written back after, the converted statement, +/// and otherwise moves the call into a local function that writes back straight after it, as VB does. +/// +internal class WriteBackPlacement +{ + private readonly SemanticModel _semanticModel; + private readonly HashSet _generatedNames; + private readonly ITypeContext _typeContext; + + public WriteBackPlacement(SemanticModel semanticModel, HashSet generatedNames, ITypeContext typeContext, CommonConversions commonConversions) + { + _semanticModel = semanticModel; + _generatedNames = generatedNames; + _typeContext = typeContext; + CommonConversions = commonConversions; + } + + private CommonConversions CommonConversions { get; } + + /// + /// The VB compiler actually just hoists the conditions within the same method, but that leads to the original logic looking very different. + /// This should be equivalent but keep closer to the look of the original source code. + /// See https://github.com/icsharpcode/CodeConverter/issues/310 and https://github.com/icsharpcode/CodeConverter/issues/324 + /// + public async Task HoistAndCallLocalFunctionAsync(VBasic.VisualBasicSyntaxNode invocation, IMethodSymbol invocationSymbol, ExpressionSyntax csExpression) + { + const string retVariableName = "ret"; + var localFuncName = $"local{invocationSymbol.Name}"; + + var callAndStoreResult = CommonConversions.CreateLocalVariableDeclarationAndAssignment(retVariableName, csExpression); + + var statements = await _typeContext.PerScopeState.CreateLocalsAsync(invocation, new[] { callAndStoreResult }, _generatedNames, _semanticModel); + + var block = SyntaxFactory.Block( + statements.Concat(SyntaxFactory.ReturnStatement(ValidSyntaxFactory.IdentifierName(retVariableName)).Yield()) + ); + var returnType = CommonConversions.GetTypeSyntax(invocationSymbol.ReturnType); + + // Parent ByRef parameters cannot be captured, including references in receivers and nested argument expressions. + var enclosingSymbol = _semanticModel.GetEnclosingSymbol(invocation.SpanStart); + var refParametersOfParent = (_semanticModel.GetOperation(invocation)?.DescendantsAndSelf() + .OfType().Select(p => p.Parameter) ?? Enumerable.Empty()) + .Where(p => p.RefKind != RefKind.None && SymbolEqualityComparer.Default.Equals(p.ContainingSymbol, enclosingSymbol)) + .Distinct(SymbolEqualityComparer.Default).ToList(); + var (args, @params) = CreateArgumentsAndParametersLists(refParametersOfParent); + + var localFunc = _typeContext.PerScopeState.Hoist(new HoistedFunction(localFuncName, returnType, block, SyntaxFactory.ParameterList(@params))); + return SyntaxFactory.InvocationExpression(localFunc.TempIdentifier, SyntaxFactory.ArgumentList(args)); + + (SeparatedSyntaxList, SeparatedSyntaxList) CreateArgumentsAndParametersLists(List parameterSymbols) + { + var arguments = new List(); + var parameters = new List(); + foreach (var p in parameterSymbols) { + var arg = (ArgumentSyntax)CommonConversions.CsSyntaxGenerator.Argument(p.RefKind, SyntaxFactory.IdentifierName(p.Name)); + arguments.Add(arg); + var par = (ParameterSyntax)CommonConversions.CsSyntaxGenerator.ParameterDeclaration(p); + parameters.Add(par.WithDefault(null)); + } + return (SyntaxFactory.SeparatedList(arguments), SyntaxFactory.SeparatedList(parameters)); + } + } + + public bool RequiresLocalFunction(VBSyntax.InvocationExpressionSyntax invocation, IMethodSymbol invocationSymbol) + { + if (IsLoopCondition(invocation)) { + // A loop condition needs fresh argument temporaries and copy-back on every evaluation. + return invocationSymbol.ReducedFrom?.Parameters.FirstOrDefault() is { RefKind: not RefKind.None } && + invocation.Expression is VBSyntax.MemberAccessExpressionSyntax member && + _semanticModel.GetRefConversionForExpression(member.Expression) != RefConversion.Inline || + invocation.ArgumentList?.Arguments.Any(a => + CommonConversions.GetRefConversionType(a, invocation.ArgumentList, invocationSymbol.Parameters, out _, out _) != RefConversion.Inline) == true || + _semanticModel.GetOperation(invocation) is IInvocationOperation operation && operation.Arguments.Any(a => + a.ArgumentKind == ArgumentKind.DefaultValue && a.Parameter.RefKind != RefKind.None); + } + + if (invocation.ArgumentList == null) return false; + var definitelyExecutedAfterPrevious = DefinitelyExecutedAfterPreviousStatement(invocation); + var nextStatementDefinitelyExecuted = NextStatementDefinitelyExecutedAfter(invocation) && !AssignmentChangesWhatIsWrittenBack(invocation, invocationSymbol); + if (definitelyExecutedAfterPrevious && nextStatementDefinitelyExecuted) return false; + var possibleInline = definitelyExecutedAfterPrevious ? RefConversion.PreAssigment : RefConversion.Inline; + return invocation.ArgumentList.Arguments.Any(a => RequiresLocalFunction(possibleInline, invocation, invocationSymbol, a)); + + bool RequiresLocalFunction(RefConversion possibleInline, VBSyntax.InvocationExpressionSyntax invocation, IMethodSymbol invocationSymbol, VBSyntax.ArgumentSyntax a) + { + var refConversion = CommonConversions.GetRefConversionType(a, invocation.ArgumentList, invocationSymbol.Parameters, out string _, out _); + if (RefConversion.Inline == refConversion || possibleInline == refConversion) return false; + if (!(a is VBSyntax.SimpleArgumentSyntax sas)) return false; + var argExpression = sas.Expression.SkipIntoParens(); + if (argExpression is VBSyntax.InstanceExpressionSyntax) return false; + return !_semanticModel.GetConstantValue(argExpression).HasValue; + } + } + + /// + /// VB writes back straight after the call, before the enclosing assignment stores its result. + /// A write-back emitted after the assignment statement would overwrite the assigned target (h.P = F(h.P)), + /// or write to a different place if the assignment changes something the write-back target reads (x = F(h.Items(x)), h = F(h.P)). + /// Other assignments keep the write-back after the statement. + /// + private bool AssignmentChangesWhatIsWrittenBack(VBSyntax.InvocationExpressionSyntax invocation, IMethodSymbol invocationSymbol) + { + if (invocation.Ancestors().FirstOrDefault(n => n is VBSyntax.StatementSyntax or VBSyntax.LambdaExpressionSyntax) is not VBSyntax.AssignmentStatementSyntax assignment || + !assignment.Right.Span.Contains(invocation.Span)) { + return false; + } + + var assignedSymbol = _semanticModel.GetSymbolInfo(assignment.Left).Symbol ?? + (assignment.Left is VBSyntax.InvocationExpressionSyntax { Expression: var indexed } ? _semanticModel.GetSymbolInfo(indexed).Symbol : null); + var writtenBackExpressions = invocation.ArgumentList.Arguments.OfType() + .Where(a => CommonConversions.GetRefConversionType(a, invocation.ArgumentList, invocationSymbol.Parameters, out _, out _) == RefConversion.PreAndPostAssignment) + .Select(a => a.Expression); + return writtenBackExpressions.Any(e => assignedSymbol is null || + e.DescendantNodesAndSelf().OfType().Any(n => SymbolEqualityComparer.Default.Equals(_semanticModel.GetSymbolInfo(n).Symbol, assignedSymbol))); + } + + public static bool IsLoopCondition(SyntaxNode node) + { + var containingStatement = node.Ancestors().FirstOrDefault(n => n is VBSyntax.StatementSyntax or VBSyntax.LambdaExpressionSyntax); + return containingStatement is VBSyntax.WhileStatementSyntax or VBSyntax.DoStatementSyntax or VBSyntax.LoopStatementSyntax; + } + + /// + /// Conservative version of _semanticModel.AnalyzeControlFlow(invocation).ExitPoints to account for exceptions + /// + private bool DefinitelyExecutedAfterPreviousStatement(VBSyntax.InvocationExpressionSyntax invocation) + { + SyntaxNode parent = invocation; + while (true) { + parent = parent.Parent; + switch (parent) { + case VBSyntax.ParenthesizedExpressionSyntax _: + continue; + case VBSyntax.BinaryExpressionSyntax binaryExpression: + if (binaryExpression.Left == invocation) continue; + else return false; + case VBSyntax.ArgumentSyntax argumentSyntax: + // Being the leftmost invocation of an unqualified method call ensures no other code is executed. Could add other cases here, such as a method call on a local variable name, or "this.". A method call on a property is not acceptable. + if (argumentSyntax.Parent.Parent is VBSyntax.InvocationExpressionSyntax parentInvocation && parentInvocation.ArgumentList.Arguments.First() == argumentSyntax && FirstArgDefinitelyEvaluated(parentInvocation)) continue; + else return false; + case VBSyntax.VariableDeclaratorSyntax declarator when IsInLocalDeclarationWithMultipleDeclarators(declarator, out var declarators): + if (declarators.First() == declarator) continue; + else return false; + case VBSyntax.ElseIfStatementSyntax _: + case VBSyntax.ExpressionSyntax _: + return false; + case VBSyntax.StatementSyntax _: + return true; + } + } + } + + private bool FirstArgDefinitelyEvaluated(VBSyntax.InvocationExpressionSyntax parentInvocation) => + parentInvocation.Expression.SkipIntoParens() switch { + VBSyntax.IdentifierNameSyntax _ => true, + VBSyntax.MemberAccessExpressionSyntax maes => maes.Expression is { } exp && !MayThrow(exp), + _ => true + }; + + /// + /// Safe overapproximation of whether an expression may throw. + /// + private bool MayThrow(VBSyntax.ExpressionSyntax expression) + { + expression = expression.SkipIntoParens(); + if (expression is VBSyntax.InstanceExpressionSyntax) return false; + var symbol = _semanticModel.GetSymbolInfo(expression).Symbol; + return !symbol.IsKind(SymbolKind.Local) && !symbol.IsKind(SymbolKind.Field); + } + + /// + /// Conservative version of _semanticModel.AnalyzeControlFlow(invocation).ExitPoints to account for exceptions. + /// A block's header statement is followed by its body, so a write-back placed after the converted block would run too late + /// (or, for a later Case clause, run when the clause was never evaluated). + /// + private static bool NextStatementDefinitelyExecutedAfter(VBSyntax.InvocationExpressionSyntax invocation) + { + SyntaxNode parent = invocation; + while (true) { + parent = parent.Parent; + switch (parent) { + case VBSyntax.ParenthesizedExpressionSyntax _: + continue; + case VBSyntax.BinaryExpressionSyntax binaryExpression: + if (binaryExpression.Right == invocation) continue; + else return false; + case VBSyntax.VariableDeclaratorSyntax declarator when IsInLocalDeclarationWithMultipleDeclarators(declarator, out var declarators): + if (declarators.Last() == declarator) continue; + else return false; + case VBSyntax.IfStatementSyntax _: + case VBSyntax.ElseIfStatementSyntax _: + case VBSyntax.SingleLineIfStatementSyntax _: + case VBSyntax.SelectStatementSyntax _: + case VBSyntax.CaseStatementSyntax _: + case VBSyntax.ForStatementSyntax _: + case VBSyntax.ForEachStatementSyntax _: + case VBSyntax.UsingStatementSyntax _: + case VBSyntax.SyncLockStatementSyntax _: + case VBSyntax.WithStatementSyntax _: + case VBSyntax.CatchStatementSyntax _: + return false; + case VBSyntax.ExpressionSyntax _: + case VBSyntax.StatementSyntax _: + return true; + } + } + } + + + /// + /// VB evaluates each declarator of Dim a = F(p.X), b = F(p.X) in turn, writing back before the next one starts, + /// but temporaries and write-backs are hoisted around the whole converted declaration. + /// A Static local's declarators become fields, where a local function couldn't be called, so those keep the old placement. + /// + private static bool IsInLocalDeclarationWithMultipleDeclarators(VBSyntax.VariableDeclaratorSyntax declarator, out SeparatedSyntaxList declarators) + { + declarators = declarator.Parent is VBSyntax.LocalDeclarationStatementSyntax localDeclaration && + !localDeclaration.Modifiers.Any(m => m.IsKind(VBasic.SyntaxKind.StaticKeyword)) + ? localDeclaration.Declarators + : default; + return declarators.Count > 1; + } +} diff --git a/CodeConverter/CSharp/NameExpressionNodeVisitor.cs b/CodeConverter/CSharp/NameExpressionNodeVisitor.cs index 9b4a9b8c1..75ce07eab 100644 --- a/CodeConverter/CSharp/NameExpressionNodeVisitor.cs +++ b/CodeConverter/CSharp/NameExpressionNodeVisitor.cs @@ -1,5 +1,6 @@ -using System.Data; +using System.Data; using System.Globalization; +using ICSharpCode.CodeConverter.CSharp.ByRefArguments; using ICSharpCode.CodeConverter.CSharp.Queries; using ICSharpCode.CodeConverter.CSharp.Replacements; using ICSharpCode.CodeConverter.Util.FromRoslyn; @@ -23,6 +24,7 @@ internal class NameExpressionNodeVisitor private readonly Dictionary _conditionalAccessReceivers; private readonly ArgumentConverter _argumentConverter; private readonly RangeVariableReplacements _rangeVariableReplacements; + private readonly WriteBackPlacement _writeBackPlacement; public CommonConversions CommonConversions { get; } public CommentConvertingVisitorWrapper TriviaConvertingExpressionVisitor { get; } @@ -45,6 +47,7 @@ public NameExpressionNodeVisitor(SemanticModel semanticModel, HashSet ge _argumentConverter = argumentConverter; CommonConversions = commonConversions; TriviaConvertingExpressionVisitor = triviaConvertingExpressionVisitor; + _writeBackPlacement = new WriteBackPlacement(semanticModel, generatedNames, typeContext, commonConversions); } public async Task ConvertMemberAccessExpressionAsync(VBasic.Syntax.MemberAccessExpressionSyntax node) @@ -213,7 +216,7 @@ public async Task ConvertInvocationExpressionAsync( { var invocationSymbol = _semanticModel.GetSymbolInfo(node).ExtractBestMatch(); var methodInvocationSymbol = invocationSymbol as IMethodSymbol; - var withinLocalFunction = methodInvocationSymbol != null && RequiresLocalFunction(node, methodInvocationSymbol); + var withinLocalFunction = methodInvocationSymbol != null && _writeBackPlacement.RequiresLocalFunction(node, methodInvocationSymbol); if (withinLocalFunction) { _typeContext.PerScopeState.PushScope(); } @@ -229,7 +232,7 @@ public async Task ConvertInvocationExpressionAsync( var convertedInvocation = await ConvertOrReplaceInvocationAsync(node, invocationSymbol); if (withinLocalFunction) { - return await HoistAndCallLocalFunctionAsync(node, methodInvocationSymbol, (ExpressionSyntax)convertedInvocation); + return await _writeBackPlacement.HoistAndCallLocalFunctionAsync(node, methodInvocationSymbol, (ExpressionSyntax)convertedInvocation); } return convertedInvocation; } finally { @@ -375,7 +378,7 @@ private async Task ConvertInvocationAsync(VBSyntax.InvocationE var thisArgExpression = await maes.Expression.AcceptAsync(TriviaConvertingExpressionVisitor); if (requiresHoist) { - thisArgExpression = _argumentConverter.HoistByRefDeclaration(maes.Expression, thisArgExpression, refConversion, thisParam.Name, refKind); + thisArgExpression = _argumentConverter.ByRefArgumentHoister.HoistByRefDeclaration(maes.Expression, thisArgExpression, refConversion, thisParam.Name, refKind); } if (requiresStaticInvocation) { @@ -483,210 +486,6 @@ private async Task TryConvertParameterizedPropertyAs } - /// - /// The VB compiler actually just hoists the conditions within the same method, but that leads to the original logic looking very different. - /// This should be equivalent but keep closer to the look of the original source code. - /// See https://github.com/icsharpcode/CodeConverter/issues/310 and https://github.com/icsharpcode/CodeConverter/issues/324 - /// - private async Task HoistAndCallLocalFunctionAsync(VBasic.VisualBasicSyntaxNode invocation, IMethodSymbol invocationSymbol, ExpressionSyntax csExpression) - { - const string retVariableName = "ret"; - var localFuncName = $"local{invocationSymbol.Name}"; - - var callAndStoreResult = CommonConversions.CreateLocalVariableDeclarationAndAssignment(retVariableName, csExpression); - - var statements = await _typeContext.PerScopeState.CreateLocalsAsync(invocation, new[] { callAndStoreResult }, _generatedNames, _semanticModel); - - var block = SyntaxFactory.Block( - statements.Concat(SyntaxFactory.ReturnStatement(ValidSyntaxFactory.IdentifierName(retVariableName)).Yield()) - ); - var returnType = CommonConversions.GetTypeSyntax(invocationSymbol.ReturnType); - - // Parent ByRef parameters cannot be captured, including references in receivers and nested argument expressions. - var enclosingSymbol = _semanticModel.GetEnclosingSymbol(invocation.SpanStart); - var refParametersOfParent = (_semanticModel.GetOperation(invocation)?.DescendantsAndSelf() - .OfType().Select(p => p.Parameter) ?? Enumerable.Empty()) - .Where(p => p.RefKind != RefKind.None && SymbolEqualityComparer.Default.Equals(p.ContainingSymbol, enclosingSymbol)) - .Distinct(SymbolEqualityComparer.Default).ToList(); - var (args, @params) = CreateArgumentsAndParametersLists(refParametersOfParent); - - var localFunc = _typeContext.PerScopeState.Hoist(new HoistedFunction(localFuncName, returnType, block, SyntaxFactory.ParameterList(@params))); - return SyntaxFactory.InvocationExpression(localFunc.TempIdentifier, SyntaxFactory.ArgumentList(args)); - - (SeparatedSyntaxList, SeparatedSyntaxList) CreateArgumentsAndParametersLists(List parameterSymbols) - { - var arguments = new List(); - var parameters = new List(); - foreach (var p in parameterSymbols) { - var arg = (ArgumentSyntax)CommonConversions.CsSyntaxGenerator.Argument(p.RefKind, SyntaxFactory.IdentifierName(p.Name)); - arguments.Add(arg); - var par = (ParameterSyntax)CommonConversions.CsSyntaxGenerator.ParameterDeclaration(p); - parameters.Add(par.WithDefault(null)); - } - return (SyntaxFactory.SeparatedList(arguments), SyntaxFactory.SeparatedList(parameters)); - } - } - - private bool RequiresLocalFunction(VBSyntax.InvocationExpressionSyntax invocation, IMethodSymbol invocationSymbol) - { - if (IsLoopCondition(invocation)) { - // A loop condition needs fresh argument temporaries and copy-back on every evaluation. - return invocationSymbol.ReducedFrom?.Parameters.FirstOrDefault() is { RefKind: not RefKind.None } && - invocation.Expression is VBSyntax.MemberAccessExpressionSyntax member && - _semanticModel.GetRefConversionForExpression(member.Expression) != RefConversion.Inline || - invocation.ArgumentList?.Arguments.Any(a => - CommonConversions.GetRefConversionType(a, invocation.ArgumentList, invocationSymbol.Parameters, out _, out _) != RefConversion.Inline) == true || - _semanticModel.GetOperation(invocation) is IInvocationOperation operation && operation.Arguments.Any(a => - a.ArgumentKind == ArgumentKind.DefaultValue && a.Parameter.RefKind != RefKind.None); - } - - if (invocation.ArgumentList == null) return false; - var definitelyExecutedAfterPrevious = DefinitelyExecutedAfterPreviousStatement(invocation); - var nextStatementDefinitelyExecuted = NextStatementDefinitelyExecutedAfter(invocation) && !AssignmentChangesWhatIsWrittenBack(invocation, invocationSymbol); - if (definitelyExecutedAfterPrevious && nextStatementDefinitelyExecuted) return false; - var possibleInline = definitelyExecutedAfterPrevious ? RefConversion.PreAssigment : RefConversion.Inline; - return invocation.ArgumentList.Arguments.Any(a => RequiresLocalFunction(possibleInline, invocation, invocationSymbol, a)); - - bool RequiresLocalFunction(RefConversion possibleInline, VBSyntax.InvocationExpressionSyntax invocation, IMethodSymbol invocationSymbol, VBSyntax.ArgumentSyntax a) - { - var refConversion = CommonConversions.GetRefConversionType(a, invocation.ArgumentList, invocationSymbol.Parameters, out string _, out _); - if (RefConversion.Inline == refConversion || possibleInline == refConversion) return false; - if (!(a is VBSyntax.SimpleArgumentSyntax sas)) return false; - var argExpression = sas.Expression.SkipIntoParens(); - if (argExpression is VBSyntax.InstanceExpressionSyntax) return false; - return !_semanticModel.GetConstantValue(argExpression).HasValue; - } - } - - /// - /// VB writes back straight after the call, before the enclosing assignment stores its result. - /// A write-back emitted after the assignment statement would overwrite the assigned target (h.P = F(h.P)), - /// or write to a different place if the assignment changes something the write-back target reads (x = F(h.Items(x)), h = F(h.P)). - /// Other assignments keep the write-back after the statement. - /// - private bool AssignmentChangesWhatIsWrittenBack(VBSyntax.InvocationExpressionSyntax invocation, IMethodSymbol invocationSymbol) - { - if (invocation.Ancestors().FirstOrDefault(n => n is VBSyntax.StatementSyntax or VBSyntax.LambdaExpressionSyntax) is not VBSyntax.AssignmentStatementSyntax assignment || - !assignment.Right.Span.Contains(invocation.Span)) { - return false; - } - - var assignedSymbol = _semanticModel.GetSymbolInfo(assignment.Left).Symbol ?? - (assignment.Left is VBSyntax.InvocationExpressionSyntax { Expression: var indexed } ? _semanticModel.GetSymbolInfo(indexed).Symbol : null); - var writtenBackExpressions = invocation.ArgumentList.Arguments.OfType() - .Where(a => CommonConversions.GetRefConversionType(a, invocation.ArgumentList, invocationSymbol.Parameters, out _, out _) == RefConversion.PreAndPostAssignment) - .Select(a => a.Expression); - return writtenBackExpressions.Any(e => assignedSymbol is null || - e.DescendantNodesAndSelf().OfType().Any(n => SymbolEqualityComparer.Default.Equals(_semanticModel.GetSymbolInfo(n).Symbol, assignedSymbol))); - } - - private static bool IsLoopCondition(SyntaxNode node) - { - var containingStatement = node.Ancestors().FirstOrDefault(n => n is VBSyntax.StatementSyntax or VBSyntax.LambdaExpressionSyntax); - return containingStatement is VBSyntax.WhileStatementSyntax or VBSyntax.DoStatementSyntax or VBSyntax.LoopStatementSyntax; - } - - /// - /// Conservative version of _semanticModel.AnalyzeControlFlow(invocation).ExitPoints to account for exceptions - /// - private bool DefinitelyExecutedAfterPreviousStatement(VBSyntax.InvocationExpressionSyntax invocation) - { - SyntaxNode parent = invocation; - while (true) { - parent = parent.Parent; - switch (parent) { - case VBSyntax.ParenthesizedExpressionSyntax _: - continue; - case VBSyntax.BinaryExpressionSyntax binaryExpression: - if (binaryExpression.Left == invocation) continue; - else return false; - case VBSyntax.ArgumentSyntax argumentSyntax: - // Being the leftmost invocation of an unqualified method call ensures no other code is executed. Could add other cases here, such as a method call on a local variable name, or "this.". A method call on a property is not acceptable. - if (argumentSyntax.Parent.Parent is VBSyntax.InvocationExpressionSyntax parentInvocation && parentInvocation.ArgumentList.Arguments.First() == argumentSyntax && FirstArgDefinitelyEvaluated(parentInvocation)) continue; - else return false; - case VBSyntax.VariableDeclaratorSyntax declarator when IsInLocalDeclarationWithMultipleDeclarators(declarator, out var declarators): - if (declarators.First() == declarator) continue; - else return false; - case VBSyntax.ElseIfStatementSyntax _: - case VBSyntax.ExpressionSyntax _: - return false; - case VBSyntax.StatementSyntax _: - return true; - } - } - } - - private bool FirstArgDefinitelyEvaluated(VBSyntax.InvocationExpressionSyntax parentInvocation) => - parentInvocation.Expression.SkipIntoParens() switch { - VBSyntax.IdentifierNameSyntax _ => true, - VBSyntax.MemberAccessExpressionSyntax maes => maes.Expression is { } exp && !MayThrow(exp), - _ => true - }; - - /// - /// Safe overapproximation of whether an expression may throw. - /// - private bool MayThrow(VBSyntax.ExpressionSyntax expression) - { - expression = expression.SkipIntoParens(); - if (expression is VBSyntax.InstanceExpressionSyntax) return false; - var symbol = _semanticModel.GetSymbolInfo(expression).Symbol; - return !symbol.IsKind(SymbolKind.Local) && !symbol.IsKind(SymbolKind.Field); - } - - /// - /// Conservative version of _semanticModel.AnalyzeControlFlow(invocation).ExitPoints to account for exceptions. - /// A block's header statement is followed by its body, so a write-back placed after the converted block would run too late - /// (or, for a later Case clause, run when the clause was never evaluated). - /// - private static bool NextStatementDefinitelyExecutedAfter(VBSyntax.InvocationExpressionSyntax invocation) - { - SyntaxNode parent = invocation; - while (true) { - parent = parent.Parent; - switch (parent) { - case VBSyntax.ParenthesizedExpressionSyntax _: - continue; - case VBSyntax.BinaryExpressionSyntax binaryExpression: - if (binaryExpression.Right == invocation) continue; - else return false; - case VBSyntax.VariableDeclaratorSyntax declarator when IsInLocalDeclarationWithMultipleDeclarators(declarator, out var declarators): - if (declarators.Last() == declarator) continue; - else return false; - case VBSyntax.IfStatementSyntax _: - case VBSyntax.ElseIfStatementSyntax _: - case VBSyntax.SingleLineIfStatementSyntax _: - case VBSyntax.SelectStatementSyntax _: - case VBSyntax.CaseStatementSyntax _: - case VBSyntax.ForStatementSyntax _: - case VBSyntax.ForEachStatementSyntax _: - case VBSyntax.UsingStatementSyntax _: - case VBSyntax.SyncLockStatementSyntax _: - case VBSyntax.WithStatementSyntax _: - case VBSyntax.CatchStatementSyntax _: - return false; - case VBSyntax.ExpressionSyntax _: - case VBSyntax.StatementSyntax _: - return true; - } - } - } - - - /// - /// VB evaluates each declarator of Dim a = F(p.X), b = F(p.X) in turn, writing back before the next one starts, - /// but temporaries and write-backs are hoisted around the whole converted declaration. - /// A Static local's declarators become fields, where a local function couldn't be called, so those keep the old placement. - /// - private static bool IsInLocalDeclarationWithMultipleDeclarators(VBSyntax.VariableDeclaratorSyntax declarator, out SeparatedSyntaxList declarators) - { - declarators = declarator.Parent is VBSyntax.LocalDeclarationStatementSyntax localDeclaration && - !localDeclaration.Modifiers.Any(m => m.IsKind(VBasic.SyntaxKind.StaticKeyword)) - ? localDeclaration.Declarators - : default; - return declarators.Count > 1; - } - /// /// The pre-expansion phase should handle this for compiling nodes. /// This is mainly targeted at dealing with missing semantic info. @@ -780,12 +579,12 @@ private async Task AddEmptyArgumentListIfImplicitAsync(SyntaxN { if (_semanticModel.SyntaxTree != node.SyntaxTree) return id; var operation = _semanticModel.GetOperation(node); - if (IsLoopCondition(node) && operation is IInvocationOperation implicitInvocation && + if (WriteBackPlacement.IsLoopCondition(node) && operation is IInvocationOperation implicitInvocation && implicitInvocation.TargetMethod.Parameters.Any(p => p.RefKind != RefKind.None)) { _typeContext.PerScopeState.PushScope(); try { var call = SyntaxFactory.InvocationExpression(id, _argumentConverter.CreateArgList(implicitInvocation.TargetMethod)); - return await HoistAndCallLocalFunctionAsync((VBasic.VisualBasicSyntaxNode)node, implicitInvocation.TargetMethod, call); + return await _writeBackPlacement.HoistAndCallLocalFunctionAsync((VBasic.VisualBasicSyntaxNode)node, implicitInvocation.TargetMethod, call); } finally { _typeContext.PerScopeState.PopExpressionScope(); } diff --git a/CodeConverter/CSharp/README.md b/CodeConverter/CSharp/README.md index dd2f5254d..5873bc336 100644 --- a/CodeConverter/CSharp/README.md +++ b/CodeConverter/CSharp/README.md @@ -1,37 +1,4 @@ # VB → C# conversion -## ByRef arguments that need a temporary - -Sources: [passing arguments by value and by reference](https://learn.microsoft.com/dotnet/visual-basic/programming-guide/language-features/procedures/passing-arguments-by-value-and-by-reference) and Roslyn's VB lowering in [`LocalRewriter_Call.vb`](https://github.com/dotnet/roslyn/blob/main/src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_Call.vb): `RewriteByRefArgumentWithCopyBack` creates the temporary, and `VisitCall` wraps the call in a sequence whose side effects after the value are the copy-backs. Behaviour below is covered by `Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb`. - -### VB - -* A ByRef parameter accepts any expression. If it isn't a variable (a property, a method result, a constant, an omitted `Optional` argument), VB passes a temporary. -* For a writable property (or a `ReadOnly` auto-property inside its constructor), VB copies the temporary back **straight after the call returns**, before the rest of the enclosing expression or statement runs. -* One call copies back its arguments from the last to the first (`copyBackArray.ReverseContents()` in `LocalRewriter_Call.vb`). It's observable when two arguments write back to the same place, e.g. `Two(p.Value, p.Value)`. A call nested in an argument has already copied back by then. - -### C# - -* `ref`/`out` need a variable, so the temporary must be declared in a statement before the call. -* There is no expression-level copy-back, so a write-back is a statement too. - -### Implementation - -`ArgumentConverter.HoistByRefDeclaration` hoists the temporary (`AdditionalDeclaration`) and, when VB copies back, the write-back (`AdditionalAssignment`) into the current `PerScopeState` scope. `PerScopeState.CreateLocalsAsync` emits them before and after the converted statement. The output takes the simplest form that keeps VB's timing: - -| Where the call is | C# | Code | -|---|---|---| -| A statement, as the last thing evaluated, including the right of an assignment whose target isn't read by the write-back (`Q = F(P)`) | temporary before, write-back after the statement | `PerScopeState.CreateLocalsAsync` | -| `Return`, `Throw`, `Yield` | `var ret = call; write-back; return ret;` (only when there is a write-back) | `PerScopeState.WithWriteBacksBefore` | -| Followed by other evaluation, or in a condition or block header (`If`, `ElseIf`, loops, `Select Case`, `Case`, `For`, `For Each`, `Using`, `SyncLock`, `With`, `Catch When`), or in one of multiple `Dim` declarators, or the right of an assignment to something the write-back reads (`P = F(P)`, `x = F(h.Items(x))`, `h = F(h.P)`): C# evaluates the assignment target first and stores last, as VB does, and the write-back happens in between | a local function that declares, calls and writes back, called in place | `NameExpressionNodeVisitor.RequiresLocalFunction`, `HoistAndCallLocalFunctionAsync` | -| A field initializer | a method that declares, writes back and returns, called from the field (static) or the constructor (instance) | `CommonConversions.WithHoistedNodesInMethodAsync`, `PerScopeState.CreateReturnBlockAsync` | - -Within each of these, one call's write-backs are hoisted after its whole argument list, last argument first, so a nested call's come before them: `ArgumentConverter.WithWriteBacksInVbOrderAsync`. - -Known gaps: -* Arguments of `New` (object creation) in a block header still write back after the block. -* A non-constant `For ... Step` is re-evaluated each iteration (not ByRef-specific). -* A lambda parameter inside a ByRef argument (`Function(x) Inc(x.P)`) hoists the local function outside the lambda, where `x` isn't in scope (CS0103). -* An auto-property initializer (`Public Property X As Integer = Inc(P)`) leaves a `ph…` placeholder (CS0103): it doesn't go through the field initializer path. -* Partial-class instance initializers run in part order rather than declaration order. -* A `ReadOnly` auto-property is assignable in its type's constructor and initializers, so VB writes it back there, but `GetRefConversionForExpression` treats every read-only property as not writable. A fix also needs the C# write-back target to be assignable from the field initializer method. +* ByRef arguments that need a temporary, and where their write-backs go: [ByRefArguments/README.md](ByRefArguments/README.md) +* Query expressions: [Queries/README.md](Queries/README.md) From 92e89b188b130b0f23237b55d0351089ce7be03e Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 21:52:30 +0000 Subject: [PATCH 18/25] Remove the byte order mark added to NameExpressionNodeVisitor.cs The extraction commit wrote the file back with a BOM it didn't have. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- CodeConverter/CSharp/NameExpressionNodeVisitor.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CodeConverter/CSharp/NameExpressionNodeVisitor.cs b/CodeConverter/CSharp/NameExpressionNodeVisitor.cs index 75ce07eab..d9f3ad3e8 100644 --- a/CodeConverter/CSharp/NameExpressionNodeVisitor.cs +++ b/CodeConverter/CSharp/NameExpressionNodeVisitor.cs @@ -1,4 +1,4 @@ -using System.Data; +using System.Data; using System.Globalization; using ICSharpCode.CodeConverter.CSharp.ByRefArguments; using ICSharpCode.CodeConverter.CSharp.Queries; From 47b99efc0c64d54d415118224a4613e6c5824601 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 21:58:22 +0000 Subject: [PATCH 19/25] Name a local function's result so it can't hide a name in use 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 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- .../CSharp/ByRefArguments/WriteBackPlacement.cs | 3 ++- .../VBToCS/ByRefWriteBackPlacementTests.vb | 11 +++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs b/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs index 5229088bf..912bb73b0 100644 --- a/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs +++ b/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs @@ -32,7 +32,8 @@ public WriteBackPlacement(SemanticModel semanticModel, HashSet generated /// public async Task HoistAndCallLocalFunctionAsync(VBasic.VisualBasicSyntaxNode invocation, IMethodSymbol invocationSymbol, ExpressionSyntax csExpression) { - const string retVariableName = "ret"; + // Each local function is its own scope, so only names visible at the call can clash, e.g. a parameter used in the argument + var retVariableName = NameGenerator.CS.GetUniqueVariableNameInScope(_semanticModel, new HashSet(), invocation, "ret"); var localFuncName = $"local{invocationSymbol.Name}"; var callAndStoreResult = CommonConversions.CreateLocalVariableDeclarationAndAssignment(retVariableName, csExpression); diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb index 9c6adb6a9..e40e28573 100644 --- a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb @@ -497,6 +497,17 @@ Public Class ByRefWriteBackPlacementTests Return New Holder End Function + + Public Sub LocalFunctionResultAvoidsANameInScope() + Dim probe As New Probe + Assert.Equal(2, AddOne(probe)) + Assert.Equal(1, probe.Stored) + End Sub + + Private Shared Function AddOne(ret As Probe) As Integer + Return Increment(ret.Value) + 1 + End Function + Private Shared Function Increment(ByRef value As Integer) As Integer value += 1 Return value From 81f4e510fecd623e2d971bd620e26de074d21a76 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 22:03:58 +0000 Subject: [PATCH 20/25] Assign through a result local when a simple target is written back `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 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- CodeConverter/CSharp/ByRefArguments/README.md | 3 +- .../ByRefArguments/WriteBackPlacement.cs | 32 ++++++++++++++++--- .../MethodBodyExecutableStatementVisitor.cs | 10 ++++-- Tests/CSharp/ExpressionTests/ByRefTests.cs | 20 ++++++++---- .../VBToCS/ByRefWriteBackPlacementTests.vb | 20 ++++++++++++ 5 files changed, 71 insertions(+), 14 deletions(-) diff --git a/CodeConverter/CSharp/ByRefArguments/README.md b/CodeConverter/CSharp/ByRefArguments/README.md index 69c1ff30b..1892d581c 100644 --- a/CodeConverter/CSharp/ByRefArguments/README.md +++ b/CodeConverter/CSharp/ByRefArguments/README.md @@ -20,8 +20,9 @@ Sources: [passing arguments by value and by reference](https://learn.microsoft.c | Where the call is | C# | Code | |---|---|---| | A statement, as the last thing evaluated, including the right of an assignment whose target isn't read by the write-back (`Q = F(P)`) | temporary before, write-back after the statement | `PerScopeState.CreateLocalsAsync` | +| `=` to a plain name or `Me.X` that the write-back reads (`P = F(P)`, `x = F(h.Items(x))`, `h = F(h.P)`) | `var ret = call; write-back; P = ret;` | `WriteBackPlacement.IsSimpleTargetReadByWriteBack`, `MethodBodyExecutableStatementVisitor.VisitAssignmentStatement` | | `Return`, `Throw`, `Yield` | `var ret = call; write-back; return ret;` (only when there is a write-back) | `PerScopeState.WithWriteBacksBefore` | -| Followed by other evaluation, or in a condition or block header (`If`, `ElseIf`, loops, `Select Case`, `Case`, `For`, `For Each`, `Using`, `SyncLock`, `With`, `Catch When`), or in one of multiple `Dim` declarators, or the right of an assignment to something the write-back reads (`P = F(P)`, `x = F(h.Items(x))`, `h = F(h.P)`): C# evaluates the assignment target first and stores last, as VB does, and the write-back happens in between | a local function that declares, calls and writes back, called in place | `WriteBackPlacement.RequiresLocalFunction`, `HoistAndCallLocalFunctionAsync` | +| Followed by other evaluation, or in a condition or block header (`If`, `ElseIf`, loops, `Select Case`, `Case`, `For`, `For Each`, `Using`, `SyncLock`, `With`, `Catch When`), or in one of multiple `Dim` declarators, or the right of a compound assignment, or one whose target has a receiver or index, that the write-back reads (`h.P = F(h.P)`, `x += F(h.Items(x))`): C# evaluates the target first and stores last, as VB does, and the write-back happens in between | a local function that declares, calls and writes back, called in place | `WriteBackPlacement.RequiresLocalFunction`, `HoistAndCallLocalFunctionAsync` | | A field initializer | a method that declares, writes back and returns, called from the field (static) or the constructor (instance) | `CommonConversions.WithHoistedNodesInMethodAsync`, `PerScopeState.CreateReturnBlockAsync` | Within each of these, one call's write-backs are hoisted after its whole argument list, last argument first, so a nested call's come before them: `ByRefArgumentHoister.WithWriteBacksInVbOrderAsync`. diff --git a/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs b/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs index 912bb73b0..e42a9adb4 100644 --- a/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs +++ b/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs @@ -105,17 +105,41 @@ bool RequiresLocalFunction(RefConversion possibleInline, VBSyntax.InvocationExpr /// VB writes back straight after the call, before the enclosing assignment stores its result. /// A write-back emitted after the assignment statement would overwrite the assigned target (h.P = F(h.P)), /// or write to a different place if the assignment changes something the write-back target reads (x = F(h.Items(x)), h = F(h.P)). - /// Other assignments keep the write-back after the statement. + /// A simple target is handled by the statement instead (see ), so only a compound assignment + /// or a target with a receiver or index to evaluate first needs the local function. /// private bool AssignmentChangesWhatIsWrittenBack(VBSyntax.InvocationExpressionSyntax invocation, IMethodSymbol invocationSymbol) { if (invocation.Ancestors().FirstOrDefault(n => n is VBSyntax.StatementSyntax or VBSyntax.LambdaExpressionSyntax) is not VBSyntax.AssignmentStatementSyntax assignment || - !assignment.Right.Span.Contains(invocation.Span)) { + !assignment.Right.Span.Contains(invocation.Span) || IsSimpleTarget(assignment)) { return false; } - var assignedSymbol = _semanticModel.GetSymbolInfo(assignment.Left).Symbol ?? - (assignment.Left is VBSyntax.InvocationExpressionSyntax { Expression: var indexed } ? _semanticModel.GetSymbolInfo(indexed).Symbol : null); + return WritesBackSomethingReading(invocation, invocationSymbol, GetAssignedSymbol(assignment)); + } + + /// + /// For P = F(P) or x = F(h.Items(x)), where the target has nothing to evaluate before the call, + /// var ret = F(...); write-backs; P = ret; keeps VB's order without a local function (which couldn't use this in a struct). + /// + public bool IsSimpleTargetReadByWriteBack(VBSyntax.AssignmentStatementSyntax assignment) + { + if (!IsSimpleTarget(assignment)) return false; + var assignedSymbol = GetAssignedSymbol(assignment); + return assignment.Right.DescendantNodesAndSelf(n => n is not VBSyntax.LambdaExpressionSyntax).OfType() + .Any(i => i.ArgumentList != null && _semanticModel.GetSymbolInfo(i).Symbol is IMethodSymbol method && WritesBackSomethingReading(i, method, assignedSymbol)); + } + + private static bool IsSimpleTarget(VBSyntax.AssignmentStatementSyntax assignment) => + assignment.IsKind(VBasic.SyntaxKind.SimpleAssignmentStatement) && + assignment.Left.SkipIntoParens() is VBSyntax.IdentifierNameSyntax or VBSyntax.MemberAccessExpressionSyntax { Expression: VBSyntax.MeExpressionSyntax or VBSyntax.MyClassExpressionSyntax }; + + private ISymbol GetAssignedSymbol(VBSyntax.AssignmentStatementSyntax assignment) => + _semanticModel.GetSymbolInfo(assignment.Left).Symbol ?? + (assignment.Left is VBSyntax.InvocationExpressionSyntax { Expression: var indexed } ? _semanticModel.GetSymbolInfo(indexed).Symbol : null); + + private bool WritesBackSomethingReading(VBSyntax.InvocationExpressionSyntax invocation, IMethodSymbol invocationSymbol, ISymbol assignedSymbol) + { var writtenBackExpressions = invocation.ArgumentList.Arguments.OfType() .Where(a => CommonConversions.GetRefConversionType(a, invocation.ArgumentList, invocationSymbol.Parameters, out _, out _) == RefConversion.PreAndPostAssignment) .Select(a => a.Expression); diff --git a/CodeConverter/CSharp/MethodBodyExecutableStatementVisitor.cs b/CodeConverter/CSharp/MethodBodyExecutableStatementVisitor.cs index d8818142c..2f29cd63b 100644 --- a/CodeConverter/CSharp/MethodBodyExecutableStatementVisitor.cs +++ b/CodeConverter/CSharp/MethodBodyExecutableStatementVisitor.cs @@ -6,6 +6,7 @@ using static Microsoft.CodeAnalysis.VisualBasic.VisualBasicExtensions; using SyntaxFactory = Microsoft.CodeAnalysis.CSharp.SyntaxFactory; using Microsoft.CodeAnalysis.Text; +using ICSharpCode.CodeConverter.CSharp.ByRefArguments; using ICSharpCode.CodeConverter.Util.FromRoslyn; using ICSharpCode.CodeConverter.VB; using ComparisonKind = ICSharpCode.CodeConverter.CSharp.VisualBasicEqualityComparison.ComparisonKind; @@ -28,6 +29,7 @@ internal class MethodBodyExecutableStatementVisitor : VBasic.VisualBasicSyntaxVi private readonly HashSet _generatedNames = new(); private readonly HashSet _localsToInlineInLoop; private readonly PerScopeState _perScopeState; + private readonly WriteBackPlacement _writeBackPlacement; public bool IsIterator { get; set; } public IdentifierNameSyntax ReturnVariable { get; set; } @@ -64,6 +66,7 @@ private MethodBodyExecutableStatementVisitor(VisualBasicSyntaxNode methodNode, S _extraUsingDirectives = extraUsingDirectives; _handledEventsAnalysis = typeContext.HandledEventsAnalysis; _perScopeState = typeContext.PerScopeState; + _writeBackPlacement = new WriteBackPlacement(semanticModel, _generatedNames, typeContext, commonConversions); var byRefParameterVisitor = new PerScopeStateVisitorDecorator(this, _perScopeState, semanticModel, _generatedNames); CommentConvertingVisitor = new CommentConvertingMethodBodyVisitor(byRefParameterVisitor); _localsToInlineInLoop = localsToInlineInLoop; @@ -288,9 +291,12 @@ _methodNode is VBSyntax.MethodBlockSyntax mb && return SingleStatement(lhs); } - var assignment = SyntaxFactory.AssignmentExpression(kind, lhs, rhs); var postAssignment = GetPostAssignmentStatements(node); - return postAssignment.Insert(0, SyntaxFactory.ExpressionStatement(assignment)); + StatementSyntax AssignTo(ExpressionSyntax value) => SyntaxFactory.ExpressionStatement(SyntaxFactory.AssignmentExpression(kind, lhs, value)); + if (kind == SyntaxKind.SimpleAssignmentExpression && _writeBackPlacement.IsSimpleTargetReadByWriteBack(node)) { + return SyntaxFactory.List(_perScopeState.WithWriteBacksBefore(rhs, "ret", () => GetResultTypeSyntax(node.Right), AssignTo).Concat(postAssignment)); + } + return postAssignment.Insert(0, AssignTo(rhs)); } private async Task> ConvertMidAssignmentAsync(VBSyntax.AssignmentStatementSyntax node, VBSyntax.MidExpressionSyntax mes) diff --git a/Tests/CSharp/ExpressionTests/ByRefTests.cs b/Tests/CSharp/ExpressionTests/ByRefTests.cs index 763b32f44..79e071375 100644 --- a/Tests/CSharp/ExpressionTests/ByRefTests.cs +++ b/Tests/CSharp/ExpressionTests/ByRefTests.cs @@ -1385,6 +1385,7 @@ End Function Sub Assignments(h As C) P = F(P) + h.Q = F(h.Q) h = G(h.P) Q = F(P) End Sub @@ -1406,15 +1407,20 @@ public C G(ref string v) public void Assignments(C h) { - string localF() { string argv = P; var ret = F(ref argv); P = argv; return ret; } - - P = localF(); - C localG() { string argv1 = h.P; var ret = G(ref argv1); h.P = argv1; return ret; } - - h = localG(); string argv = P; - Q = F(ref argv); + var ret = F(ref argv); P = argv; + P = ret; + string localF() { string argv = h.Q; var ret = F(ref argv); h.Q = argv; return ret; } + + h.Q = localF(); + string argv1 = h.P; + var ret1 = G(ref argv1); + h.P = argv1; + h = ret1; + string argv2 = P; + Q = F(ref argv2); + P = argv2; } }"); } diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb index e40e28573..1f7922d72 100644 --- a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb @@ -508,6 +508,26 @@ Public Class ByRefWriteBackPlacementTests Return Increment(ret.Value) + 1 End Function + + Public Sub StructureAssignmentWritesBackBeforeAssigning() + Dim s As New Counter + s.Go() + Assert.Equal(5, s.P) + End Sub + + Private Structure Counter + Public Property P As Integer + + Public Sub Go() + P = SetToTwoReturnFive(P) + End Sub + End Structure + + Private Shared Function SetToTwoReturnFive(ByRef value As Integer) As Integer + value = 2 + Return 5 + End Function + Private Shared Function Increment(ByRef value As Integer) As Integer value += 1 Return value From d1d42263c5f56fc18e71475bf58df5770532ad77 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 22:11:52 +0000 Subject: [PATCH 21/25] Keep statement placement in a struct where a local function needs this 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 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- CodeConverter/CSharp/ByRefArguments/README.md | 1 + .../ByRefArguments/WriteBackPlacement.cs | 25 ++++++--- Tests/CSharp/ExpressionTests/ByRefTests.cs | 54 +++++++++++++++++++ 3 files changed, 73 insertions(+), 7 deletions(-) diff --git a/CodeConverter/CSharp/ByRefArguments/README.md b/CodeConverter/CSharp/ByRefArguments/README.md index 1892d581c..d85134332 100644 --- a/CodeConverter/CSharp/ByRefArguments/README.md +++ b/CodeConverter/CSharp/ByRefArguments/README.md @@ -30,6 +30,7 @@ Within each of these, one call's write-backs are hoisted after its whole argumen The classes in this folder hold the ByRef-specific decisions. The placement mechanics stay with the code they extend: the hoisted node types and `PerScopeState` (the hoisting for every feature), `MethodBodyExecutableStatementVisitor` (jumps) and `CommonConversions` (field initializers, whose method wraps any hoisted statement, not only ByRef ones). Known gaps: +* In a `Structure`, a local function can't use `this` (CS1673). So when the call uses an instance member, block headers, `Dim` declarators, and compound or receiver-target assignments keep writing back after the statement: the code compiles but the write-back is late. (`If`/`ElseIf` and loop conditions used local functions before this, so they still give CS1673 there.) * Arguments of `New` (object creation) in a block header still write back after the block. * A non-constant `For ... Step` is re-evaluated each iteration (not ByRef-specific). * A lambda parameter inside a ByRef argument (`Function(x) Inc(x.P)`) hoists the local function outside the lambda, where `x` isn't in scope (CS0103). diff --git a/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs b/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs index e42a9adb4..948436c69 100644 --- a/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs +++ b/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs @@ -84,8 +84,10 @@ invocation.Expression is VBSyntax.MemberAccessExpressionSyntax member && } if (invocation.ArgumentList == null) return false; - var definitelyExecutedAfterPrevious = DefinitelyExecutedAfterPreviousStatement(invocation); - var nextStatementDefinitelyExecuted = NextStatementDefinitelyExecutedAfter(invocation) && !AssignmentChangesWhatIsWrittenBack(invocation, invocationSymbol); + var localFunctionCanUseThis = !IsInStructAndUsesThis(invocation); + var definitelyExecutedAfterPrevious = DefinitelyExecutedAfterPreviousStatement(invocation, localFunctionCanUseThis); + var nextStatementDefinitelyExecuted = NextStatementDefinitelyExecutedAfter(invocation, localFunctionCanUseThis) && + !(localFunctionCanUseThis && AssignmentChangesWhatIsWrittenBack(invocation, invocationSymbol)); if (definitelyExecutedAfterPrevious && nextStatementDefinitelyExecuted) return false; var possibleInline = definitelyExecutedAfterPrevious ? RefConversion.PreAssigment : RefConversion.Inline; return invocation.ArgumentList.Arguments.Any(a => RequiresLocalFunction(possibleInline, invocation, invocationSymbol, a)); @@ -156,7 +158,15 @@ public static bool IsLoopCondition(SyntaxNode node) /// /// Conservative version of _semanticModel.AnalyzeControlFlow(invocation).ExitPoints to account for exceptions /// - private bool DefinitelyExecutedAfterPreviousStatement(VBSyntax.InvocationExpressionSyntax invocation) + /// + /// A local function in a struct can't use this (CS1673). Block headers, Dim declarators and assignments + /// then keep writing back after the statement, as before they used the local function: compiling but late, a known gap. + /// + private bool IsInStructAndUsesThis(VBSyntax.InvocationExpressionSyntax invocation) => + _semanticModel.GetEnclosingSymbol(invocation.SpanStart) is { IsStatic: false, ContainingType.TypeKind: TypeKind.Struct } && + _semanticModel.GetOperation(invocation)?.DescendantsAndSelf().OfType().Any() != false; + + private bool DefinitelyExecutedAfterPreviousStatement(VBSyntax.InvocationExpressionSyntax invocation, bool localFunctionCanUseThis) { SyntaxNode parent = invocation; while (true) { @@ -171,7 +181,7 @@ private bool DefinitelyExecutedAfterPreviousStatement(VBSyntax.InvocationExpress // Being the leftmost invocation of an unqualified method call ensures no other code is executed. Could add other cases here, such as a method call on a local variable name, or "this.". A method call on a property is not acceptable. if (argumentSyntax.Parent.Parent is VBSyntax.InvocationExpressionSyntax parentInvocation && parentInvocation.ArgumentList.Arguments.First() == argumentSyntax && FirstArgDefinitelyEvaluated(parentInvocation)) continue; else return false; - case VBSyntax.VariableDeclaratorSyntax declarator when IsInLocalDeclarationWithMultipleDeclarators(declarator, out var declarators): + case VBSyntax.VariableDeclaratorSyntax declarator when localFunctionCanUseThis && IsInLocalDeclarationWithMultipleDeclarators(declarator, out var declarators): if (declarators.First() == declarator) continue; else return false; case VBSyntax.ElseIfStatementSyntax _: @@ -206,7 +216,7 @@ private bool MayThrow(VBSyntax.ExpressionSyntax expression) /// A block's header statement is followed by its body, so a write-back placed after the converted block would run too late /// (or, for a later Case clause, run when the clause was never evaluated). /// - private static bool NextStatementDefinitelyExecutedAfter(VBSyntax.InvocationExpressionSyntax invocation) + private static bool NextStatementDefinitelyExecutedAfter(VBSyntax.InvocationExpressionSyntax invocation, bool localFunctionCanUseThis) { SyntaxNode parent = invocation; while (true) { @@ -217,12 +227,13 @@ private static bool NextStatementDefinitelyExecutedAfter(VBSyntax.InvocationExpr case VBSyntax.BinaryExpressionSyntax binaryExpression: if (binaryExpression.Right == invocation) continue; else return false; - case VBSyntax.VariableDeclaratorSyntax declarator when IsInLocalDeclarationWithMultipleDeclarators(declarator, out var declarators): + case VBSyntax.VariableDeclaratorSyntax declarator when localFunctionCanUseThis && IsInLocalDeclarationWithMultipleDeclarators(declarator, out var declarators): if (declarators.Last() == declarator) continue; else return false; case VBSyntax.IfStatementSyntax _: case VBSyntax.ElseIfStatementSyntax _: case VBSyntax.SingleLineIfStatementSyntax _: + return false; case VBSyntax.SelectStatementSyntax _: case VBSyntax.CaseStatementSyntax _: case VBSyntax.ForStatementSyntax _: @@ -231,7 +242,7 @@ private static bool NextStatementDefinitelyExecutedAfter(VBSyntax.InvocationExpr case VBSyntax.SyncLockStatementSyntax _: case VBSyntax.WithStatementSyntax _: case VBSyntax.CatchStatementSyntax _: - return false; + return !localFunctionCanUseThis; case VBSyntax.ExpressionSyntax _: case VBSyntax.StatementSyntax _: return true; diff --git a/Tests/CSharp/ExpressionTests/ByRefTests.cs b/Tests/CSharp/ExpressionTests/ByRefTests.cs index 79e071375..ff2c017bf 100644 --- a/Tests/CSharp/ExpressionTests/ByRefTests.cs +++ b/Tests/CSharp/ExpressionTests/ByRefTests.cs @@ -1424,4 +1424,58 @@ public void Assignments(C h) } }"); } + + [Fact] + public async Task StructureKeepsStatementPlacementWhereALocalFunctionWouldNeedThisAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Public Structure S + Public Property P As Integer + + Shared Function Inc(ByRef v As Integer) As Integer + v += 1 + Return v + End Function + + Sub M() + Select Case Inc(P) + Case 1 + Console.WriteLine(1) + End Select + Dim a = Inc(P), b = Inc(P) + P += Inc(P) + End Sub +End Structure", @"using System; + +public partial struct S +{ + public int P { get; set; } + + public static int Inc(ref int v) + { + v += 1; + return v; + } + + public void M() + { + int argv = P; + switch (Inc(ref argv)) + { + case 1: + Console.WriteLine(1); + break; + } + P = argv; + int argv1 = P; + int argv2 = P; + int a = Inc(ref argv1); + int b = Inc(ref argv2); + P = argv1; + P = argv2; + int argv3 = P; + P += Inc(ref argv3); + P = argv3; + } +}", incompatibleWithAutomatedCommentTesting: true); // The write-back after the block moves line comments out of order + } } \ No newline at end of file From a09e19970150f7cd1b0636acc8bffaf36d9e342b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 22:18:33 +0000 Subject: [PATCH 22/25] Treat a ByRef extension receiver like a written-back argument `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 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- .../ByRefArguments/WriteBackPlacement.cs | 18 ++++++++++--- .../VBToCS/ByRefWriteBackPlacementTests.vb | 25 ++++++++++++++++++- 2 files changed, 39 insertions(+), 4 deletions(-) diff --git a/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs b/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs index 948436c69..5766d1750 100644 --- a/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs +++ b/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs @@ -86,9 +86,10 @@ invocation.Expression is VBSyntax.MemberAccessExpressionSyntax member && if (invocation.ArgumentList == null) return false; var localFunctionCanUseThis = !IsInStructAndUsesThis(invocation); var definitelyExecutedAfterPrevious = DefinitelyExecutedAfterPreviousStatement(invocation, localFunctionCanUseThis); - var nextStatementDefinitelyExecuted = NextStatementDefinitelyExecutedAfter(invocation, localFunctionCanUseThis) && - !(localFunctionCanUseThis && AssignmentChangesWhatIsWrittenBack(invocation, invocationSymbol)); + var assignmentChangesWhatIsWrittenBack = localFunctionCanUseThis && AssignmentChangesWhatIsWrittenBack(invocation, invocationSymbol); + var nextStatementDefinitelyExecuted = NextStatementDefinitelyExecutedAfter(invocation, localFunctionCanUseThis) && !assignmentChangesWhatIsWrittenBack; if (definitelyExecutedAfterPrevious && nextStatementDefinitelyExecuted) return false; + if (assignmentChangesWhatIsWrittenBack && GetWrittenBackReceiver(invocation, invocationSymbol) is not null) return true; var possibleInline = definitelyExecutedAfterPrevious ? RefConversion.PreAssigment : RefConversion.Inline; return invocation.ArgumentList.Arguments.Any(a => RequiresLocalFunction(possibleInline, invocation, invocationSymbol, a)); @@ -132,6 +133,16 @@ public bool IsSimpleTargetReadByWriteBack(VBSyntax.AssignmentStatementSyntax ass .Any(i => i.ArgumentList != null && _semanticModel.GetSymbolInfo(i).Symbol is IMethodSymbol method && WritesBackSomethingReading(i, method, assignedSymbol)); } + /// + /// The receiver of an extension method whose first parameter is ByRef, e.g. h.P in h.P.Ext(), is written back like an argument. + /// + private VBSyntax.ExpressionSyntax GetWrittenBackReceiver(VBSyntax.InvocationExpressionSyntax invocation, IMethodSymbol invocationSymbol) => + invocationSymbol.ReducedFrom?.Parameters.FirstOrDefault() is { RefKind: not RefKind.None } && + invocation.Expression is VBSyntax.MemberAccessExpressionSyntax { Expression: { } receiver } && + _semanticModel.GetRefConversionForExpression(receiver) == RefConversion.PreAndPostAssignment + ? receiver + : null; + private static bool IsSimpleTarget(VBSyntax.AssignmentStatementSyntax assignment) => assignment.IsKind(VBasic.SyntaxKind.SimpleAssignmentStatement) && assignment.Left.SkipIntoParens() is VBSyntax.IdentifierNameSyntax or VBSyntax.MemberAccessExpressionSyntax { Expression: VBSyntax.MeExpressionSyntax or VBSyntax.MyClassExpressionSyntax }; @@ -144,7 +155,8 @@ private bool WritesBackSomethingReading(VBSyntax.InvocationExpressionSyntax invo { var writtenBackExpressions = invocation.ArgumentList.Arguments.OfType() .Where(a => CommonConversions.GetRefConversionType(a, invocation.ArgumentList, invocationSymbol.Parameters, out _, out _) == RefConversion.PreAndPostAssignment) - .Select(a => a.Expression); + .Select(a => a.Expression) + .Concat(GetWrittenBackReceiver(invocation, invocationSymbol) is { } receiver ? new[] { receiver } : Array.Empty()); return writtenBackExpressions.Any(e => assignedSymbol is null || e.DescendantNodesAndSelf().OfType().Any(n => SymbolEqualityComparer.Default.Equals(_semanticModel.GetSymbolInfo(n).Symbol, assignedSymbol))); } diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb index 1f7922d72..f7c825cfd 100644 --- a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb @@ -1,5 +1,6 @@ Imports System Imports System.Collections.Generic +Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices Imports Xunit @@ -477,9 +478,23 @@ Public Class ByRefWriteBackPlacementTests Assert.Equal("get,get,set,set", probe.LogText) End Sub - Private Class Holder + + Public Sub AssignmentToTheWrittenBackExtensionReceiverKeepsTheCallResult() + Dim h As New Holder + h.Plain = h.Plain.SetToChangedReturnResult() + Assert.Equal("result", h.Plain) + h.Plain = "" + h.AssignOwnPlain() + Assert.Equal("result", h.Plain) + End Sub + + Public Class Holder Public Property Plain As String = "" Public Property Items As New List(Of String) From {"a", "b"} + + Public Sub AssignOwnPlain() + Plain = Plain.SetToChangedReturnResult() + End Sub End Class Private Shared Function SetValueReturnOther(ByRef value As String) As String @@ -561,3 +576,11 @@ Public Class ByRefWriteBackPlacementTests End Property End Class End Class + +Public Module ByRefWriteBackPlacementExtensions + + Public Function SetToChangedReturnResult(ByRef value As String) As String + value = "changed" + Return "result" + End Function +End Module From a2a214d7ddf3e61bba24d61308de369d14a43886 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 22:18:47 +0000 Subject: [PATCH 23/25] Document further ByRef write-back gaps found in review 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 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- CodeConverter/CSharp/ByRefArguments/README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CodeConverter/CSharp/ByRefArguments/README.md b/CodeConverter/CSharp/ByRefArguments/README.md index d85134332..31b98e216 100644 --- a/CodeConverter/CSharp/ByRefArguments/README.md +++ b/CodeConverter/CSharp/ByRefArguments/README.md @@ -33,6 +33,12 @@ Known gaps: * In a `Structure`, a local function can't use `this` (CS1673). So when the call uses an instance member, block headers, `Dim` declarators, and compound or receiver-target assignments keep writing back after the statement: the code compiles but the write-back is late. (`If`/`ElseIf` and loop conditions used local functions before this, so they still give CS1673 there.) * Arguments of `New` (object creation) in a block header still write back after the block. * A non-constant `For ... Step` is re-evaluated each iteration (not ByRef-specific). +* An assignment is only seen to change what's written back when the same symbol appears in both, e.g. `h.P = F(h.P)`. So: + * `h1.P = F(h2.P)` where `h1 Is h2` still writes back after the assignment. + * `a.P = F(b.P)` takes the local function even when `a` and `b` are different objects, because two names can always refer to the same object. +* `WF = New W(WF.Name)`, a ByRef constructor argument in an assignment, writes back to the new object: object creation doesn't take the assignment placement. +* The write-back re-evaluates the target's receiver, so `F(GetH(h).P)` calls `GetH` twice. Hoisting the receiver into a temporary is left to the parameterized-property work (#909), which adds that for its own targets. +* A setter with side effects on the written-back target, e.g. `Other = F(P)` where `Other`'s setter writes `P`, runs before the write-back instead of after it. * A lambda parameter inside a ByRef argument (`Function(x) Inc(x.P)`) hoists the local function outside the lambda, where `x` isn't in scope (CS0103). * An auto-property initializer (`Public Property X As Integer = Inc(P)`) leaves a `ph…` placeholder (CS0103): it doesn't go through the field initializer path. * Partial-class instance initializers run in part order rather than declaration order. From d22baa0d4e5906ff25144ea956cace428b045652 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 23:33:30 +0000 Subject: [PATCH 24/25] Never move a struct call that uses this into a local function 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 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- CodeConverter/CSharp/ByRefArguments/README.md | 2 +- .../ByRefArguments/WriteBackPlacement.cs | 22 +++++---- Tests/CSharp/ExpressionTests/ByRefTests.cs | 45 +++++++++++++++++++ 3 files changed, 56 insertions(+), 13 deletions(-) diff --git a/CodeConverter/CSharp/ByRefArguments/README.md b/CodeConverter/CSharp/ByRefArguments/README.md index 31b98e216..e5567face 100644 --- a/CodeConverter/CSharp/ByRefArguments/README.md +++ b/CodeConverter/CSharp/ByRefArguments/README.md @@ -30,7 +30,7 @@ Within each of these, one call's write-backs are hoisted after its whole argumen The classes in this folder hold the ByRef-specific decisions. The placement mechanics stay with the code they extend: the hoisted node types and `PerScopeState` (the hoisting for every feature), `MethodBodyExecutableStatementVisitor` (jumps) and `CommonConversions` (field initializers, whose method wraps any hoisted statement, not only ByRef ones). Known gaps: -* In a `Structure`, a local function can't use `this` (CS1673). So when the call uses an instance member, block headers, `Dim` declarators, and compound or receiver-target assignments keep writing back after the statement: the code compiles but the write-back is late. (`If`/`ElseIf` and loop conditions used local functions before this, so they still give CS1673 there.) +* In a `Structure`, a local function can't use `this` (CS1673). So when the call uses an instance member, every case that would use the local function instead writes back after the statement. That covers operands, conditions, block headers, `Dim` declarators, and compound or receiver-target assignments. The code compiles, but the write-back is late. Loop conditions still use a local function there and give CS1673, because writing back once would be wrong in a different way. * Arguments of `New` (object creation) in a block header still write back after the block. * A non-constant `For ... Step` is re-evaluated each iteration (not ByRef-specific). * An assignment is only seen to change what's written back when the same symbol appears in both, e.g. `h.P = F(h.P)`. So: diff --git a/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs b/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs index 5766d1750..982457c1a 100644 --- a/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs +++ b/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs @@ -84,10 +84,10 @@ invocation.Expression is VBSyntax.MemberAccessExpressionSyntax member && } if (invocation.ArgumentList == null) return false; - var localFunctionCanUseThis = !IsInStructAndUsesThis(invocation); - var definitelyExecutedAfterPrevious = DefinitelyExecutedAfterPreviousStatement(invocation, localFunctionCanUseThis); - var assignmentChangesWhatIsWrittenBack = localFunctionCanUseThis && AssignmentChangesWhatIsWrittenBack(invocation, invocationSymbol); - var nextStatementDefinitelyExecuted = NextStatementDefinitelyExecutedAfter(invocation, localFunctionCanUseThis) && !assignmentChangesWhatIsWrittenBack; + if (IsInStructAndUsesThis(invocation)) return false; + var definitelyExecutedAfterPrevious = DefinitelyExecutedAfterPreviousStatement(invocation); + var assignmentChangesWhatIsWrittenBack = AssignmentChangesWhatIsWrittenBack(invocation, invocationSymbol); + var nextStatementDefinitelyExecuted = NextStatementDefinitelyExecutedAfter(invocation) && !assignmentChangesWhatIsWrittenBack; if (definitelyExecutedAfterPrevious && nextStatementDefinitelyExecuted) return false; if (assignmentChangesWhatIsWrittenBack && GetWrittenBackReceiver(invocation, invocationSymbol) is not null) return true; var possibleInline = definitelyExecutedAfterPrevious ? RefConversion.PreAssigment : RefConversion.Inline; @@ -171,14 +171,13 @@ public static bool IsLoopCondition(SyntaxNode node) /// Conservative version of _semanticModel.AnalyzeControlFlow(invocation).ExitPoints to account for exceptions /// /// - /// A local function in a struct can't use this (CS1673). Block headers, Dim declarators and assignments - /// then keep writing back after the statement, as before they used the local function: compiling but late, a known gap. + /// A local function in a struct can't use this (CS1673), so there the write-back stays after the statement: compiling but late, a known gap. /// private bool IsInStructAndUsesThis(VBSyntax.InvocationExpressionSyntax invocation) => _semanticModel.GetEnclosingSymbol(invocation.SpanStart) is { IsStatic: false, ContainingType.TypeKind: TypeKind.Struct } && _semanticModel.GetOperation(invocation)?.DescendantsAndSelf().OfType().Any() != false; - private bool DefinitelyExecutedAfterPreviousStatement(VBSyntax.InvocationExpressionSyntax invocation, bool localFunctionCanUseThis) + private bool DefinitelyExecutedAfterPreviousStatement(VBSyntax.InvocationExpressionSyntax invocation) { SyntaxNode parent = invocation; while (true) { @@ -193,7 +192,7 @@ private bool DefinitelyExecutedAfterPreviousStatement(VBSyntax.InvocationExpress // Being the leftmost invocation of an unqualified method call ensures no other code is executed. Could add other cases here, such as a method call on a local variable name, or "this.". A method call on a property is not acceptable. if (argumentSyntax.Parent.Parent is VBSyntax.InvocationExpressionSyntax parentInvocation && parentInvocation.ArgumentList.Arguments.First() == argumentSyntax && FirstArgDefinitelyEvaluated(parentInvocation)) continue; else return false; - case VBSyntax.VariableDeclaratorSyntax declarator when localFunctionCanUseThis && IsInLocalDeclarationWithMultipleDeclarators(declarator, out var declarators): + case VBSyntax.VariableDeclaratorSyntax declarator when IsInLocalDeclarationWithMultipleDeclarators(declarator, out var declarators): if (declarators.First() == declarator) continue; else return false; case VBSyntax.ElseIfStatementSyntax _: @@ -228,7 +227,7 @@ private bool MayThrow(VBSyntax.ExpressionSyntax expression) /// A block's header statement is followed by its body, so a write-back placed after the converted block would run too late /// (or, for a later Case clause, run when the clause was never evaluated). /// - private static bool NextStatementDefinitelyExecutedAfter(VBSyntax.InvocationExpressionSyntax invocation, bool localFunctionCanUseThis) + private static bool NextStatementDefinitelyExecutedAfter(VBSyntax.InvocationExpressionSyntax invocation) { SyntaxNode parent = invocation; while (true) { @@ -239,13 +238,12 @@ private static bool NextStatementDefinitelyExecutedAfter(VBSyntax.InvocationExpr case VBSyntax.BinaryExpressionSyntax binaryExpression: if (binaryExpression.Right == invocation) continue; else return false; - case VBSyntax.VariableDeclaratorSyntax declarator when localFunctionCanUseThis && IsInLocalDeclarationWithMultipleDeclarators(declarator, out var declarators): + case VBSyntax.VariableDeclaratorSyntax declarator when IsInLocalDeclarationWithMultipleDeclarators(declarator, out var declarators): if (declarators.Last() == declarator) continue; else return false; case VBSyntax.IfStatementSyntax _: case VBSyntax.ElseIfStatementSyntax _: case VBSyntax.SingleLineIfStatementSyntax _: - return false; case VBSyntax.SelectStatementSyntax _: case VBSyntax.CaseStatementSyntax _: case VBSyntax.ForStatementSyntax _: @@ -254,7 +252,7 @@ private static bool NextStatementDefinitelyExecutedAfter(VBSyntax.InvocationExpr case VBSyntax.SyncLockStatementSyntax _: case VBSyntax.WithStatementSyntax _: case VBSyntax.CatchStatementSyntax _: - return !localFunctionCanUseThis; + return false; case VBSyntax.ExpressionSyntax _: case VBSyntax.StatementSyntax _: return true; diff --git a/Tests/CSharp/ExpressionTests/ByRefTests.cs b/Tests/CSharp/ExpressionTests/ByRefTests.cs index ff2c017bf..6aca648f2 100644 --- a/Tests/CSharp/ExpressionTests/ByRefTests.cs +++ b/Tests/CSharp/ExpressionTests/ByRefTests.cs @@ -1478,4 +1478,49 @@ public void M() } }", incompatibleWithAutomatedCommentTesting: true); // The write-back after the block moves line comments out of order } + + [Fact] + public async Task StructureKeepsStatementPlacementForOperandsThatWouldNeedThisAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Public Structure S + Public Property P As Integer + + Shared Function Inc(ByRef v As Integer) As Integer + v += 1 + Return v + End Function + + Sub M() + Me.P = Inc(Me.P) + 1 + Dim x = 1 + Inc(P) + P = Inc(Inc(P)) + End Sub +End Structure", @" +public partial struct S +{ + public int P { get; set; } + + public static int Inc(ref int v) + { + v += 1; + return v; + } + + public void M() + { + int argv = P; + var ret = Inc(ref argv) + 1; + P = argv; + P = ret; + int argv1 = P; + int x = 1 + Inc(ref argv1); + P = argv1; + int argv2 = P; + int argv3 = Inc(ref argv2); + var ret1 = Inc(ref argv3); + P = argv2; + P = ret1; + } +}"); + } } \ No newline at end of file From c8c3931a5a494e4fcd240f7a810a1bf922171bda Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 23:36:43 +0000 Subject: [PATCH 25/25] Cover the remaining write-back placement branches with tests 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 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- Tests/CSharp/ExpressionTests/ByRefTests.cs | 34 ++++++++++++++ .../VBToCS/ByRefWriteBackPlacementTests.vb | 45 +++++++++++++++++++ 2 files changed, 79 insertions(+) diff --git a/Tests/CSharp/ExpressionTests/ByRefTests.cs b/Tests/CSharp/ExpressionTests/ByRefTests.cs index 6aca648f2..d1437fa1c 100644 --- a/Tests/CSharp/ExpressionTests/ByRefTests.cs +++ b/Tests/CSharp/ExpressionTests/ByRefTests.cs @@ -1523,4 +1523,38 @@ public void M() } }"); } + + [Fact] + public async Task LateBoundAssignmentTargetTakesTheLocalFunctionAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Option Strict Off + +Public Class C + Public Property P As Integer + + Shared Function Inc(ByRef v As Integer) As Integer + v += 1 + Return v + End Function + + Sub M(o As Object) + o.X = Inc(P) + End Sub +End Class", @" +public partial class C +{ + public int P { get; set; } + + public static int Inc(ref int v) + { + v += 1; + return v; + } + + public void M(object o) + { + int localInc() { int argv = P; var ret = Inc(ref argv); P = argv; return ret; } ((dynamic)o).X = localInc(); + } +}", incompatibleWithAutomatedCommentTesting: true); // The late-bound assignment is emitted on the local function's line + } } \ No newline at end of file diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb index f7c825cfd..f4a5112f5 100644 --- a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb @@ -543,6 +543,45 @@ Public Class ByRefWriteBackPlacementTests Return 5 End Function + + Public Sub ParenthesizedCallAssignedToTheWrittenBackPropertyKeepsTheCallResult() + Dim h As New Holder + h.Plain = (SetValueReturnOther(h.Plain)) + Assert.Equal("result", h.Plain) + End Sub + + + Public Sub LastDeclaratorWritesBackAfterTheDeclaration() + Dim probe As New Probe + Dim a = Increment(probe.Value), b = Increment(probe.Value) + Assert.Equal(1, a) + Assert.Equal(2, b) + Assert.Equal(2, probe.Stored) + End Sub + + + Public Sub MidAssignmentToTheWrittenBackProperty() + Dim h As New Holder With {.Plain = "abcdef"} + Mid(h.Plain, 1) = SetValueReturnZZ(h.Plain) + Assert.Equal("ZZcdef", h.Plain) + End Sub + + Private Shared Function SetValueReturnZZ(ByRef value As String) As String + value = "changed" + Return "ZZ" + End Function + + + Public Sub ExtensionReceiverInLoopConditionWritesBackEachTime() + Dim h As New Holder + Dim count = 0 + Do While h.Plain.GrowIsShort() + count += 1 + Loop + Assert.Equal(2, count) + Assert.Equal("xxx", h.Plain) + End Sub + Private Shared Function Increment(ByRef value As Integer) As Integer value += 1 Return value @@ -583,4 +622,10 @@ Public Module ByRefWriteBackPlacementExtensions value = "changed" Return "result" End Function + + + Public Function GrowIsShort(ByRef value As String) As Boolean + value &= "x" + Return value.Length < 3 + End Function End Module