From a116487543de4b6bcabdc42b4d6e04a41ac9d843 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 19:02:40 +0000 Subject: [PATCH 01/56] Build a local function's arguments and parameters in shared lists A pure refactor so the next commit can add a parameter before the captured ByRef parameters, and generate another name that can't clash with the result's. IsInStructAndUsesThis now takes any VB node, as HoistAndCallLocalFunctionAsync does, and a duplicated summary is dropped. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- .../ByRefArguments/WriteBackPlacement.cs | 21 ++++++++----------- 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs b/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs index 982457c1a..af9b115e2 100644 --- a/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs +++ b/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs @@ -33,7 +33,8 @@ public WriteBackPlacement(SemanticModel semanticModel, HashSet generated public async Task HoistAndCallLocalFunctionAsync(VBasic.VisualBasicSyntaxNode invocation, IMethodSymbol invocationSymbol, ExpressionSyntax csExpression) { // 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 namesInLocalFunction = new HashSet(); + var retVariableName = NameGenerator.CS.GetUniqueVariableNameInScope(_semanticModel, namesInLocalFunction, invocation, "ret"); var localFuncName = $"local{invocationSymbol.Name}"; var callAndStoreResult = CommonConversions.CreateLocalVariableDeclarationAndAssignment(retVariableName, csExpression); @@ -45,28 +46,27 @@ public async Task HoistAndCallLocalFunctionAsync(VBa ); var returnType = CommonConversions.GetTypeSyntax(invocationSymbol.ReturnType); + var arguments = new List(); + var parameters = new List(); // 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); + AddArgumentsAndParameters(refParametersOfParent); - var localFunc = _typeContext.PerScopeState.Hoist(new HoistedFunction(localFuncName, returnType, block, SyntaxFactory.ParameterList(@params))); - return SyntaxFactory.InvocationExpression(localFunc.TempIdentifier, SyntaxFactory.ArgumentList(args)); + var localFunc = _typeContext.PerScopeState.Hoist(new HoistedFunction(localFuncName, returnType, block, SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(parameters)))); + return SyntaxFactory.InvocationExpression(localFunc.TempIdentifier, SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(arguments))); - (SeparatedSyntaxList, SeparatedSyntaxList) CreateArgumentsAndParametersLists(List parameterSymbols) + void AddArgumentsAndParameters(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)); } } @@ -167,13 +167,10 @@ public static bool IsLoopCondition(SyntaxNode node) return containingStatement is VBSyntax.WhileStatementSyntax or VBSyntax.DoStatementSyntax or VBSyntax.LoopStatementSyntax; } - /// - /// Conservative version of _semanticModel.AnalyzeControlFlow(invocation).ExitPoints to account for exceptions - /// /// /// 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) => + private bool IsInStructAndUsesThis(VBasic.VisualBasicSyntaxNode invocation) => _semanticModel.GetEnclosingSymbol(invocation.SpanStart) is { IsStatic: false, ContainingType.TypeKind: TypeKind.Struct } && _semanticModel.GetOperation(invocation)?.DescendantsAndSelf().OfType().Any() != false; From 482b2b937fe6e690935340bd57064c00e8879378 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 19:08:02 +0000 Subject: [PATCH 02/56] Pass this by ref to a struct's write-back local function In a Structure, a local function can't use `this` (CS1673). Where a ByRef write-back needed one (operands, If/ElseIf and loop conditions, block headers, Dim declarators, compound or receiver-target assignments) and the call used an instance member, the write-back was moved after the statement instead: compiling, but late. Loop conditions still used the local function and gave CS1673. The local function now takes `ref S self`, is called with `ref this`, and its body uses `self` for `this`. The converted body qualifies every instance member with `this` (including generic and extension calls), so replacing `this` covers them; nested local functions get `ref self`. C# allows `ref this` wherever VB allows `Me` in a structure: methods, accessors, constructors, iterators and async methods. Its only illegal context, a readonly member (CS1605), can't come from VB, and VB doesn't allow `Me` in a structure's lambdas (BC36638), so no case is left that needs a conversion error. The two struct conversion tests pinned the late write-back; their expectations now pin the local function, which self-verifying tests show has VB's timing. They're renamed, since they no longer keep the statement placement. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- CodeConverter/CSharp/ByRefArguments/README.md | 3 +- .../ByRefArguments/WriteBackPlacement.cs | 15 +- Tests/CSharp/ExpressionTests/ByRefTests.cs | 167 +++++++++++--- .../VBToCS/ByRefWriteBackPlacementTests.vb | 208 ++++++++++++++++++ 4 files changed, 363 insertions(+), 30 deletions(-) diff --git a/CodeConverter/CSharp/ByRefArguments/README.md b/CodeConverter/CSharp/ByRefArguments/README.md index e5567face..a60923621 100644 --- a/CodeConverter/CSharp/ByRefArguments/README.md +++ b/CodeConverter/CSharp/ByRefArguments/README.md @@ -27,10 +27,11 @@ Sources: [passing arguments by value and by reference](https://learn.microsoft.c 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`. +In a `Structure`, a local function can't use `this` (CS1673). When the call uses an instance member, the local function takes `ref S self` and is called with `ref this`, and its body uses `self` for `this` (the converted body always qualifies instance members, which are only simplified later). `ref this` is legal wherever VB can use `Me` in a structure; VB has no read-only members (where it's CS1605) and no `Me` in a structure's lambdas (BC36638): `WriteBackPlacement.HoistAndCallLocalFunctionAsync`. + 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, 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 af9b115e2..d8fa83f66 100644 --- a/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs +++ b/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs @@ -48,6 +48,15 @@ public async Task HoistAndCallLocalFunctionAsync(VBa var arguments = new List(); var parameters = new List(); + if (IsInStructAndUsesThis(invocation)) { + var selfName = NameGenerator.CS.GetUniqueVariableNameInScope(_semanticModel, namesInLocalFunction, invocation, "self"); + block = block.ReplaceNodes(block.DescendantNodes().OfType(), (_, _) => ValidSyntaxFactory.IdentifierName(selfName)); + arguments.Add(SyntaxFactory.Argument(SyntaxFactory.ThisExpression()).WithRefKindKeyword(SyntaxFactory.Token(SyntaxKind.RefKeyword))); + parameters.Add(SyntaxFactory.Parameter(SyntaxFactory.Identifier(selfName)) + .WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.RefKeyword))) + .WithType(CommonConversions.GetTypeSyntax(_semanticModel.GetEnclosingSymbol(invocation.SpanStart).ContainingType))); + } + // 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() @@ -84,7 +93,6 @@ invocation.Expression is VBSyntax.MemberAccessExpressionSyntax member && } if (invocation.ArgumentList == null) return false; - if (IsInStructAndUsesThis(invocation)) return false; var definitelyExecutedAfterPrevious = DefinitelyExecutedAfterPreviousStatement(invocation); var assignmentChangesWhatIsWrittenBack = AssignmentChangesWhatIsWrittenBack(invocation, invocationSymbol); var nextStatementDefinitelyExecuted = NextStatementDefinitelyExecutedAfter(invocation) && !assignmentChangesWhatIsWrittenBack; @@ -168,7 +176,10 @@ public static bool IsLoopCondition(SyntaxNode node) } /// - /// 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. + /// A local function in a struct can't use this (CS1673), but it can take it as a ref parameter: local(ref this). + /// That's legal wherever VB can use Me in a structure: methods, property and event accessors, constructors (C# 11 structs are auto-default), + /// iterators and async methods (which work on a copy in both languages). VB has no read-only members, where ref this would be CS1605, + /// and doesn't allow Me in a lambda in a structure (BC36638), so the call is never inside one. /// private bool IsInStructAndUsesThis(VBasic.VisualBasicSyntaxNode invocation) => _semanticModel.GetEnclosingSymbol(invocation.SpanStart) is { IsStatic: false, ContainingType.TypeKind: TypeKind.Struct } && diff --git a/Tests/CSharp/ExpressionTests/ByRefTests.cs b/Tests/CSharp/ExpressionTests/ByRefTests.cs index d1437fa1c..390fc2649 100644 --- a/Tests/CSharp/ExpressionTests/ByRefTests.cs +++ b/Tests/CSharp/ExpressionTests/ByRefTests.cs @@ -1426,7 +1426,7 @@ public void Assignments(C h) } [Fact] - public async Task StructureKeepsStatementPlacementWhereALocalFunctionWouldNeedThisAsync() + public async Task StructureBlockHeaderDeclaratorAndCompoundAssignmentPassThisToTheLocalFunctionAsync() { await TestConversionVisualBasicToCSharpAsync(@"Public Structure S Public Property P As Integer @@ -1458,29 +1458,29 @@ public static int Inc(ref int v) public void M() { - int argv = P; - switch (Inc(ref argv)) + int localInc(ref S self) { int argv = self.P; var ret = Inc(ref argv); self.P = argv; return ret; } + + switch (localInc(ref this)) { 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; + int localInc1(ref S self) { int argv1 = self.P; var ret = Inc(ref argv1); self.P = argv1; return ret; } + + int localInc2(ref S self) { int argv2 = self.P; var ret = Inc(ref argv2); self.P = argv2; return ret; } + + int a = localInc1(ref this); + int b = localInc2(ref this); + int localInc3(ref S self) { int argv3 = self.P; var ret = Inc(ref argv3); self.P = argv3; return ret; } + + P += localInc3(ref this); } -}", incompatibleWithAutomatedCommentTesting: true); // The write-back after the block moves line comments out of order +}"); } [Fact] - public async Task StructureKeepsStatementPlacementForOperandsThatWouldNeedThisAsync() + public async Task StructureOperandsPassThisToTheLocalFunctionAsync() { await TestConversionVisualBasicToCSharpAsync(@"Public Structure S Public Property P As Integer @@ -1508,18 +1508,16 @@ public static int Inc(ref int 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; + int localInc(ref S self) { int argv = self.P; var ret = Inc(ref argv); self.P = argv; return ret; } + + P = localInc(ref this) + 1; + int localInc1(ref S self) { int argv1 = self.P; var ret = Inc(ref argv1); self.P = argv1; return ret; } + + int x = 1 + localInc1(ref this); + int localInc2(ref S self) { int argv2 = self.P; var ret = Inc(ref argv2); self.P = argv2; return ret; } + + int argv = localInc2(ref this); + P = Inc(ref argv); } }"); } @@ -1557,4 +1555,119 @@ public void M(object o) } }", incompatibleWithAutomatedCommentTesting: true); // The late-bound assignment is emitted on the local function's line } + [Fact] + public async Task StructureConditionsPassThisToTheLocalFunctionAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Public Structure S + Public Shared Counter As Integer + Public Property P As Integer + Private F As Integer + + Shared Function Inc(ByRef v As Integer) As Integer + v += 1 + Return v + End Function + + Function InstanceInc(ByRef v As Integer) As Integer + v += F + Return v + End Function + + Sub New(start As Integer) + F = start + If Inc(P) > F Then P = 0 + End Sub + + ReadOnly Property Incremented As Integer + Get + If Inc(P) > 0 Then Return P + Return 0 + End Get + End Property + + Sub M(b As Boolean, self As Integer) + If b AndAlso Inc(P) > self Then + P = 0 + ElseIf InstanceInc(Me.P) > Inc(Inc(P)) Then + P = 1 + End If + While Inc(P) < 10 + End While + Do + Loop Until InstanceInc(P) > 20 + If Inc(Counter) > 0 Then Counter = 0 + End Sub +End Structure", @" +public partial struct S +{ + public static int Counter; + public int P { get; set; } + private int F; + + public static int Inc(ref int v) + { + v += 1; + return v; + } + + public int InstanceInc(ref int v) + { + v += F; + return v; + } + + public S(int start) + { + F = start; + int localInc(ref S self) { int argv = self.P; var ret = Inc(ref argv); self.P = argv; return ret; } + + if (localInc(ref this) > F) + P = 0; + } + + public int Incremented + { + get + { + int localInc(ref S self) { int argv1 = self.P; var ret = Inc(ref argv1); self.P = argv1; return ret; } + + if (localInc(ref this) > 0) + return P; + return 0; + } + } + + public void M(bool b, int self) + { + int localInc(ref S self1) { int argv2 = self1.P; var ret = Inc(ref argv2); self1.P = argv2; return ret; } + int localInstanceInc(ref S self1) { int argv3 = self1.P; var ret = self1.InstanceInc(ref argv3); self1.P = argv3; return ret; } + + int localInc1(ref S self1) { int argv4 = self1.P; var ret = Inc(ref argv4); self1.P = argv4; return ret; } + + int localInc2(ref S self1) { int argv5 = localInc1(ref self1); var ret = Inc(ref argv5); return ret; } + + if (b && localInc(ref this) > self) + { + P = 0; + } + else if (localInstanceInc(ref this) > localInc2(ref this)) + { + P = 1; + } + int localInc3(ref S self1) { int argv6 = self1.P; var ret = Inc(ref argv6); self1.P = argv6; return ret; } + + while (localInc3(ref this) < 10) + { + } + int localInstanceInc1(ref S self1) { int argv7 = self1.P; var ret = self1.InstanceInc(ref argv7); self1.P = argv7; return ret; } + + do + { + } + while (localInstanceInc1(ref this) <= 20); + if (Inc(ref Counter) > 0) + Counter = 0; + } +}"); + } } \ No newline at end of file diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb index f4a5112f5..eebf06179 100644 --- a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb @@ -582,6 +582,214 @@ Public Class ByRefWriteBackPlacementTests Assert.Equal("xxx", h.Plain) End Sub + + Public Sub StructureIfConditionWritesBackBeforeTheBody() + Dim s As New LoggedValue(New List(Of String)) + s.IfCondition() + Assert.Equal("get 0,set 1,then 1", s.LogText) + End Sub + + + Public Sub StructureElseIfConditionWritesBackBeforeTheBody() + Dim s As New LoggedValue(New List(Of String)) + s.ElseIfCondition() + Assert.Equal("mark if,get 0,set 1,elseif 1", s.LogText) + End Sub + + + Public Sub StructureShortCircuitedOperandOnlyWritesBackWhenCalled() + Dim s As New LoggedValue(New List(Of String)) + s.ShortCircuitedOperand(False) + s.ShortCircuitedOperand(True) + Assert.Equal("mark left,mark left,get 0,set 1,then 1", s.LogText) + End Sub + + + Public Sub StructureWhileConditionWritesBackEachTime() + Dim s As New LoggedValue(New List(Of String)) + s.WhileCondition() + Assert.Equal("get 0,set 1,body 1,get 1,set 2,body 2,get 2,set 3", s.LogText) + End Sub + + + Public Sub StructureDoLoopUntilConditionWritesBackEachTime() + Dim s As New LoggedValue(New List(Of String)) + s.DoLoopUntilCondition() + Assert.Equal("body 0,get 0,set 1,body 1,get 1,set 2", s.LogText) + End Sub + + + Public Sub StructureOperandWritesBackBeforeTheNextOperand() + Dim s As New LoggedValue(New List(Of String)) + Assert.Equal(2, s.OperandFollowedByPeek()) + Assert.Equal("get 0,set 1,peek 1", s.LogText) + End Sub + + + Public Sub StructureDeclaratorWritesBackBeforeTheNext() + Dim s As New LoggedValue(New List(Of String)) + Assert.Equal(2, s.DeclaratorFollowedByPeek()) + Assert.Equal("get 0,set 1,peek 1", s.LogText) + End Sub + + + Public Sub StructureNestedCallsWriteBackInnerFirst() + Dim s As New LoggedValue(New List(Of String)) + s.NestedCalls() + Assert.Equal("get 0,get 0,set 1,set 0,then 0", s.LogText) + End Sub + + + Public Sub StructureInstanceMethodSeesItsOwnState() + Dim s As New LoggedValue(New List(Of String)) + s.InstanceMethodInCondition() + Assert.Equal("get 0,instance 0,set 1,then 1", s.LogText) + End Sub + + + Public Sub StructureConstructorConditionWritesBackBeforeTheBody() + Dim s As New LoggedValue(New List(Of String), True) + Assert.Equal("get 0,set 1,then 1", s.LogText) + End Sub + + + Public Sub StructurePropertyGetterConditionWritesBackBeforeTheBody() + Dim s As New LoggedValue(New List(Of String)) + Assert.Equal(1, s.IncrementedIfPositive) + Assert.Equal("get 0,set 1,get 1", s.LogText) + End Sub + + + Public Sub StructureSharedMemberConditionWritesBackBeforeTheBody() + LoggedValue.SharedValue = 0 + Assert.True(LoggedValue.SharedCondition()) + Assert.Equal(1, LoggedValue.SharedValue) + End Sub + + Private Structure LoggedValue + Public Shared SharedValue As Integer + Private ReadOnly _log As List(Of String) + Private _value As Integer + + Public Sub New(log As List(Of String)) + _log = log + End Sub + + Public Sub New(log As List(Of String), incrementInCondition As Boolean) + _log = log + If incrementInCondition AndAlso Increment(Value) > 0 Then + _log.Add("then " & _value) + End If + End Sub + + Public ReadOnly Property LogText As String + Get + Return String.Join(",", _log) + End Get + End Property + + Public Property Value As Integer + Get + _log.Add("get " & _value) + Return _value + End Get + Set(v As Integer) + _log.Add("set " & v) + _value = v + End Set + End Property + + Public ReadOnly Property IncrementedIfPositive As Integer + Get + If Increment(Value) > 0 Then + Return Value + End If + Return -1 + End Get + End Property + + Private Function Mark(name As String, result As Boolean) As Boolean + _log.Add("mark " & name) + Return result + End Function + + Private Function Peek() As Integer + _log.Add("peek " & _value) + Return _value + End Function + + Private Function IncrementLogged(ByRef v As Integer) As Integer + _log.Add("instance " & _value) + v += 1 + Return v + End Function + + Public Sub IfCondition() + If Increment(Value) > 0 Then + _log.Add("then " & _value) + End If + End Sub + + Public Sub ElseIfCondition() + If Mark("if", False) Then + _log.Add("if") + ElseIf Increment(Me.Value) > 0 Then + _log.Add("elseif " & _value) + End If + End Sub + + Public Sub ShortCircuitedOperand(callIt As Boolean) + If Mark("left", callIt) AndAlso Increment(Value) > 0 Then + _log.Add("then " & _value) + End If + End Sub + + Public Sub WhileCondition() + While Increment(Value) < 3 + _log.Add("body " & _value) + End While + End Sub + + Public Sub DoLoopUntilCondition() + Do + _log.Add("body " & _value) + Loop Until Increment(Value) >= 2 + End Sub + + Public Function OperandFollowedByPeek() As Integer + Return Increment(Value) + Peek() + End Function + + Public Function DeclaratorFollowedByPeek() As Integer + Dim a = Increment(Value), b = Peek() + Return a + b + End Function + + Public Sub NestedCalls() + If AddTo(Value, Increment(Value)) > 0 Then + _log.Add("then " & _value) + End If + End Sub + + Public Sub InstanceMethodInCondition() + If IncrementLogged(Value) > 0 Then + _log.Add("then " & _value) + End If + End Sub + + Public Shared Function SharedCondition() As Boolean + If Increment(SharedValue) > 0 Then + Return SharedValue = 1 + End If + Return False + End Function + End Structure + + Private Shared Function AddTo(ByRef target As Integer, amount As Integer) As Integer + target = 0 + Return amount + End Function + Private Shared Function Increment(ByRef value As Integer) As Integer value += 1 Return value From 55b4b4db10ccd2ce6c4a65dddd27df204c209efe Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 19:23:30 +0000 Subject: [PATCH 03/56] Look up a local function's enclosing symbol and operation once Pure refactor, from review. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- .../CSharp/ByRefArguments/WriteBackPlacement.cs | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs b/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs index d8fa83f66..4e3c9ffe6 100644 --- a/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs +++ b/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs @@ -46,20 +46,21 @@ public async Task HoistAndCallLocalFunctionAsync(VBa ); var returnType = CommonConversions.GetTypeSyntax(invocationSymbol.ReturnType); + var enclosingSymbol = _semanticModel.GetEnclosingSymbol(invocation.SpanStart); + var operation = _semanticModel.GetOperation(invocation); var arguments = new List(); var parameters = new List(); - if (IsInStructAndUsesThis(invocation)) { + if (IsInStructAndUsesThis(enclosingSymbol, operation)) { var selfName = NameGenerator.CS.GetUniqueVariableNameInScope(_semanticModel, namesInLocalFunction, invocation, "self"); block = block.ReplaceNodes(block.DescendantNodes().OfType(), (_, _) => ValidSyntaxFactory.IdentifierName(selfName)); arguments.Add(SyntaxFactory.Argument(SyntaxFactory.ThisExpression()).WithRefKindKeyword(SyntaxFactory.Token(SyntaxKind.RefKeyword))); parameters.Add(SyntaxFactory.Parameter(SyntaxFactory.Identifier(selfName)) .WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.RefKeyword))) - .WithType(CommonConversions.GetTypeSyntax(_semanticModel.GetEnclosingSymbol(invocation.SpanStart).ContainingType))); + .WithType(CommonConversions.GetTypeSyntax(enclosingSymbol.ContainingType))); } // 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() + var refParametersOfParent = (operation?.DescendantsAndSelf() .OfType().Select(p => p.Parameter) ?? Enumerable.Empty()) .Where(p => p.RefKind != RefKind.None && SymbolEqualityComparer.Default.Equals(p.ContainingSymbol, enclosingSymbol)) .Distinct(SymbolEqualityComparer.Default).ToList(); @@ -181,9 +182,9 @@ public static bool IsLoopCondition(SyntaxNode node) /// iterators and async methods (which work on a copy in both languages). VB has no read-only members, where ref this would be CS1605, /// and doesn't allow Me in a lambda in a structure (BC36638), so the call is never inside one. /// - private bool IsInStructAndUsesThis(VBasic.VisualBasicSyntaxNode invocation) => - _semanticModel.GetEnclosingSymbol(invocation.SpanStart) is { IsStatic: false, ContainingType.TypeKind: TypeKind.Struct } && - _semanticModel.GetOperation(invocation)?.DescendantsAndSelf().OfType().Any() != false; + private static bool IsInStructAndUsesThis(ISymbol enclosingSymbol, IOperation operation) => + enclosingSymbol is { IsStatic: false, ContainingType.TypeKind: TypeKind.Struct } && + operation?.DescendantsAndSelf().OfType().Any() != false; private bool DefinitelyExecutedAfterPreviousStatement(VBSyntax.InvocationExpressionSyntax invocation) { From 7a2e55289947ebb81908ef744ee5a793cf9e2cc5 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 19:24:54 +0000 Subject: [PATCH 04/56] Only pass this to a struct's local function when it uses this A With block's implicit receiver is an IInstanceReferenceOperation too, so a call on a local's members inside With in a Structure got an unused ref S self parameter. Only ContainingTypeInstance references count now. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- .../ByRefArguments/WriteBackPlacement.cs | 3 +- Tests/CSharp/ExpressionTests/ByRefTests.cs | 43 +++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs b/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs index 4e3c9ffe6..9ed3ab970 100644 --- a/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs +++ b/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs @@ -181,10 +181,11 @@ public static bool IsLoopCondition(SyntaxNode node) /// That's legal wherever VB can use Me in a structure: methods, property and event accessors, constructors (C# 11 structs are auto-default), /// iterators and async methods (which work on a copy in both languages). VB has no read-only members, where ref this would be CS1605, /// and doesn't allow Me in a lambda in a structure (BC36638), so the call is never inside one. + /// A With block's implicit receiver is also an instance reference, but not to this. /// private static bool IsInStructAndUsesThis(ISymbol enclosingSymbol, IOperation operation) => enclosingSymbol is { IsStatic: false, ContainingType.TypeKind: TypeKind.Struct } && - operation?.DescendantsAndSelf().OfType().Any() != false; + operation?.DescendantsAndSelf().OfType().Any(i => i.ReferenceKind == InstanceReferenceKind.ContainingTypeInstance) != false; private bool DefinitelyExecutedAfterPreviousStatement(VBSyntax.InvocationExpressionSyntax invocation) { diff --git a/Tests/CSharp/ExpressionTests/ByRefTests.cs b/Tests/CSharp/ExpressionTests/ByRefTests.cs index 390fc2649..d398ded1d 100644 --- a/Tests/CSharp/ExpressionTests/ByRefTests.cs +++ b/Tests/CSharp/ExpressionTests/ByRefTests.cs @@ -1668,6 +1668,49 @@ public void M(bool b, int self) if (Inc(ref Counter) > 0) Counter = 0; } +}"); + } + [Fact] + public async Task StructureWithBlockOnALocalDoesNotPassThisAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Public Class Box + Public Property X As Integer +End Class + +Public Structure S + Shared Function Inc(ByRef v As Integer) As Integer + v += 1 + Return v + End Function + + Sub M() + Dim b As New Box + With b + If Inc(.X) > 0 Then .X = 0 + End With + End Sub +End Structure", @" +public partial class Box +{ + public int X { get; set; } +} + +public partial struct S +{ + public static int Inc(ref int v) + { + v += 1; + return v; + } + + public void M() + { + var b = new Box(); + int localInc() { int argv = b.X; var ret = Inc(ref argv); b.X = argv; return ret; } + + if (localInc() > 0) + b.X = 0; + } }"); } } \ No newline at end of file From 74c5dedc419f3ce4e1fc7e835d17e87ffc76b168 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 19:29:15 +0000 Subject: [PATCH 05/56] Pass ref locals to a write-back local function by ref A local function can't use a ref local (CS8175). `With Inner`, where Inner is a structure field, declares `ref var withBlock = ref Inner;`, so a ByRef write-back in the block that took the local function didn't compile, in a class as well as (since the previous commits) in a Structure. References to a ref local made for a side-effect-free expression are now annotated with its type. The local function takes each one in its body as a ref parameter of the same name, as it already does for the enclosing method's ByRef parameters, and is called with `ref withBlock`. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- CodeConverter/CSharp/ByRefArguments/README.md | 2 + .../ByRefArguments/RefLocalReferences.cs | 23 ++++++ .../ByRefArguments/WriteBackPlacement.cs | 14 +++- .../MethodBodyExecutableStatementVisitor.cs | 1 + Tests/CSharp/ExpressionTests/ByRefTests.cs | 74 +++++++++++++++++++ .../VBToCS/ByRefWriteBackPlacementTests.vb | 33 +++++++++ 6 files changed, 144 insertions(+), 3 deletions(-) create mode 100644 CodeConverter/CSharp/ByRefArguments/RefLocalReferences.cs diff --git a/CodeConverter/CSharp/ByRefArguments/README.md b/CodeConverter/CSharp/ByRefArguments/README.md index a60923621..78e66c89e 100644 --- a/CodeConverter/CSharp/ByRefArguments/README.md +++ b/CodeConverter/CSharp/ByRefArguments/README.md @@ -29,6 +29,8 @@ Within each of these, one call's write-backs are hoisted after its whole argumen In a `Structure`, a local function can't use `this` (CS1673). When the call uses an instance member, the local function takes `ref S self` and is called with `ref this`, and its body uses `self` for `this` (the converted body always qualifies instance members, which are only simplified later). `ref this` is legal wherever VB can use `Me` in a structure; VB has no read-only members (where it's CS1605) and no `Me` in a structure's lambdas (BC36638): `WriteBackPlacement.HoistAndCallLocalFunctionAsync`. +A local function can't use a ref local either (CS8175), such as the `ref var withBlock` of a `With` over a structure field. References to a ref local are marked with its type, and the local function takes each one it uses as a `ref` parameter of the same name: `RefLocalReferences`. + 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: diff --git a/CodeConverter/CSharp/ByRefArguments/RefLocalReferences.cs b/CodeConverter/CSharp/ByRefArguments/RefLocalReferences.cs new file mode 100644 index 000000000..c31f78c41 --- /dev/null +++ b/CodeConverter/CSharp/ByRefArguments/RefLocalReferences.cs @@ -0,0 +1,23 @@ +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace ICSharpCode.CodeConverter.CSharp.ByRefArguments; + +/// +/// A local function can't use a ref local from its enclosing method (CS8175), e.g. the ref var withBlock of a With block over a structure field. +/// Each reference to a ref local is marked with the local's type, so that a local function can find the ones in its body and take them as ref parameters. +/// +internal static class RefLocalReferences +{ + private const string AnnotationKind = "CodeConverter.RefLocalReference"; + + public static IdentifierNameSyntax Mark(IdentifierNameSyntax reference, TypeSyntax refLocalType) => + reference.WithAdditionalAnnotations(new SyntaxAnnotation(AnnotationKind, refLocalType.ToString())); + + /// One marked reference per ref local used in , and the local's type + public static IEnumerable<(IdentifierNameSyntax Reference, TypeSyntax Type)> FindIn(SyntaxNode node) => + node.GetAnnotatedNodes(AnnotationKind).OfType() + .GroupBy(n => n.Identifier.ValueText) + .Select(g => g.First()) + .Select(n => (n, SyntaxFactory.ParseTypeName(n.GetAnnotations(AnnotationKind).First().Data))); +} diff --git a/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs b/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs index 9ed3ab970..5c376f799 100644 --- a/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs +++ b/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs @@ -54,9 +54,7 @@ public async Task HoistAndCallLocalFunctionAsync(VBa var selfName = NameGenerator.CS.GetUniqueVariableNameInScope(_semanticModel, namesInLocalFunction, invocation, "self"); block = block.ReplaceNodes(block.DescendantNodes().OfType(), (_, _) => ValidSyntaxFactory.IdentifierName(selfName)); arguments.Add(SyntaxFactory.Argument(SyntaxFactory.ThisExpression()).WithRefKindKeyword(SyntaxFactory.Token(SyntaxKind.RefKeyword))); - parameters.Add(SyntaxFactory.Parameter(SyntaxFactory.Identifier(selfName)) - .WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.RefKeyword))) - .WithType(CommonConversions.GetTypeSyntax(enclosingSymbol.ContainingType))); + parameters.Add(RefParameter(selfName, CommonConversions.GetTypeSyntax(enclosingSymbol.ContainingType))); } // Parent ByRef parameters cannot be captured, including references in receivers and nested argument expressions. @@ -66,9 +64,19 @@ public async Task HoistAndCallLocalFunctionAsync(VBa .Distinct(SymbolEqualityComparer.Default).ToList(); AddArgumentsAndParameters(refParametersOfParent); + foreach (var (reference, type) in RefLocalReferences.FindIn(block)) { + arguments.Add(SyntaxFactory.Argument(reference).WithRefKindKeyword(SyntaxFactory.Token(SyntaxKind.RefKeyword))); + parameters.Add(RefParameter(reference.Identifier.ValueText, type)); + } + var localFunc = _typeContext.PerScopeState.Hoist(new HoistedFunction(localFuncName, returnType, block, SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(parameters)))); return SyntaxFactory.InvocationExpression(localFunc.TempIdentifier, SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(arguments))); + static ParameterSyntax RefParameter(string name, TypeSyntax type) => + SyntaxFactory.Parameter(SyntaxFactory.Identifier(name)) + .WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.RefKeyword))) + .WithType(type); + void AddArgumentsAndParameters(List parameterSymbols) { foreach (var p in parameterSymbols) { diff --git a/CodeConverter/CSharp/MethodBodyExecutableStatementVisitor.cs b/CodeConverter/CSharp/MethodBodyExecutableStatementVisitor.cs index 2f29cd63b..577f78d56 100644 --- a/CodeConverter/CSharp/MethodBodyExecutableStatementVisitor.cs +++ b/CodeConverter/CSharp/MethodBodyExecutableStatementVisitor.cs @@ -1010,6 +1010,7 @@ private static CasePatternSwitchLabelSyntax VarWhen(SyntaxToken varName, Express } var (stmt, id) = CreateLocalVariableWithUniqueName(vbExpr, variableNameBase, expr, forceType); + if (forceType != null) id = RefLocalReferences.Mark(id, CommonConversions.GetTypeSyntax(_semanticModel.GetTypeInfo(vbExpr).Type)); stmts = stmts.Add(stmt); reusableExprWithoutSideEffects = exprWithoutSideEffects = id; } diff --git a/Tests/CSharp/ExpressionTests/ByRefTests.cs b/Tests/CSharp/ExpressionTests/ByRefTests.cs index d398ded1d..9209d04d2 100644 --- a/Tests/CSharp/ExpressionTests/ByRefTests.cs +++ b/Tests/CSharp/ExpressionTests/ByRefTests.cs @@ -1711,6 +1711,80 @@ public void M() if (localInc() > 0) b.X = 0; } +}"); + } + [Fact] + public async Task WithBlockRefLocalIsPassedToTheLocalFunctionAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Public Structure T + Public Property P As Integer +End Structure + +Public Class C + Public Inner As T + + Sub M() + With Inner + If S.Inc(.P) > 0 Then .P = 0 + End With + End Sub +End Class + +Public Structure S + Public Inner As T + + Shared Function Inc(ByRef v As Integer) As Integer + v += 1 + Return v + End Function + + Sub M() + With Inner + If Inc(.P) > 0 Then .P = 0 + End With + End Sub +End Structure", @" +public partial struct T +{ + public int P { get; set; } +} + +public partial class C +{ + public T Inner; + + public void M() + { + { + ref var withBlock = ref Inner; + int localInc(ref T withBlock) { int argv = withBlock.P; var ret = S.Inc(ref argv); withBlock.P = argv; return ret; } + + if (localInc(ref withBlock) > 0) + withBlock.P = 0; + } + } +} + +public partial struct S +{ + public T Inner; + + public static int Inc(ref int v) + { + v += 1; + return v; + } + + public void M() + { + { + ref var withBlock = ref Inner; + int localInc(ref T withBlock) { int argv1 = withBlock.P; var ret = Inc(ref argv1); withBlock.P = argv1; return ret; } + + if (localInc(ref withBlock) > 0) + withBlock.P = 0; + } + } }"); } } \ No newline at end of file diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb index eebf06179..b8a5c8c1b 100644 --- a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb @@ -666,10 +666,36 @@ Public Class ByRefWriteBackPlacementTests Assert.Equal(1, LoggedValue.SharedValue) End Sub + + Public Sub WithStructureFieldConditionWritesBackBeforeTheBody() + Dim h As New CounterHolder + Assert.Equal(1, h.IncrementInWith()) + Assert.Equal(1, h.Inner.P) + End Sub + + Private Class CounterHolder + Public Inner As Counter + + Public Function IncrementInWith() As Integer + With Inner + If Increment(.P) > 0 Then Return .P + End With + Return -1 + End Function + End Class + + + Public Sub StructureWithStructureFieldConditionWritesBackBeforeTheBody() + Dim s As New LoggedValue(New List(Of String)) + Assert.Equal(1, s.IncrementInnerInWith()) + Assert.Equal(1, s.Inner.P) + End Sub + Private Structure LoggedValue Public Shared SharedValue As Integer Private ReadOnly _log As List(Of String) Private _value As Integer + Public Inner As Counter Public Sub New(log As List(Of String)) _log = log @@ -777,6 +803,13 @@ Public Class ByRefWriteBackPlacementTests End If End Sub + Public Function IncrementInnerInWith() As Integer + With Inner + If Increment(.P) > 0 Then Return .P + End With + Return -1 + End Function + Public Shared Function SharedCondition() As Boolean If Increment(SharedValue) > 0 Then Return SharedValue = 1 From 66c9f04acbb8079e3d0b82535796e3609b5b7ed5 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 19:33:21 +0000 Subject: [PATCH 06/56] Copy a structure's Me at the call when it's passed ByRef VB passes a copy of a Structure's Me to a ByRef parameter, taken when the call evaluates its arguments. In `Return Inc(P) + ValueOf(Me)`, the copy (`var args = this;`) was hoisted before the statement, so it missed Inc's write-back: VB returned 2 and C# 1. The same happened after AndAlso. This existed before this PR. Me was never considered to need the local function, which is right for a class (its copy is the same reference whenever it's taken) but not for a structure. A structure's Me now takes the local function like any other temporary, so the copy is made in place (`var args = self;`). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- .../ByRefArguments/WriteBackPlacement.cs | 3 +- Tests/CSharp/ExpressionTests/ByRefTests.cs | 44 +++++++++++++++++++ .../VBToCS/ByRefWriteBackPlacementTests.vb | 24 ++++++++++ 3 files changed, 70 insertions(+), 1 deletion(-) diff --git a/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs b/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs index 5c376f799..fe5ff437f 100644 --- a/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs +++ b/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs @@ -116,7 +116,8 @@ bool RequiresLocalFunction(RefConversion possibleInline, VBSyntax.InvocationExpr 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; + // A copy of a class's Me is the same reference whenever it's taken, but a structure's Me is copied by value, so it must be taken at the call + if (argExpression is VBSyntax.InstanceExpressionSyntax) return _semanticModel.GetTypeInfo(argExpression).Type?.IsValueType == true; return !_semanticModel.GetConstantValue(argExpression).HasValue; } } diff --git a/Tests/CSharp/ExpressionTests/ByRefTests.cs b/Tests/CSharp/ExpressionTests/ByRefTests.cs index 9209d04d2..75cf91cd6 100644 --- a/Tests/CSharp/ExpressionTests/ByRefTests.cs +++ b/Tests/CSharp/ExpressionTests/ByRefTests.cs @@ -1785,6 +1785,50 @@ public void M() withBlock.P = 0; } } +}"); + } + [Fact] + public async Task StructureMePassedByRefAfterAWriteBackTakesTheLocalFunctionAsync() + { + 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 + + Shared Function ValueOf(ByRef s As S) As Integer + Return s.P + End Function + + Function M() As Integer + Return Inc(P) + ValueOf(Me) + End Function +End Structure", @" +public partial struct S +{ + public int P { get; set; } + + public static int Inc(ref int v) + { + v += 1; + return v; + } + + public static int ValueOf(ref S s) + { + return s.P; + } + + public int M() + { + int localInc(ref S self) { int argv = self.P; var ret = Inc(ref argv); self.P = argv; return ret; } + + int localValueOf(ref S self) { var args = self; var ret = ValueOf(ref args); return ret; } + + return localInc(ref this) + localValueOf(ref this); + } }"); } } \ No newline at end of file diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb index b8a5c8c1b..8e0bd0aeb 100644 --- a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb @@ -691,6 +691,18 @@ Public Class ByRefWriteBackPlacementTests Assert.Equal(1, s.Inner.P) End Sub + + Public Sub StructureMePassedByRefIsCopiedAfterAnEarlierWriteBack() + Dim s As New LoggedValue(New List(Of String)) + Assert.Equal(2, s.OperandThenMeByRef()) + End Sub + + + Public Sub StructureMePassedByRefAfterAndAlsoIsCopiedAfterAnEarlierWriteBack() + Dim s As New LoggedValue(New List(Of String)) + Assert.True(s.MeByRefAfterAndAlso()) + End Sub + Private Structure LoggedValue Public Shared SharedValue As Integer Private ReadOnly _log As List(Of String) @@ -810,6 +822,18 @@ Public Class ByRefWriteBackPlacementTests Return -1 End Function + Public Function OperandThenMeByRef() As Integer + Return Increment(Value) + ValueOf(Me) + End Function + + Public Function MeByRefAfterAndAlso() As Boolean + Return Increment(Value) > 0 AndAlso ValueOf(Me) = 1 + End Function + + Private Shared Function ValueOf(ByRef s As LoggedValue) As Integer + Return s._value + End Function + Public Shared Function SharedCondition() As Boolean If Increment(SharedValue) > 0 Then Return SharedValue = 1 From 44a635f0fda7efa6a531d78c0724eb2df86884da Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 19:33:33 +0000 Subject: [PATCH 07/56] Document further pre-existing ByRef gaps found in review Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- CodeConverter/CSharp/ByRefArguments/README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CodeConverter/CSharp/ByRefArguments/README.md b/CodeConverter/CSharp/ByRefArguments/README.md index 78e66c89e..af4a7dacc 100644 --- a/CodeConverter/CSharp/ByRefArguments/README.md +++ b/CodeConverter/CSharp/ByRefArguments/README.md @@ -45,4 +45,7 @@ Known gaps: * 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 parameterized property argument (`Inc(Item(0))`) writes back with `get_Item(0) = argv` (CS0131). The parameterized-property work (#909) handles these targets. +* A member of a structure returned by a property (`Inc(InnerProp.P)`) writes back with `InnerProp.P = argv`, which C# rejects because `InnerProp` returns a copy (CS1612). +* `Select Case Inc(P)` with `Case Inc(P)` gives `case var @case when ...` (CS0825). * 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 0b2cc995b693bfc6e8b4b557b588e765964fdab8 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 20:05:08 +0000 Subject: [PATCH 08/56] Pass this to a write-back local function inside With Me in a structure 7a2e552 counted only ContainingTypeInstance references, so the implicit receiver of With Me (which is this) no longer counted and the local function used this (CS1673). Decide from the converted body instead: it qualifies every instance member with this, so it contains a this exactly when the local function needs ref self. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- .../ByRefArguments/WriteBackPlacement.cs | 9 ++--- Tests/CSharp/ExpressionTests/ByRefTests.cs | 36 +++++++++++++++++++ .../VBToCS/ByRefWriteBackPlacementTests.vb | 13 +++++++ 3 files changed, 54 insertions(+), 4 deletions(-) diff --git a/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs b/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs index fe5ff437f..cd8d8afb7 100644 --- a/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs +++ b/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs @@ -50,7 +50,7 @@ public async Task HoistAndCallLocalFunctionAsync(VBa var operation = _semanticModel.GetOperation(invocation); var arguments = new List(); var parameters = new List(); - if (IsInStructAndUsesThis(enclosingSymbol, operation)) { + if (IsInStructAndUsesThis(enclosingSymbol, block)) { var selfName = NameGenerator.CS.GetUniqueVariableNameInScope(_semanticModel, namesInLocalFunction, invocation, "self"); block = block.ReplaceNodes(block.DescendantNodes().OfType(), (_, _) => ValidSyntaxFactory.IdentifierName(selfName)); arguments.Add(SyntaxFactory.Argument(SyntaxFactory.ThisExpression()).WithRefKindKeyword(SyntaxFactory.Token(SyntaxKind.RefKeyword))); @@ -190,11 +190,12 @@ public static bool IsLoopCondition(SyntaxNode node) /// That's legal wherever VB can use Me in a structure: methods, property and event accessors, constructors (C# 11 structs are auto-default), /// iterators and async methods (which work on a copy in both languages). VB has no read-only members, where ref this would be CS1605, /// and doesn't allow Me in a lambda in a structure (BC36638), so the call is never inside one. - /// A With block's implicit receiver is also an instance reference, but not to this. + /// The converted body qualifies every instance member with this (the simplifier removes it later), so it uses this exactly when it contains one. + /// Deciding from the VB operation instead would have to resolve a With block's implicit receiver, which is this only for With Me. /// - private static bool IsInStructAndUsesThis(ISymbol enclosingSymbol, IOperation operation) => + private static bool IsInStructAndUsesThis(ISymbol enclosingSymbol, BlockSyntax block) => enclosingSymbol is { IsStatic: false, ContainingType.TypeKind: TypeKind.Struct } && - operation?.DescendantsAndSelf().OfType().Any(i => i.ReferenceKind == InstanceReferenceKind.ContainingTypeInstance) != false; + block.DescendantNodes().OfType().Any(); private bool DefinitelyExecutedAfterPreviousStatement(VBSyntax.InvocationExpressionSyntax invocation) { diff --git a/Tests/CSharp/ExpressionTests/ByRefTests.cs b/Tests/CSharp/ExpressionTests/ByRefTests.cs index 75cf91cd6..cb5efea23 100644 --- a/Tests/CSharp/ExpressionTests/ByRefTests.cs +++ b/Tests/CSharp/ExpressionTests/ByRefTests.cs @@ -1711,6 +1711,42 @@ public void M() if (localInc() > 0) b.X = 0; } +}"); + } + [Fact] + public async Task StructureWithMePassesThisToTheLocalFunctionAsync() + { + 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() + With Me + If Inc(.P) > 0 Then .P = 0 + End With + 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 localInc(ref S self) { int argv = self.P; var ret = Inc(ref argv); self.P = argv; return ret; } + + if (localInc(ref this) > 0) + P = 0; + } }"); } [Fact] diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb index 8e0bd0aeb..01ae1cdcc 100644 --- a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb @@ -691,6 +691,12 @@ Public Class ByRefWriteBackPlacementTests Assert.Equal(1, s.Inner.P) End Sub + + Public Sub StructureWithMeConditionWritesBackBeforeTheBody() + Dim s As New LoggedValue(New List(Of String)) + s.IfConditionInWithMe() + Assert.Equal("get 0,set 1,then 1", s.LogText) + End Sub Public Sub StructureMePassedByRefIsCopiedAfterAnEarlierWriteBack() Dim s As New LoggedValue(New List(Of String)) @@ -822,6 +828,13 @@ Public Class ByRefWriteBackPlacementTests Return -1 End Function + Public Sub IfConditionInWithMe() + With Me + If Increment(.Value) > 0 Then + _log.Add("then " & _value) + End If + End With + End Sub Public Function OperandThenMeByRef() As Integer Return Increment(Value) + ValueOf(Me) End Function From e7629919aa461e64f828b975868b8de2b4d0bb3b Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 20:16:48 +0000 Subject: [PATCH 09/56] Don't pass a ref local declared inside the write-back local function 74c5ded passed every ref local the local function's body referenced, including a With block's withBlock declared inside a lambda argument, which doesn't exist at the call (CS0103). Skip names declared within the body: they're already in scope there. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- .../ByRefArguments/RefLocalReferences.cs | 12 +++- Tests/CSharp/ExpressionTests/ByRefTests.cs | 62 +++++++++++++++++++ .../VBToCS/ByRefWriteBackPlacementTests.vb | 21 +++++++ 3 files changed, 92 insertions(+), 3 deletions(-) diff --git a/CodeConverter/CSharp/ByRefArguments/RefLocalReferences.cs b/CodeConverter/CSharp/ByRefArguments/RefLocalReferences.cs index c31f78c41..bc996b1eb 100644 --- a/CodeConverter/CSharp/ByRefArguments/RefLocalReferences.cs +++ b/CodeConverter/CSharp/ByRefArguments/RefLocalReferences.cs @@ -14,10 +14,16 @@ internal static class RefLocalReferences public static IdentifierNameSyntax Mark(IdentifierNameSyntax reference, TypeSyntax refLocalType) => reference.WithAdditionalAnnotations(new SyntaxAnnotation(AnnotationKind, refLocalType.ToString())); - /// One marked reference per ref local used in , and the local's type - public static IEnumerable<(IdentifierNameSyntax Reference, TypeSyntax Type)> FindIn(SyntaxNode node) => - node.GetAnnotatedNodes(AnnotationKind).OfType() + /// One marked reference per ref local that uses from outside it, and the local's type. + /// A ref local declared inside, e.g. by a With block in a lambda argument, is in scope already. + /// Generated names are unique within a method, so a name declared inside can't also refer to one outside. + public static IEnumerable<(IdentifierNameSyntax Reference, TypeSyntax Type)> FindIn(SyntaxNode node) + { + var declaredInside = new HashSet(node.DescendantNodes().OfType().Select(v => v.Identifier.ValueText)); + return node.GetAnnotatedNodes(AnnotationKind).OfType() + .Where(n => !declaredInside.Contains(n.Identifier.ValueText)) .GroupBy(n => n.Identifier.ValueText) .Select(g => g.First()) .Select(n => (n, SyntaxFactory.ParseTypeName(n.GetAnnotations(AnnotationKind).First().Data))); + } } diff --git a/Tests/CSharp/ExpressionTests/ByRefTests.cs b/Tests/CSharp/ExpressionTests/ByRefTests.cs index cb5efea23..94f41b95b 100644 --- a/Tests/CSharp/ExpressionTests/ByRefTests.cs +++ b/Tests/CSharp/ExpressionTests/ByRefTests.cs @@ -1748,6 +1748,68 @@ public void M() P = 0; } }"); + } + [Fact] + public async Task RefLocalDeclaredInsideTheLocalFunctionIsNotPassedAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Public Structure T + Public Property P As Integer +End Structure + +Public Class C + Public Property Total As Integer + Public Inner As T + + Shared Function Apply(ByRef v As Integer, f As System.Func(Of Integer)) As Integer + Return v + f() + End Function + + Sub M() + If Apply(Total, Function() + With Inner + .P = 3 + End With + Return 1 + End Function) > 0 Then Total = 0 + End Sub +End Class", @"using System; + +public partial struct T +{ + public int P { get; set; } +} + +public partial class C +{ + public int Total { get; set; } + public T Inner; + + public static int Apply(ref int v, Func f) + { + return v + f(); + } + + public void M() + { + int localApply() + { + int argv = Total; + var ret = Apply(ref argv, () => + { + { + ref var withBlock = ref Inner; + withBlock.P = 3; + } + return 1; + }); + Total = argv; + return ret; + } + + if (localApply() > 0) + Total = 0; + } +}", incompatibleWithAutomatedCommentTesting: true); // The multi-line lambda is emitted inside the local function, before the If's line } [Fact] public async Task WithBlockRefLocalIsPassedToTheLocalFunctionAsync() diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb index 01ae1cdcc..89bd3ca26 100644 --- a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb @@ -673,8 +673,29 @@ Public Class ByRefWriteBackPlacementTests Assert.Equal(1, h.Inner.P) End Sub + + Public Sub WithInsideALambdaArgumentStaysInTheLambda() + Dim h As New CounterHolder + Assert.Equal(13, h.WithInLambdaArgument()) + End Sub Private Class CounterHolder Public Inner As Counter + Public Property Total As Integer + + Public Function WithInLambdaArgument() As Integer + If AddResult(Total, Function() + With Inner + .P = 3 + End With + Return 1 + End Function) > 0 Then Return Total * 10 + Inner.P + Return -1 + End Function + + Private Shared Function AddResult(ByRef target As Integer, f As Func(Of Integer)) As Integer + target += f() + Return target + End Function Public Function IncrementInWith() As Integer With Inner From 067bc7fa9addc44510b5fe993b3345a5a413fa95 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 20:26:10 +0000 Subject: [PATCH 10/56] Pass a ByRef parameter used as a With receiver to the local function With b, where b is a ByRef parameter, reuses b directly as the receiver, but the parameter reference is in the With header, so the local function didn't take it as a ref parameter and used it (CS1628). This existed before; the CS8175 fix for ref locals is its sibling. Resolve a With block's implicit receiver to the With expression's operations when collecting the enclosing method's ByRef parameters. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- CodeConverter/CSharp/ByRefArguments/README.md | 2 +- .../ByRefArguments/WriteBackPlacement.cs | 17 +++++- Tests/CSharp/ExpressionTests/ByRefTests.cs | 57 +++++++++++++++++++ .../VBToCS/ByRefWriteBackPlacementTests.vb | 17 ++++++ 4 files changed, 90 insertions(+), 3 deletions(-) diff --git a/CodeConverter/CSharp/ByRefArguments/README.md b/CodeConverter/CSharp/ByRefArguments/README.md index af4a7dacc..de6cf0937 100644 --- a/CodeConverter/CSharp/ByRefArguments/README.md +++ b/CodeConverter/CSharp/ByRefArguments/README.md @@ -29,7 +29,7 @@ Within each of these, one call's write-backs are hoisted after its whole argumen In a `Structure`, a local function can't use `this` (CS1673). When the call uses an instance member, the local function takes `ref S self` and is called with `ref this`, and its body uses `self` for `this` (the converted body always qualifies instance members, which are only simplified later). `ref this` is legal wherever VB can use `Me` in a structure; VB has no read-only members (where it's CS1605) and no `Me` in a structure's lambdas (BC36638): `WriteBackPlacement.HoistAndCallLocalFunctionAsync`. -A local function can't use a ref local either (CS8175), such as the `ref var withBlock` of a `With` over a structure field. References to a ref local are marked with its type, and the local function takes each one it uses as a `ref` parameter of the same name: `RefLocalReferences`. +A local function can't use a ref local either (CS8175), such as the `ref var withBlock` of a `With` over a structure field. References to a ref local are marked with its type, and the local function takes each one it uses from outside its body as a `ref` parameter of the same name: `RefLocalReferences`. The enclosing method's ByRef parameters are passed the same way (CS1628), including one reused directly as a `With` receiver (`With b : Inc(.X)` becomes `Inc(ref b.X)`): `WriteBackPlacement.DescendantsResolvingWithReceivers`. 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). diff --git a/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs b/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs index cd8d8afb7..f815be80e 100644 --- a/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs +++ b/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs @@ -57,8 +57,8 @@ public async Task HoistAndCallLocalFunctionAsync(VBa parameters.Add(RefParameter(selfName, CommonConversions.GetTypeSyntax(enclosingSymbol.ContainingType))); } - // Parent ByRef parameters cannot be captured, including references in receivers and nested argument expressions. - var refParametersOfParent = (operation?.DescendantsAndSelf() + // Parent ByRef parameters cannot be captured, including references in receivers, With receivers and nested argument expressions. + var refParametersOfParent = (operation is null ? null : DescendantsResolvingWithReceivers(operation) .OfType().Select(p => p.Parameter) ?? Enumerable.Empty()) .Where(p => p.RefKind != RefKind.None && SymbolEqualityComparer.Default.Equals(p.ContainingSymbol, enclosingSymbol)) .Distinct(SymbolEqualityComparer.Default).ToList(); @@ -88,6 +88,19 @@ void AddArgumentsAndParameters(List parameterSymbols) } } + /// + /// The operations within , where a With block's implicit receiver is replaced by the operations of the With expression. + /// The converter reuses a With expression such as a ByRef parameter directly as the receiver (With b : Inc(.X) becomes Inc(ref b.X)), + /// so the local function uses whatever that expression uses. + /// + private IEnumerable DescendantsResolvingWithReceivers(IOperation operation) => + operation.DescendantsAndSelf().SelectMany(o => + o is IInstanceReferenceOperation { ReferenceKind: InstanceReferenceKind.ImplicitReceiver } && + o.Syntax is VBSyntax.ExpressionSyntax { Parent: VBSyntax.WithStatementSyntax } withExpression && + _semanticModel.GetOperation(withExpression) is { } withOperation + ? DescendantsResolvingWithReceivers(withOperation) + : new[] { o }); + public bool RequiresLocalFunction(VBSyntax.InvocationExpressionSyntax invocation, IMethodSymbol invocationSymbol) { if (IsLoopCondition(invocation)) { diff --git a/Tests/CSharp/ExpressionTests/ByRefTests.cs b/Tests/CSharp/ExpressionTests/ByRefTests.cs index 94f41b95b..944bb75d7 100644 --- a/Tests/CSharp/ExpressionTests/ByRefTests.cs +++ b/Tests/CSharp/ExpressionTests/ByRefTests.cs @@ -1810,6 +1810,63 @@ int localApply() Total = 0; } }", incompatibleWithAutomatedCommentTesting: true); // The multi-line lambda is emitted inside the local function, before the If's line + } + [Fact] + public async Task WithByRefParameterIsPassedToTheLocalFunctionAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Public Structure T + Public Property P As Integer +End Structure + +Public Class Box + Public Property X As Integer +End Class + +Public Class C + Shared Function Inc(ByRef v As Integer) As Integer + v += 1 + Return v + End Function + + Sub M(ByRef b As Box, ByRef p As T) + With b + If Inc(.X) > 0 Then .X = 0 + End With + With p + If Inc(.P) > 0 Then .P = 0 + End With + End Sub +End Class", @" +public partial struct T +{ + public int P { get; set; } +} + +public partial class Box +{ + public int X { get; set; } +} + +public partial class C +{ + public static int Inc(ref int v) + { + v += 1; + return v; + } + + public void M(ref Box b, ref T p) + { + int localInc(ref Box b) { int argv = b.X; var ret = Inc(ref argv); b.X = argv; return ret; } + + if (localInc(ref b) > 0) + b.X = 0; + int localInc1(ref T p) { int argv1 = p.P; var ret = Inc(ref argv1); p.P = argv1; return ret; } + + if (localInc1(ref p) > 0) + p.P = 0; + } +}"); } [Fact] public async Task WithBlockRefLocalIsPassedToTheLocalFunctionAsync() diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb index 89bd3ca26..9cef412bd 100644 --- a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb @@ -678,10 +678,27 @@ Public Class ByRefWriteBackPlacementTests Dim h As New CounterHolder Assert.Equal(13, h.WithInLambdaArgument()) End Sub + + Public Sub WithByRefParameterConditionWritesBackBeforeTheBody() + Dim h As New CounterHolder + Dim c As New Counter + Assert.Equal(11, CounterHolder.IncrementInWithByRefParameters(h, c)) + Assert.Equal(1, c.P) + End Sub Private Class CounterHolder Public Inner As Counter Public Property Total As Integer + Public Shared Function IncrementInWithByRefParameters(ByRef holder As CounterHolder, ByRef counter As Counter) As Integer + Dim result = 0 + With holder + If Increment(.Total) > 0 Then result = .Total * 10 + End With + With counter + If Increment(.P) > 0 Then result += .P + End With + Return result + End Function Public Function WithInLambdaArgument() As Integer If AddResult(Total, Function() With Inner From 1f19e57399ef05db034547188d3610e0e46b19ac Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 20:29:01 +0000 Subject: [PATCH 11/56] Keep a ref local's TypeSyntax instead of reparsing it Pure refactor. An annotation's data can only be a string, so the type was stored as text and parsed again. The annotation instance stays on every copy of the node, so key the type by it instead. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- .../CSharp/ByRefArguments/RefLocalReferences.cs | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/CodeConverter/CSharp/ByRefArguments/RefLocalReferences.cs b/CodeConverter/CSharp/ByRefArguments/RefLocalReferences.cs index bc996b1eb..0c8e396cc 100644 --- a/CodeConverter/CSharp/ByRefArguments/RefLocalReferences.cs +++ b/CodeConverter/CSharp/ByRefArguments/RefLocalReferences.cs @@ -1,4 +1,4 @@ -using Microsoft.CodeAnalysis.CSharp; +using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace ICSharpCode.CodeConverter.CSharp.ByRefArguments; @@ -11,8 +11,15 @@ internal static class RefLocalReferences { private const string AnnotationKind = "CodeConverter.RefLocalReference"; - public static IdentifierNameSyntax Mark(IdentifierNameSyntax reference, TypeSyntax refLocalType) => - reference.WithAdditionalAnnotations(new SyntaxAnnotation(AnnotationKind, refLocalType.ToString())); + /// An annotation's data can only be a string, but the annotation itself is kept on every copy of the node, so it can key the type. + private static readonly ConditionalWeakTable RefLocalTypes = new(); + + public static IdentifierNameSyntax Mark(IdentifierNameSyntax reference, TypeSyntax refLocalType) + { + var annotation = new SyntaxAnnotation(AnnotationKind); + RefLocalTypes.Add(annotation, refLocalType); + return reference.WithAdditionalAnnotations(annotation); + } /// One marked reference per ref local that uses from outside it, and the local's type. /// A ref local declared inside, e.g. by a With block in a lambda argument, is in scope already. @@ -24,6 +31,6 @@ public static IdentifierNameSyntax Mark(IdentifierNameSyntax reference, TypeSynt .Where(n => !declaredInside.Contains(n.Identifier.ValueText)) .GroupBy(n => n.Identifier.ValueText) .Select(g => g.First()) - .Select(n => (n, SyntaxFactory.ParseTypeName(n.GetAnnotations(AnnotationKind).First().Data))); + .Select(n => (n, RefLocalTypes.TryGetValue(n.GetAnnotations(AnnotationKind).First(), out var type) ? type : null)); } } From 6330662c19cf6d6eecfb05d496516fb075e10393 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 00:22:46 +0000 Subject: [PATCH 12/56] Extract adding a parameterized property setter's value argument Pure refactor, so the ByRef write-back for #909 can build the same setter call. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- CodeConverter/CSharp/CommonConversions.cs | 16 ++++++++++++++++ .../CSharp/NameExpressionNodeVisitor.cs | 11 +---------- 2 files changed, 17 insertions(+), 10 deletions(-) diff --git a/CodeConverter/CSharp/CommonConversions.cs b/CodeConverter/CSharp/CommonConversions.cs index d5086bf6a..33f6531b5 100644 --- a/CodeConverter/CSharp/CommonConversions.cs +++ b/CodeConverter/CSharp/CommonConversions.cs @@ -646,6 +646,22 @@ public static CSSyntax.VariableDeclaratorSyntax CreateVariableDeclarator(string return (null, null); } + /// + /// A parameterized property's setter takes the value after the index parameters. + /// When an index argument is named, or an optional one is left out, the value must be named too, since a positional argument can't follow them. + /// + public static CSSyntax.ArgumentListSyntax AddSetterValueArgument(CSSyntax.ArgumentListSyntax indexArgs, IPropertySymbol property, ExpressionSyntax value) + { + var valueArg = SyntaxFactory.Argument(value); + var mustNameValue = indexArgs.Arguments.Count != property.GetParameters().Length || + indexArgs.Arguments.Any(t => t.NameColon != null); + if (mustNameValue) { + valueArg = valueArg.WithNameColon(SyntaxFactory.NameColon("value")); + } + + return indexArgs.WithArguments(indexArgs.Arguments.Add(valueArg)); + } + private async Task GetParameterizedSetterArgAsync(IOperation operation) { var vbNode = (VBSyntax.ExpressionSyntax) operation.Parent.Syntax.ChildNodes().ElementAt(1); diff --git a/CodeConverter/CSharp/NameExpressionNodeVisitor.cs b/CodeConverter/CSharp/NameExpressionNodeVisitor.cs index d9f3ad3e8..7331794f4 100644 --- a/CodeConverter/CSharp/NameExpressionNodeVisitor.cs +++ b/CodeConverter/CSharp/NameExpressionNodeVisitor.cs @@ -467,16 +467,7 @@ private async Task TryConvertParameterizedPropertyAs var args = await _argumentConverter.ConvertArgumentListOrEmptyAsync(node, optionalArgumentList); if (extraArg != null) { - var extraArgSyntax = SyntaxFactory.Argument(extraArg); - var propertySymbol = ((IPropertyReferenceOperation)operation).Property; - var forceNamedExtraArg = args.Arguments.Count != propertySymbol.GetParameters().Length || - args.Arguments.Any(t => t.NameColon != null); - - if (forceNamedExtraArg) { - extraArgSyntax = extraArgSyntax.WithNameColon(SyntaxFactory.NameColon("value")); - } - - args = args.WithArguments(args.Arguments.Add(extraArgSyntax)); + args = CommonConversions.AddSetterValueArgument(args, ((IPropertyReferenceOperation)operation).Property, extraArg); } return SyntaxFactory.InvocationExpression((ExpressionSyntax)expr, args); From ae65b030f6b6695558282b230f5daa3f697606af Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 00:32:06 +0000 Subject: [PATCH 13/56] Write back a ByRef parameterized property through its setter (#909) A parameterized property (not the default one) becomes get_X/set_X methods in C#, and the ByRef argument converted to the getter call. The write-back reused that call as the assignment target, giving `get_X(...) = arg` (CS0131). Like VB (LocalRewriter_Call.vb sets the second use's access kind to Set), write back by calling the setter with the same index arguments and the value. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- CodeConverter/CSharp/AdditionalAssignment.cs | 23 +-- .../ByRefArguments/ByRefArgumentHoister.cs | 26 +++- Tests/CSharp/ExpressionTests/ByRefTests.cs | 69 +++++++++ ...rameterizedPropertyOptionStrictOffTests.vb | 42 ++++++ .../VBToCS/ByRefParameterizedPropertyTests.vb | 136 ++++++++++++++++++ 5 files changed, 284 insertions(+), 12 deletions(-) create mode 100644 Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyOptionStrictOffTests.vb create mode 100644 Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb diff --git a/CodeConverter/CSharp/AdditionalAssignment.cs b/CodeConverter/CSharp/AdditionalAssignment.cs index 95ff7e39f..4f874b012 100644 --- a/CodeConverter/CSharp/AdditionalAssignment.cs +++ b/CodeConverter/CSharp/AdditionalAssignment.cs @@ -5,18 +5,21 @@ namespace ICSharpCode.CodeConverter.CSharp; internal class AdditionalAssignment : IHoistedNode { + private readonly ExpressionSyntax _assignment; + public AdditionalAssignment(ExpressionSyntax lhs, ExpressionSyntax rhs) + : this(SyntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, + lhs ?? throw new ArgumentNullException(nameof(lhs)), rhs ?? throw new ArgumentNullException(nameof(rhs)))) { - RightHandSide = rhs ?? throw new ArgumentNullException(nameof(rhs)); - LeftHandSide = lhs ?? throw new ArgumentNullException(nameof(lhs)); } - public ExpressionSyntax LeftHandSide { get; set; } - public ExpressionSyntax RightHandSide { get; } + private AdditionalAssignment(ExpressionSyntax assignment) => _assignment = assignment; - public static StatementSyntax CreateAssignment(AdditionalAssignment additionalAssignment) - { - var assign = SyntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, additionalAssignment.LeftHandSide, additionalAssignment.RightHandSide); - return SyntaxFactory.ExpressionStatement(assign); - } -} \ No newline at end of file + /// + /// A parameterized property becomes a pair of methods in C#, so there's nothing to assign to: call its setter instead. + /// + public static AdditionalAssignment ViaSetter(InvocationExpressionSyntax setterCall) => new(setterCall); + + public static StatementSyntax CreateAssignment(AdditionalAssignment additionalAssignment) => + SyntaxFactory.ExpressionStatement(additionalAssignment._assignment); +} diff --git a/CodeConverter/CSharp/ByRefArguments/ByRefArgumentHoister.cs b/CodeConverter/CSharp/ByRefArguments/ByRefArgumentHoister.cs index abd89565e..c26a8e188 100644 --- a/CodeConverter/CSharp/ByRefArguments/ByRefArgumentHoister.cs +++ b/CodeConverter/CSharp/ByRefArguments/ByRefArgumentHoister.cs @@ -1,4 +1,6 @@ -namespace ICSharpCode.CodeConverter.CSharp.ByRefArguments; +using Microsoft.CodeAnalysis.Operations; + +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. @@ -58,11 +60,31 @@ public CSSyntax.ExpressionSyntax HoistByRefDeclaration(VBSyntax.ExpressionSyntax 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); + var writeBack = CreateWriteBack(node, refLValue, convertedLocalIdentifier); if (_writeBacksPerCall.Count > 0) _writeBacksPerCall.Peek().Add(writeBack); else _typeContext.PerScopeState.Hoist(writeBack); } return local.IdentifierName; } + + private AdditionalAssignment CreateWriteBack(VBSyntax.ExpressionSyntax vbTarget, CSSyntax.ExpressionSyntax csTarget, CSSyntax.ExpressionSyntax value) + { + if (_semanticModel.GetOperation(vbTarget) is IPropertyReferenceOperation { Arguments.Length: > 0 } pro && !VBasic.VisualBasicExtensions.IsDefault(pro.Property) && + csTarget is CSSyntax.InvocationExpressionSyntax getterCall) { + return AdditionalAssignment.ViaSetter(CreateSetterCall(getterCall, pro.Property, value)); + } + return new AdditionalAssignment(csTarget, value); + } + + private static CSSyntax.InvocationExpressionSyntax CreateSetterCall(CSSyntax.InvocationExpressionSyntax getterCall, IPropertySymbol property, CSSyntax.ExpressionSyntax value) + { + var setterName = ValidSyntaxFactory.IdentifierName(property.SetMethod.Name); + CSSyntax.ExpressionSyntax setter = getterCall.Expression switch { + CSSyntax.MemberAccessExpressionSyntax maes => maes.WithName(setterName), + CSSyntax.SimpleNameSyntax => setterName, + var other => throw new NotSupportedException($"Parameterized property getter call {other.Kind()}") + }; + return CS.SyntaxFactory.InvocationExpression(setter, CommonConversions.AddSetterValueArgument(getterCall.ArgumentList, property, value)); + } } diff --git a/Tests/CSharp/ExpressionTests/ByRefTests.cs b/Tests/CSharp/ExpressionTests/ByRefTests.cs index d1437fa1c..f3bba8775 100644 --- a/Tests/CSharp/ExpressionTests/ByRefTests.cs +++ b/Tests/CSharp/ExpressionTests/ByRefTests.cs @@ -1557,4 +1557,73 @@ public void M(object o) } }", incompatibleWithAutomatedCommentTesting: true); // The late-bound assignment is emitted on the local function's line } + + [Fact] + public async Task ParameterizedPropertyIsWrittenBackThroughItsSetterIssue909Async() + { + await TestConversionVisualBasicToCSharpAsync(@"Public Class ClsDb + Private ReadOnly _recordValues(10, 30) As String + + Public Sub Get_Equal(ByRef tableBuffer As Integer, ByRef keyIndex As Integer, ByRef keyValue As String, ByRef recordPosition As String, ByRef errorNumber As Integer) + keyValue = ""found"" + End Sub + + Public Property Qr(ByVal tableBuffer As Integer, ByVal fieldNumber As Integer) As String + Get + Return _recordValues(tableBuffer, fieldNumber) + End Get + Set(ByVal value As String) + _recordValues(tableBuffer, fieldNumber) = value + End Set + End Property +End Class + +Public Module Euro_Str + Public Db As New ClsDb + Public QAdr As Integer + Public CourseBuffer As Integer +End Module + +Public Class Caller + Sub Find(recordPositionQAdr As String, errorCode As Integer) + Db.Get_Equal(QAdr, 0, Db.Qr(CourseBuffer, 21), recordPositionQAdr, errorCode) + End Sub +End Class", @" +public partial class ClsDb +{ + private readonly string[,] _recordValues = new string[11, 31]; + + public void Get_Equal(ref int tableBuffer, ref int keyIndex, ref string keyValue, ref string recordPosition, ref int errorNumber) + { + keyValue = ""found""; + } + + public string get_Qr(int tableBuffer, int fieldNumber) + { + return _recordValues[tableBuffer, fieldNumber]; + } + public void set_Qr(int tableBuffer, int fieldNumber, string value) + { + _recordValues[tableBuffer, fieldNumber] = value; + } +} + +public static partial class Euro_Str +{ + public static ClsDb Db = new ClsDb(); + public static int QAdr; + public static int CourseBuffer; +} + +public partial class Caller +{ + public void Find(string recordPositionQAdr, int errorCode) + { + int argkeyIndex = 0; + string argkeyValue = Euro_Str.Db.get_Qr(Euro_Str.CourseBuffer, 21); + Euro_Str.Db.Get_Equal(ref Euro_Str.QAdr, ref argkeyIndex, ref argkeyValue, ref recordPositionQAdr, ref errorCode); + Euro_Str.Db.set_Qr(Euro_Str.CourseBuffer, 21, argkeyValue); + } +}"); + } } \ No newline at end of file diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyOptionStrictOffTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyOptionStrictOffTests.vb new file mode 100644 index 000000000..0d30c5dde --- /dev/null +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyOptionStrictOffTests.vb @@ -0,0 +1,42 @@ +Option Strict Off + +Imports System.Collections.Generic +Imports Xunit + +Public Class ByRefParameterizedPropertyOptionStrictOffTests + Private ReadOnly _log As New List(Of String) + + + Public Sub ConvertedValueIsWrittenBackThroughTheSetter() + Dim table As New Table(_log) + Dim index As Object = "2" + Increment(table.Cell(index)) + Assert.Equal(11, table.Cell(2)) + Assert.Equal("get 2;set 2=11;get 2", String.Join(";", _log)) + End Sub + + Private Shared Sub Increment(ByRef value As String) + value = CStr(CInt(value) + 1) + End Sub + + Private Class Table + Private ReadOnly _log As List(Of String) + Private ReadOnly _values As New Dictionary(Of Integer, Integer) + + Public Sub New(log As List(Of String)) + _log = log + End Sub + + Public Property Cell(index As Integer) As Integer + Get + _log.Add("get " & index) + Dim value As Integer + Return If(_values.TryGetValue(index, value), value, 10) + End Get + Set(value As Integer) + _log.Add("set " & index & "=" & value) + _values(index) = value + End Set + End Property + End Class +End Class diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb new file mode 100644 index 000000000..da9e681a5 --- /dev/null +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb @@ -0,0 +1,136 @@ +Imports System.Collections.Generic +Imports Xunit + +Public Class ByRefParameterizedPropertyTests + Private ReadOnly _log As New List(Of String) + Private _fieldIndex As Integer = 1 + + + Public Sub ParameterizedPropertyIsWrittenBackThroughItsSetterIssue909() + Dim db As New Db(_log) + db.Get_Equal(1, db.Qr(1, 21), "position") + Assert.Equal("changed", db.Qr(1, 21)) + Assert.Equal("get 1,21;set 1,21=changed;get 1,21", LogText()) + End Sub + + + Public Sub OmittedOptionalIndexIsWrittenBackThroughTheSetter() + Dim db As New Db(_log) + SetValue(db.WithDefault()) + Assert.Equal("get 7;set 7=changed", LogText()) + End Sub + + + Public Sub ImplicitMeParameterizedPropertyIsWrittenBack() + Dim db As New Db(_log) + db.SetOwnValue() + db.SetOwnValueWithMe() + Assert.Equal("get 2,3;set 2,3=changed;get 4,5;set 4,5=changed", LogText()) + End Sub + + + Public Sub ReadOnlyParameterizedPropertyIsNotWrittenBack() + Dim db As New Db(_log) + SetValue(db.ReadOnlyQr(NextIndex())) + Assert.Equal("index 1;readonly get 1", LogText()) + End Sub + + Private Function LogText() As String + Return String.Join(";", _log) + End Function + + Private Function NextIndex() As Integer + _log.Add("index 1") + Return 1 + End Function + + Private Function GetDb() As Db + _log.Add("receiver") + Return New Db(_log) + End Function + + Private Shared Function SetValue(ByRef value As String) As String + value = "changed" + Return value + End Function + + Private Shared Sub SetValueAndIndex(ByRef value As String, ByRef index As Integer) + value = "changed" + index = 5 + End Sub + + Private Class Db + Private ReadOnly _log As List(Of String) + Private ReadOnly _values As New Dictionary(Of String, String) + + Public Sub New(log As List(Of String)) + _log = log + End Sub + + Public Sub Get_Equal(ByRef tableBuffer As Integer, ByRef keyValue As String, ByRef recordPosition As String) + keyValue = "changed" + End Sub + + Public Sub SetOwnValue() + SetValue(Qr(2, 3)) + End Sub + + Public Sub SetOwnValueWithMe() + SetValue(Me.Qr(4, 5)) + End Sub + + Public Property Qr(tableBuffer As Integer, fieldNumber As Integer) As String + Get + _log.Add("get " & tableBuffer & "," & fieldNumber) + Return Lookup(tableBuffer & "," & fieldNumber) + End Get + Set(value As String) + _log.Add("set " & tableBuffer & "," & fieldNumber & "=" & value) + _values(tableBuffer & "," & fieldNumber) = value + End Set + End Property + + Public Property WithDefault(Optional index As Integer = 7) As String + Get + _log.Add("get " & index) + Return Lookup(CStr(index)) + End Get + Set(value As String) + _log.Add("set " & index & "=" & value) + End Set + End Property + + Public ReadOnly Property ReadOnlyQr(index As Integer) As String + Get + _log.Add("readonly get " & index) + Return Lookup(CStr(index)) + End Get + End Property + + Default Public Property Item(index As Integer) As String + Get + _log.Add("item get " & index) + Return Lookup(CStr(index)) + End Get + Set(value As String) + _log.Add("item set " & index & "=" & value) + End Set + End Property + + Public Property Plain As String + Get + _log.Add("plain get") + Return Nothing + End Get + Set(value As String) + _log.Add("plain set=" & value) + End Set + End Property + + Private Function Lookup(key As String) As String + Dim value As String = Nothing + _values.TryGetValue(key, value) + Return value + End Function + End Class +End Class From 33eee75e3fb596251273915d273e7ebfb12db62b Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 23:58:06 +0000 Subject: [PATCH 14/56] Evaluate a ByRef property target's receiver and indexes once VB reads a ByRef property argument before the call and writes it after, evaluating its receiver and index arguments only once (UseTwiceRewriter.vb). The C# read and write-back each evaluated them, so e.g. `db.Qr(NextIndex())` called NextIndex twice, and `GetC().Plain` called GetC twice. Hoist a part into a temporary only where its second value could differ: anything but a constant, Me, or a local, parameter or field that the enclosing expression doesn't write. Existing simple output is unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- .../ByRefArguments/ByRefArgumentHoister.cs | 4 + .../CSharp/ByRefTargetTemporaries.cs | 129 ++++++++++++++++++ Tests/CSharp/ExpressionTests/ByRefTests.cs | 122 +++++++++++++++++ .../VBToCS/ByRefParameterizedPropertyTests.vb | 70 ++++++++++ 4 files changed, 325 insertions(+) create mode 100644 CodeConverter/CSharp/ByRefTargetTemporaries.cs diff --git a/CodeConverter/CSharp/ByRefArguments/ByRefArgumentHoister.cs b/CodeConverter/CSharp/ByRefArguments/ByRefArgumentHoister.cs index c26a8e188..bb95c36cd 100644 --- a/CodeConverter/CSharp/ByRefArguments/ByRefArgumentHoister.cs +++ b/CodeConverter/CSharp/ByRefArguments/ByRefArgumentHoister.cs @@ -54,6 +54,10 @@ public CSSyntax.ExpressionSyntax HoistByRefDeclaration(VBSyntax.ExpressionSyntax refLValue = eae.WithExpression(tmpContainer.IdentifierName); } + if (refType == SemanticModelExtensions.RefConversion.PreAndPostAssignment) { + refLValue = ByRefTargetTemporaries.Hoist(_semanticModel, _typeContext, node, refLValue); + } + var withCast = CommonConversions.TypeConversionAnalyzer.AddExplicitConversion(node, refLValue, defaultToCast: refKind != RefKind.None); var local = _typeContext.PerScopeState.Hoist(new AdditionalDeclaration(prefix, withCast, typeSyntax)); diff --git a/CodeConverter/CSharp/ByRefTargetTemporaries.cs b/CodeConverter/CSharp/ByRefTargetTemporaries.cs new file mode 100644 index 000000000..482f760c6 --- /dev/null +++ b/CodeConverter/CSharp/ByRefTargetTemporaries.cs @@ -0,0 +1,129 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.Operations; + +namespace ICSharpCode.CodeConverter.CSharp; + +/// +/// A ByRef argument that VB copies back is used twice: read before the call, and written after it. +/// VB evaluates the target's receiver and index arguments once, and the write reuses their values +/// (Roslyn's UseTwiceRewriter.vb, called from RewriteByRefArgumentWithCopyBack in LocalRewriter_Call.vb). +/// The C# read and write-back are separate expressions, so a part that could have a different value the second time is hoisted into a temporary. +/// +/// +/// VB copies every part except constants and Me. A local, parameter or field gives the same value again unless it's written while the +/// enclosing expression runs, so it's only copied when that expression writes it (as a ByRef argument, or by assignment in a lambda). +/// A field that the called method itself assigns is still read again: we can't see that cheaply, and it's rare. +/// +internal class ByRefTargetTemporaries +{ + private readonly SemanticModel _semanticModel; + private readonly ITypeContext _typeContext; + private readonly VBSyntax.ExpressionSyntax _vbTarget; + private readonly Lazy> _writtenSymbols; + + private ByRefTargetTemporaries(SemanticModel semanticModel, ITypeContext typeContext, VBSyntax.ExpressionSyntax vbTarget) + { + _semanticModel = semanticModel; + _typeContext = typeContext; + _vbTarget = vbTarget; + _writtenSymbols = new Lazy>(GetSymbolsWrittenInEnclosingExpression); + } + + /// The C# target with each part VB evaluates once replaced by a hoisted temporary, where its value could otherwise differ. + public static CSSyntax.ExpressionSyntax Hoist(SemanticModel semanticModel, ITypeContext typeContext, VBSyntax.ExpressionSyntax vbTarget, CSSyntax.ExpressionSyntax csTarget) => + new ByRefTargetTemporaries(semanticModel, typeContext, vbTarget).Hoist(csTarget); + + private CSSyntax.ExpressionSyntax Hoist(CSSyntax.ExpressionSyntax csTarget) + { + return (_semanticModel.GetOperation(_vbTarget), csTarget) switch { + (IPropertyReferenceOperation pro, CSSyntax.InvocationExpressionSyntax getterCall) => + getterCall.WithExpression(HoistReceiver(getterCall.Expression, pro)) + .WithArgumentList(getterCall.ArgumentList.WithArguments(HoistArguments(getterCall.ArgumentList.Arguments, pro))), + (IPropertyReferenceOperation pro, CSSyntax.ElementAccessExpressionSyntax indexer) => + indexer.WithArgumentList(indexer.ArgumentList.WithArguments(HoistArguments(indexer.ArgumentList.Arguments, pro))), + (IArrayElementReferenceOperation element, CSSyntax.ElementAccessExpressionSyntax elementAccess) => + elementAccess.WithArgumentList(elementAccess.ArgumentList.WithArguments(HoistIndices(elementAccess.ArgumentList.Arguments, element.Indices))), + (IPropertyReferenceOperation pro, CSSyntax.MemberAccessExpressionSyntax) => HoistReceiver(csTarget, pro), + _ => csTarget + }; + } + + /// The container of an element access is already hoisted by the caller. + private CSSyntax.ExpressionSyntax HoistReceiver(CSSyntax.ExpressionSyntax memberExpression, IPropertyReferenceOperation pro) + { + if (memberExpression is not CSSyntax.MemberAccessExpressionSyntax maes || pro.Property.IsStatic || IsReusable(pro.Instance)) { + return memberExpression; + } + return maes.WithExpression(HoistValue(maes.Expression)); + } + + private SeparatedSyntaxList HoistArguments(SeparatedSyntaxList csArgs, IPropertyReferenceOperation pro) + { + var parameters = pro.Property.Parameters; + return CS.SyntaxFactory.SeparatedList(csArgs.Select((csArg, i) => { + var parameter = csArg.NameColon is { } nameColon + ? parameters.FirstOrDefault(p => string.Equals(p.Name, nameColon.Name.Identifier.ValueText, StringComparison.OrdinalIgnoreCase)) + : parameters.ElementAtOrDefault(Math.Min(i, parameters.Length - 1)); + var vbArg = pro.Arguments.FirstOrDefault(a => SymbolEqualityComparer.Default.Equals(a.Parameter, parameter)); + return IsReusable(vbArg, i - parameters.IndexOf(parameter)) ? csArg : csArg.WithExpression(HoistValue(csArg.Expression)); + })); + } + + private SeparatedSyntaxList HoistIndices(SeparatedSyntaxList csArgs, ImmutableArray indices) + { + return CS.SyntaxFactory.SeparatedList(csArgs.Select((csArg, i) => + IsReusable(indices.ElementAtOrDefault(i)) ? csArg : csArg.WithExpression(HoistValue(csArg.Expression)))); + } + + /// For a ParamArray parameter, which of its elements the C# argument passes. + private bool IsReusable(IArgumentOperation vbArg, int paramArrayIndex) => vbArg switch { + // The converter fills in an omitted argument with a constant or a temporary of its own + { ArgumentKind: ArgumentKind.DefaultValue } => true, + { ArgumentKind: ArgumentKind.ParamArray, Value: IArrayCreationOperation { Initializer.ElementValues: var elements } } => + paramArrayIndex >= 0 && paramArrayIndex < elements.Length && IsReusable(elements[paramArrayIndex]), + { ArgumentKind: ArgumentKind.Explicit } => IsReusable(vbArg.Value), + _ => false + }; + + private bool IsReusable(IOperation vbValue) => vbValue switch { + null => true, + { ConstantValue.HasValue: true } => true, + IInstanceReferenceOperation => true, + IParenthesizedOperation p => IsReusable(p.Operand), + IConversionOperation { OperatorMethod: null } c => IsReusable(c.Operand), + ILocalReferenceOperation l => !_writtenSymbols.Value.Contains(l.Local), + IParameterReferenceOperation p => !_writtenSymbols.Value.Contains(p.Parameter), + IFieldReferenceOperation f => !_writtenSymbols.Value.Contains(f.Field) && IsReusable(f.Instance), + _ => false + }; + + private CSSyntax.ExpressionSyntax HoistValue(CSSyntax.ExpressionSyntax value) => + _typeContext.PerScopeState.Hoist(new AdditionalDeclaration("tmp", value, ValidSyntaxFactory.VarType)).IdentifierName; + + /// + /// The temporaries and write-back are placed around the enclosing expression, so that's what could change a variable in between. + /// + private HashSet GetSymbolsWrittenInEnclosingExpression() + { + SyntaxNode enclosing = _vbTarget; + while (enclosing.Parent is VBSyntax.ExpressionSyntax or VBSyntax.ArgumentSyntax or VBSyntax.ArgumentListSyntax) { + enclosing = enclosing.Parent; + } + + var written = _semanticModel.GetOperation(enclosing)?.DescendantsAndSelf().Select(o => o switch { + IArgumentOperation { Parameter.RefKind: not RefKind.None } a => a.Value, + IAssignmentOperation a => a.Target, + _ => null + }).Select(GetReferencedVariable).Where(s => s != null); + return new HashSet(written ?? Enumerable.Empty(), SymbolEqualityComparer.Default); + } + + private static ISymbol GetReferencedVariable(IOperation operation) => operation switch { + IParenthesizedOperation p => GetReferencedVariable(p.Operand), + IConversionOperation c => GetReferencedVariable(c.Operand), + ILocalReferenceOperation l => l.Local, + IParameterReferenceOperation p => p.Parameter, + IFieldReferenceOperation f => f.Field, + _ => null + }; +} diff --git a/Tests/CSharp/ExpressionTests/ByRefTests.cs b/Tests/CSharp/ExpressionTests/ByRefTests.cs index f3bba8775..d26891865 100644 --- a/Tests/CSharp/ExpressionTests/ByRefTests.cs +++ b/Tests/CSharp/ExpressionTests/ByRefTests.cs @@ -1624,6 +1624,128 @@ public void Find(string recordPositionQAdr, int errorCode) Euro_Str.Db.Get_Equal(ref Euro_Str.QAdr, ref argkeyIndex, ref argkeyValue, ref recordPositionQAdr, ref errorCode); Euro_Str.Db.set_Qr(Euro_Str.CourseBuffer, 21, argkeyValue); } +}"); + } + + [Fact] + public async Task ByRefPropertyTargetEvaluatesReceiverAndIndexesOnceAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Public Class C + Private _index As Integer + + Public Property Qr(a As Integer, b As Integer) As String + Get + Return """" + End Get + Set(value As String) + End Set + End Property + + Default Public Property Item(i As Integer) As String + Get + Return """" + End Get + Set(value As String) + End Set + End Property + + Public Property Plain As String + + Function NextIndex() As Integer + Return 1 + End Function + + Function GetC() As C + Return Me + End Function + + Shared Sub SetValue(ByRef value As String) + End Sub + + Shared Sub SetValueAndIndex(ByRef value As String, ByRef index As Integer) + End Sub + + Sub UsesTwice(other As C) + Dim i = 1 + SetValue(Qr(i, 2)) ' Locals, constants and fields are evaluated again + SetValue(other.Qr(_index, NextIndex())) + SetValue(GetC().Qr(1, 2)) + SetValue(GetC().Plain) + SetValue(other(NextIndex())) + SetValueAndIndex(other.Qr(i, 2), i) ' i is written by the call + End Sub +End Class", @" +public partial class C +{ + private int _index; + + public string get_Qr(int a, int b) + { + return """"; + } + public void set_Qr(int a, int b, string value) + { + } + + public string this[int i] + { + get + { + return """"; + } + set + { + } + } + + public string Plain { get; set; } + + public int NextIndex() + { + return 1; + } + + public C GetC() + { + return this; + } + + public static void SetValue(ref string value) + { + } + + public static void SetValueAndIndex(ref string value, ref int index) + { + } + + public void UsesTwice(C other) + { + int i = 1; + string argvalue = get_Qr(i, 2); + SetValue(ref argvalue); + set_Qr(i, 2, argvalue); // Locals, constants and fields are evaluated again + var tmp = NextIndex(); + string argvalue1 = other.get_Qr(_index, tmp); + SetValue(ref argvalue1); + other.set_Qr(_index, tmp, argvalue1); + var tmp1 = GetC(); + string argvalue2 = tmp1.get_Qr(1, 2); + SetValue(ref argvalue2); + tmp1.set_Qr(1, 2, argvalue2); + var tmp2 = GetC(); + string argvalue3 = tmp2.Plain; + SetValue(ref argvalue3); + tmp2.Plain = argvalue3; + var tmp3 = other; + var tmp4 = NextIndex(); + string argvalue4 = tmp3[tmp4]; + SetValue(ref argvalue4); + tmp3[tmp4] = argvalue4; + var tmp5 = i; + string argvalue5 = other.get_Qr(tmp5, 2); + SetValueAndIndex(ref argvalue5, ref i); + other.set_Qr(tmp5, 2, argvalue5); // i is written by the call + } }"); } } \ No newline at end of file diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb index da9e681a5..1bc3bc582 100644 --- a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb @@ -13,6 +13,26 @@ Public Class ByRefParameterizedPropertyTests Assert.Equal("get 1,21;set 1,21=changed;get 1,21", LogText()) End Sub + + Public Sub IndexArgumentsAreEvaluatedOnce() + Dim db As New Db(_log) + SetValue(db.Qr(NextIndex(), 21)) + Assert.Equal("index 1;get 1,21;set 1,21=changed", LogText()) + End Sub + + + Public Sub ReceiverIsEvaluatedOnce() + SetValue(GetDb().Qr(1, 21)) + Assert.Equal("receiver;get 1,21;set 1,21=changed", LogText()) + End Sub + + + Public Sub NamedIndexArgumentsAreWrittenBackThroughTheSetter() + Dim db As New Db(_log) + SetValue(db.Qr(fieldNumber:=21, tableBuffer:=NextIndex())) + Assert.Equal("index 1;get 1,21;set 1,21=changed", LogText()) + End Sub + Public Sub OmittedOptionalIndexIsWrittenBackThroughTheSetter() Dim db As New Db(_log) @@ -28,6 +48,23 @@ Public Class ByRefParameterizedPropertyTests Assert.Equal("get 2,3;set 2,3=changed;get 4,5;set 4,5=changed", LogText()) End Sub + + Public Sub LocalIndexWrittenByAnotherArgumentUsesItsOriginalValue() + Dim db As New Db(_log) + Dim index = 1 + SetValueAndIndex(db.Qr(index, 21), index) + Assert.Equal(5, index) + Assert.Equal("get 1,21;set 1,21=changed", LogText()) + End Sub + + + Public Sub FieldIndexWrittenByAnotherArgumentUsesItsOriginalValue() + Dim db As New Db(_log) + SetValueAndIndex(db.Qr(_fieldIndex, 21), _fieldIndex) + Assert.Equal(5, _fieldIndex) + Assert.Equal("get 1,21;set 1,21=changed", LogText()) + End Sub + Public Sub ReadOnlyParameterizedPropertyIsNotWrittenBack() Dim db As New Db(_log) @@ -35,6 +72,39 @@ Public Class ByRefParameterizedPropertyTests Assert.Equal("index 1;readonly get 1", LogText()) End Sub + + Public Sub DefaultPropertyIndexIsEvaluatedOnce() + Dim db As New Db(_log) + SetValue(db(NextIndex())) + Assert.Equal("index 1;item get 1;item set 1=changed", LogText()) + End Sub + + + Public Sub PropertyReceiverIsEvaluatedOnce() + SetValue(GetDb().Plain) + Assert.Equal("receiver;plain get;plain set=changed", LogText()) + End Sub + + + Public Sub ReturnWritesBackThroughTheSetterBeforeReturning() + Dim db As New Db(_log) + Assert.Equal("changed", ReturnSetValue(db)) + Assert.Equal("index 1;get 1,21;set 1,21=changed", LogText()) + End Sub + + + Public Sub ConditionWritesBackThroughTheSetterBeforeTheBlock() + Dim db As New Db(_log) + If SetValue(db.Qr(NextIndex(), 21)) = "changed" Then + _log.Add("then " & db.Qr(1, 21)) + End If + Assert.Equal("index 1;get 1,21;set 1,21=changed;get 1,21;then changed", LogText()) + End Sub + + Private Function ReturnSetValue(db As Db) As String + Return SetValue(db.Qr(NextIndex(), 21)) + End Function + Private Function LogText() As String Return String.Join(";", _log) End Function From 5a58e8f75be91b3ef9baccd86fa5bdb10fc54dd4 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 23:58:28 +0000 Subject: [PATCH 15/56] Document what a ByRef write-back writes to Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- CodeConverter/CSharp/ByRefArguments/README.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/CodeConverter/CSharp/ByRefArguments/README.md b/CodeConverter/CSharp/ByRefArguments/README.md index e5567face..ec90b9307 100644 --- a/CodeConverter/CSharp/ByRefArguments/README.md +++ b/CodeConverter/CSharp/ByRefArguments/README.md @@ -29,7 +29,25 @@ 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). +### What the write-back writes to + +Source: Roslyn's [`UseTwiceRewriter.vb`](https://github.com/dotnet/roslyn/blob/main/src/Compilers/VisualBasic/Portable/Lowering/UseTwiceRewriter.vb), which `RewriteByRefArgumentWithCopyBack` uses to read the target and then write it with the setter. Behaviour is covered by `Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedProperty*.vb`. + +* VB evaluates the target's receiver and index arguments once, and the write-back reuses their values. It copies each into a temporary except literals, constants and `Me`. +* The converter hoists a `tmp` only where the second evaluation could give a different value. A local, parameter or field is reused unless the enclosing expression writes it (as a ByRef argument, or in a lambda): `ByRefTargetTemporaries`. +* A parameterized property (not the default one) becomes `get_X`/`set_X` methods, so its write-back calls the setter with the same index arguments: `ByRefArgumentHoister.CreateWriteBack`, `AdditionalAssignment.ViaSetter`. It takes its place in the call's reversed write-back order like any other. +* A `ReadOnly` property isn't written back (`GetRefConversionForExpression`), so it's evaluated once and needs no temporaries. + +| VB target | C# | +|---|---| +| `Qr(i, 2)`, `other.Qr(_index, 2)` | `get_Qr(i, 2)` … `set_Qr(i, 2, arg)` | +| `other.Qr(NextIndex(), 2)` | `var tmp = NextIndex();` … `other.get_Qr(tmp, 2)` … `other.set_Qr(tmp, 2, arg)` | +| `GetC().Qr(1, 2)`, `GetC().Plain` | `var tmp = GetC();` … `tmp.set_Qr(1, 2, arg)`, `tmp.Plain = arg` | +| `other(NextIndex())` (default property or indexer) | `var tmp = other; var tmp1 = NextIndex();` … `tmp[tmp1] = arg` (the container is always copied, as before) | +| `Two(other.Qr(i, 2), i)` | `var tmp = i;` … `other.set_Qr(tmp, 2, arg)` | + Known gaps: +* A field that the called method itself assigns is read again for the write-back, where VB uses its original value. Detecting it needs analysis of the callee. * 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). From 9ec4b83369a6f3a065c7516ab9748acd2b128b57 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 00:07:16 +0000 Subject: [PATCH 16/56] Write a ByRef structure property back in place Copying a structure receiver such as `cells(NextIndex())` into a temporary made the write-back set the property on the copy, losing it. Like VB's UseTwiceRewriter, keep a structure variable in place and copy only the parts that locate it: the array and indexes, or the reference holding the field. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- CodeConverter/CSharp/ByRefArguments/README.md | 1 + .../CSharp/ByRefTargetTemporaries.cs | 24 +++++++++++- .../VBToCS/ByRefParameterizedPropertyTests.vb | 38 +++++++++++++++++++ 3 files changed, 61 insertions(+), 2 deletions(-) diff --git a/CodeConverter/CSharp/ByRefArguments/README.md b/CodeConverter/CSharp/ByRefArguments/README.md index ec90b9307..3eb595fb5 100644 --- a/CodeConverter/CSharp/ByRefArguments/README.md +++ b/CodeConverter/CSharp/ByRefArguments/README.md @@ -45,6 +45,7 @@ Source: Roslyn's [`UseTwiceRewriter.vb`](https://github.com/dotnet/roslyn/blob/m | `GetC().Qr(1, 2)`, `GetC().Plain` | `var tmp = GetC();` … `tmp.set_Qr(1, 2, arg)`, `tmp.Plain = arg` | | `other(NextIndex())` (default property or indexer) | `var tmp = other; var tmp1 = NextIndex();` … `tmp[tmp1] = arg` (the container is always copied, as before) | | `Two(other.Qr(i, 2), i)` | `var tmp = i;` … `other.set_Qr(tmp, 2, arg)` | +| `cells(NextIndex()).Text`, `GetHolder().Cell.Text` (`Cell` is a structure) | `var tmp = NextIndex();` … `cells[tmp].Text = arg`, `var tmp = GetHolder();` … `tmp.Cell.Text = arg`: a structure variable is written in place (`ByRefTargetTemporaries.HoistInstance`) | Known gaps: * A field that the called method itself assigns is read again for the write-back, where VB uses its original value. Detecting it needs analysis of the callee. diff --git a/CodeConverter/CSharp/ByRefTargetTemporaries.cs b/CodeConverter/CSharp/ByRefTargetTemporaries.cs index 482f760c6..6cf035b1f 100644 --- a/CodeConverter/CSharp/ByRefTargetTemporaries.cs +++ b/CodeConverter/CSharp/ByRefTargetTemporaries.cs @@ -51,10 +51,30 @@ private CSSyntax.ExpressionSyntax Hoist(CSSyntax.ExpressionSyntax csTarget) /// The container of an element access is already hoisted by the caller. private CSSyntax.ExpressionSyntax HoistReceiver(CSSyntax.ExpressionSyntax memberExpression, IPropertyReferenceOperation pro) { - if (memberExpression is not CSSyntax.MemberAccessExpressionSyntax maes || pro.Property.IsStatic || IsReusable(pro.Instance)) { + if (memberExpression is not CSSyntax.MemberAccessExpressionSyntax maes || pro.Property.IsStatic) { return memberExpression; } - return maes.WithExpression(HoistValue(maes.Expression)); + return maes.WithExpression(HoistInstance(pro.Instance, maes.Expression)); + } + + /// + /// A reference can be copied, but writing a structure's property through a copy would lose the write. + /// So, like VB, a structure variable stays in place and only the parts that locate it are copied. + /// + private CSSyntax.ExpressionSyntax HoistInstance(IOperation instance, CSSyntax.ExpressionSyntax csInstance) + { + if (IsReusable(instance)) return csInstance; + if (instance.Type?.IsReferenceType == true) return HoistValue(csInstance); + return (instance, csInstance) switch { + (ILocalReferenceOperation or IParameterReferenceOperation, _) => csInstance, + (IFieldReferenceOperation { Instance: { } fieldInstance }, CSSyntax.MemberAccessExpressionSyntax maes) => + maes.WithExpression(HoistInstance(fieldInstance, maes.Expression)), + (IFieldReferenceOperation, _) => csInstance, + (IArrayElementReferenceOperation element, CSSyntax.ElementAccessExpressionSyntax elementAccess) => + elementAccess.WithExpression(HoistInstance(element.ArrayReference, elementAccess.Expression)) + .WithArgumentList(elementAccess.ArgumentList.WithArguments(HoistIndices(elementAccess.ArgumentList.Arguments, element.Indices))), + _ => HoistValue(csInstance) + }; } private SeparatedSyntaxList HoistArguments(SeparatedSyntaxList csArgs, IPropertyReferenceOperation pro) diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb index 1bc3bc582..b2ac44dcd 100644 --- a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb @@ -85,6 +85,44 @@ Public Class ByRefParameterizedPropertyTests Assert.Equal("receiver;plain get;plain set=changed", LogText()) End Sub + + Public Sub StructureReceiverInAnArrayIsWrittenInPlace() + Dim cells(2) As Cell + SetValue(cells(NextIndex()).Text) + Assert.Equal("changed", cells(1).Text) + Assert.Equal("index 1", LogText()) + End Sub + + + Public Sub StructureFieldReceiverIsWrittenInPlace() + Dim holder As New CellHolder + SetValue(holder.Cell.Text) + SetValue(GetHolder(holder).Cell.Text) + Assert.Equal("changedchanged", holder.Cell.Text) + Assert.Equal("holder", LogText()) + End Sub + + Private Function GetHolder(holder As CellHolder) As CellHolder + _log.Add("holder") + Return holder + End Function + + Private Class CellHolder + Public Cell As Cell + End Class + + Private Structure Cell + Private _text As String + Public Property Text As String + Get + Return _text + End Get + Set(value As String) + _text &= value + End Set + End Property + End Structure + Public Sub ReturnWritesBackThroughTheSetterBeforeReturning() Dim db As New Db(_log) From 077b82da1020fc5bc46c0f0ea89f6c1944e5805a Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 00:10:15 +0000 Subject: [PATCH 17/56] Test that ByRef setters write back in VB's reverse order Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- .../VBToCS/ByRefParameterizedPropertyTests.vb | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb index b2ac44dcd..68f622368 100644 --- a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb @@ -85,6 +85,18 @@ Public Class ByRefParameterizedPropertyTests Assert.Equal("receiver;plain get;plain set=changed", LogText()) End Sub + + Public Sub SettersAreCalledFromTheLastArgumentToTheFirst() + Dim db As New Db(_log) + SetTwoValues(db.Qr(1, 1), db.Qr(NextIndex(), 2)) + Assert.Equal("get 1,1;index 1;get 1,2;set 1,2=second;set 1,1=first", LogText()) + End Sub + + Private Shared Sub SetTwoValues(ByRef first As String, ByRef second As String) + first = "first" + second = "second" + End Sub + Public Sub StructureReceiverInAnArrayIsWrittenInPlace() Dim cells(2) As Cell From 15ae6ecd653c283cb62901e6512b08e7a268b1ed Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 00:24:11 +0000 Subject: [PATCH 18/56] Test more shapes of ByRef property targets Cover the cases coverage showed untested: a structure local written by another argument, an index local assigned in a lambda, an omitted optional index before a given one, and a parenthesized index. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- Tests/CSharp/ExpressionTests/ByRefTests.cs | 2 +- .../VBToCS/ByRefParameterizedPropertyTests.vb | 44 +++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/Tests/CSharp/ExpressionTests/ByRefTests.cs b/Tests/CSharp/ExpressionTests/ByRefTests.cs index d26891865..eded23428 100644 --- a/Tests/CSharp/ExpressionTests/ByRefTests.cs +++ b/Tests/CSharp/ExpressionTests/ByRefTests.cs @@ -1667,7 +1667,7 @@ End Sub Sub UsesTwice(other As C) Dim i = 1 - SetValue(Qr(i, 2)) ' Locals, constants and fields are evaluated again + SetValue(Qr((i), 2)) ' Locals, constants and fields are evaluated again SetValue(other.Qr(_index, NextIndex())) SetValue(GetC().Qr(1, 2)) SetValue(GetC().Plain) diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb index 68f622368..fc55ef309 100644 --- a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb @@ -1,3 +1,4 @@ +Imports System Imports System.Collections.Generic Imports Xunit @@ -114,6 +115,39 @@ Public Class ByRefParameterizedPropertyTests Assert.Equal("holder", LogText()) End Sub + + Public Sub StructureLocalWrittenByAnotherArgumentIsWrittenInPlace() + Dim cell As Cell + SetValueAndCell(cell.Text, cell) + Assert.Equal("replacedchanged", cell.Text) + End Sub + + Private Shared Sub SetValueAndCell(ByRef value As String, ByRef cell As Cell) + value = "changed" + cell = New Cell With {.Text = "replaced"} + End Sub + + + Public Sub LocalIndexAssignedInALambdaUsesItsOriginalValue() + Dim db As New Db(_log) + Dim index = 1 + SetValueAndRun(db.Qr(index, 21), Sub() index = 5) + Assert.Equal(5, index) + Assert.Equal("get 1,21;set 1,21=changed", LogText()) + End Sub + + Private Shared Sub SetValueAndRun(ByRef value As String, action As Action) + action() + value = "changed" + End Sub + + + Public Sub OmittedIndexBeforeAGivenOneIsWrittenBackThroughTheSetter() + Dim db As New Db(_log) + SetValue(db.TwoDefaults(, NextIndex())) + Assert.Equal("index 1;get 7,1;set 7,1=changed", LogText()) + End Sub + Private Function GetHolder(holder As CellHolder) As CellHolder _log.Add("holder") Return holder @@ -210,6 +244,16 @@ Public Class ByRefParameterizedPropertyTests End Set End Property + Public Property TwoDefaults(Optional a As Integer = 7, Optional b As Integer = 8) As String + Get + _log.Add("get " & a & "," & b) + Return Nothing + End Get + Set(value As String) + _log.Add("set " & a & "," & b & "=" & value) + End Set + End Property + Public Property WithDefault(Optional index As Integer = 7) As String Get _log.Add("get " & index) From 80d2bb6fe26d21123e2d24eb380a04f18848a4e8 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 00:24:11 +0000 Subject: [PATCH 19/56] Drop unreachable cases from ByRef target temporaries A ParamArray parameterized property can't be written back (its C# setter would need params before the value), and ParamArray elements don't map one to one onto C# arguments, so copy them like any other non-constant. ByRef arguments and assignment targets are never parenthesized or converted. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- CodeConverter/CSharp/ByRefTargetTemporaries.cs | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/CodeConverter/CSharp/ByRefTargetTemporaries.cs b/CodeConverter/CSharp/ByRefTargetTemporaries.cs index 6cf035b1f..8dd46e976 100644 --- a/CodeConverter/CSharp/ByRefTargetTemporaries.cs +++ b/CodeConverter/CSharp/ByRefTargetTemporaries.cs @@ -83,9 +83,9 @@ private CSSyntax.ExpressionSyntax HoistInstance(IOperation instance, CSSyntax.Ex return CS.SyntaxFactory.SeparatedList(csArgs.Select((csArg, i) => { var parameter = csArg.NameColon is { } nameColon ? parameters.FirstOrDefault(p => string.Equals(p.Name, nameColon.Name.Identifier.ValueText, StringComparison.OrdinalIgnoreCase)) - : parameters.ElementAtOrDefault(Math.Min(i, parameters.Length - 1)); + : parameters.ElementAtOrDefault(i); var vbArg = pro.Arguments.FirstOrDefault(a => SymbolEqualityComparer.Default.Equals(a.Parameter, parameter)); - return IsReusable(vbArg, i - parameters.IndexOf(parameter)) ? csArg : csArg.WithExpression(HoistValue(csArg.Expression)); + return IsReusable(vbArg) ? csArg : csArg.WithExpression(HoistValue(csArg.Expression)); })); } @@ -95,12 +95,10 @@ private CSSyntax.ExpressionSyntax HoistInstance(IOperation instance, CSSyntax.Ex IsReusable(indices.ElementAtOrDefault(i)) ? csArg : csArg.WithExpression(HoistValue(csArg.Expression)))); } - /// For a ParamArray parameter, which of its elements the C# argument passes. - private bool IsReusable(IArgumentOperation vbArg, int paramArrayIndex) => vbArg switch { + /// A ParamArray's elements don't map one to one onto C# arguments, so they're each copied. + private bool IsReusable(IArgumentOperation vbArg) => vbArg switch { // The converter fills in an omitted argument with a constant or a temporary of its own { ArgumentKind: ArgumentKind.DefaultValue } => true, - { ArgumentKind: ArgumentKind.ParamArray, Value: IArrayCreationOperation { Initializer.ElementValues: var elements } } => - paramArrayIndex >= 0 && paramArrayIndex < elements.Length && IsReusable(elements[paramArrayIndex]), { ArgumentKind: ArgumentKind.Explicit } => IsReusable(vbArg.Value), _ => false }; @@ -139,8 +137,6 @@ private HashSet GetSymbolsWrittenInEnclosingExpression() } private static ISymbol GetReferencedVariable(IOperation operation) => operation switch { - IParenthesizedOperation p => GetReferencedVariable(p.Operand), - IConversionOperation c => GetReferencedVariable(c.Operand), ILocalReferenceOperation l => l.Local, IParameterReferenceOperation p => p.Parameter, IFieldReferenceOperation f => f.Field, From baa5344c1e415b2e653e2e408f5dd7398be039b1 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 00:24:25 +0000 Subject: [PATCH 20/56] Document remaining ByRef property target gaps Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- CodeConverter/CSharp/ByRefArguments/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CodeConverter/CSharp/ByRefArguments/README.md b/CodeConverter/CSharp/ByRefArguments/README.md index 3eb595fb5..8c3689c63 100644 --- a/CodeConverter/CSharp/ByRefArguments/README.md +++ b/CodeConverter/CSharp/ByRefArguments/README.md @@ -48,7 +48,8 @@ Source: Roslyn's [`UseTwiceRewriter.vb`](https://github.com/dotnet/roslyn/blob/m | `cells(NextIndex()).Text`, `GetHolder().Cell.Text` (`Cell` is a structure) | `var tmp = NextIndex();` … `cells[tmp].Text = arg`, `var tmp = GetHolder();` … `tmp.Cell.Text = arg`: a structure variable is written in place (`ByRefTargetTemporaries.HoistInstance`) | Known gaps: -* A field that the called method itself assigns is read again for the write-back, where VB uses its original value. Detecting it needs analysis of the callee. +* A field that the called method itself assigns is read again for the write-back, where VB uses its original value. Detecting it needs analysis of the callee. (The container of an element access is always copied, so `Issue567ExtendedAsync`'s reassigned list keeps VB's behaviour.) +* A parameterized property with a `ParamArray` converts to a setter with `params` before the value (CS0231), so it can't be written back. * 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). From 1a94b44280d92a78564ac1f9131dd88f2c8300e6 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 20:41:53 +0000 Subject: [PATCH 21/56] Ask an oracle whether a call may change a field Pure refactor: ByRefTargetTemporaries asks IFieldMutationOracle whether a field read for a ByRef target can change while the call runs. The first implementation keeps the current assumption (it can't), so the next commit can replace it with a whole-compilation analysis, and later a call graph. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- .../CSharp/ByRefArguments/ByRefArgumentHoister.cs | 4 +++- CodeConverter/CSharp/ByRefTargetTemporaries.cs | 14 ++++++++++---- CodeConverter/CSharp/FieldWriteAnalysis.cs | 9 +++++++++ CodeConverter/CSharp/IFieldMutationOracle.cs | 11 +++++++++++ 4 files changed, 33 insertions(+), 5 deletions(-) create mode 100644 CodeConverter/CSharp/FieldWriteAnalysis.cs create mode 100644 CodeConverter/CSharp/IFieldMutationOracle.cs diff --git a/CodeConverter/CSharp/ByRefArguments/ByRefArgumentHoister.cs b/CodeConverter/CSharp/ByRefArguments/ByRefArgumentHoister.cs index bb95c36cd..0509b89ea 100644 --- a/CodeConverter/CSharp/ByRefArguments/ByRefArgumentHoister.cs +++ b/CodeConverter/CSharp/ByRefArguments/ByRefArgumentHoister.cs @@ -9,6 +9,7 @@ internal class ByRefArgumentHoister { private readonly ITypeContext _typeContext; private readonly SemanticModel _semanticModel; + private readonly IFieldMutationOracle _fieldMutations; private CommonConversions CommonConversions { get; } /// @@ -20,6 +21,7 @@ public ByRefArgumentHoister(ITypeContext typeContext, SemanticModel semanticMode { _typeContext = typeContext; _semanticModel = semanticModel; + _fieldMutations = FieldWriteAnalysis.For(semanticModel.Compilation); CommonConversions = commonConversions; } @@ -55,7 +57,7 @@ public CSSyntax.ExpressionSyntax HoistByRefDeclaration(VBSyntax.ExpressionSyntax } if (refType == SemanticModelExtensions.RefConversion.PreAndPostAssignment) { - refLValue = ByRefTargetTemporaries.Hoist(_semanticModel, _typeContext, node, refLValue); + refLValue = ByRefTargetTemporaries.Hoist(_semanticModel, _typeContext, _fieldMutations, node, refLValue); } var withCast = CommonConversions.TypeConversionAnalyzer.AddExplicitConversion(node, refLValue, defaultToCast: refKind != RefKind.None); diff --git a/CodeConverter/CSharp/ByRefTargetTemporaries.cs b/CodeConverter/CSharp/ByRefTargetTemporaries.cs index 8dd46e976..62e94cf71 100644 --- a/CodeConverter/CSharp/ByRefTargetTemporaries.cs +++ b/CodeConverter/CSharp/ByRefTargetTemporaries.cs @@ -18,20 +18,23 @@ internal class ByRefTargetTemporaries { private readonly SemanticModel _semanticModel; private readonly ITypeContext _typeContext; + private readonly IFieldMutationOracle _fieldMutations; private readonly VBSyntax.ExpressionSyntax _vbTarget; private readonly Lazy> _writtenSymbols; - private ByRefTargetTemporaries(SemanticModel semanticModel, ITypeContext typeContext, VBSyntax.ExpressionSyntax vbTarget) + private ByRefTargetTemporaries(SemanticModel semanticModel, ITypeContext typeContext, IFieldMutationOracle fieldMutations, VBSyntax.ExpressionSyntax vbTarget) { _semanticModel = semanticModel; _typeContext = typeContext; + _fieldMutations = fieldMutations; _vbTarget = vbTarget; _writtenSymbols = new Lazy>(GetSymbolsWrittenInEnclosingExpression); } /// The C# target with each part VB evaluates once replaced by a hoisted temporary, where its value could otherwise differ. - public static CSSyntax.ExpressionSyntax Hoist(SemanticModel semanticModel, ITypeContext typeContext, VBSyntax.ExpressionSyntax vbTarget, CSSyntax.ExpressionSyntax csTarget) => - new ByRefTargetTemporaries(semanticModel, typeContext, vbTarget).Hoist(csTarget); + public static CSSyntax.ExpressionSyntax Hoist(SemanticModel semanticModel, ITypeContext typeContext, IFieldMutationOracle fieldMutations, + VBSyntax.ExpressionSyntax vbTarget, CSSyntax.ExpressionSyntax csTarget) => + new ByRefTargetTemporaries(semanticModel, typeContext, fieldMutations, vbTarget).Hoist(csTarget); private CSSyntax.ExpressionSyntax Hoist(CSSyntax.ExpressionSyntax csTarget) { @@ -111,10 +114,13 @@ private CSSyntax.ExpressionSyntax HoistInstance(IOperation instance, CSSyntax.Ex IConversionOperation { OperatorMethod: null } c => IsReusable(c.Operand), ILocalReferenceOperation l => !_writtenSymbols.Value.Contains(l.Local), IParameterReferenceOperation p => !_writtenSymbols.Value.Contains(p.Parameter), - IFieldReferenceOperation f => !_writtenSymbols.Value.Contains(f.Field) && IsReusable(f.Instance), + IFieldReferenceOperation f => !_writtenSymbols.Value.Contains(f.Field) && !_fieldMutations.MayChangeDuringCall(f.Field, GetCall()) && IsReusable(f.Instance), _ => false }; + /// The call (or object creation, or event raise) that the ByRef target is an argument of. + private IOperation GetCall() => _semanticModel.GetOperation(_vbTarget)?.Parent is IArgumentOperation { Parent: var call } ? call : null; + private CSSyntax.ExpressionSyntax HoistValue(CSSyntax.ExpressionSyntax value) => _typeContext.PerScopeState.Hoist(new AdditionalDeclaration("tmp", value, ValidSyntaxFactory.VarType)).IdentifierName; diff --git a/CodeConverter/CSharp/FieldWriteAnalysis.cs b/CodeConverter/CSharp/FieldWriteAnalysis.cs new file mode 100644 index 000000000..972d06714 --- /dev/null +++ b/CodeConverter/CSharp/FieldWriteAnalysis.cs @@ -0,0 +1,9 @@ +namespace ICSharpCode.CodeConverter.CSharp; + +internal class FieldWriteAnalysis : IFieldMutationOracle +{ + public static FieldWriteAnalysis For(Compilation compilation) => new(); + + /// Assumes a called method doesn't assign the fields its caller reads. + public bool MayChangeDuringCall(IFieldSymbol field, IOperation call) => false; +} diff --git a/CodeConverter/CSharp/IFieldMutationOracle.cs b/CodeConverter/CSharp/IFieldMutationOracle.cs new file mode 100644 index 000000000..4b6135d47 --- /dev/null +++ b/CodeConverter/CSharp/IFieldMutationOracle.cs @@ -0,0 +1,11 @@ +namespace ICSharpCode.CodeConverter.CSharp; + +/// +/// Answers whether a field can hold a different value after a call than before it, so the converter knows whether reading it again is safe. +/// +internal interface IFieldMutationOracle +{ + /// The call whose ByRef argument reads the field. Lets an implementation narrow the answer to what that call can reach. + /// False only when the field certainly keeps its value while the call runs. + bool MayChangeDuringCall(IFieldSymbol field, IOperation call); +} From 4eedd831e272f19e5e998b245fa3f5f198490963 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 20:49:40 +0000 Subject: [PATCH 22/56] Copy a ByRef target's field when the call could change it VB evaluates a ByRef property target's receiver and index arguments once, so a field the called method reassigns keeps its old value for the write-back. The converter read such a field again, so e.g. a callee that replaced `_db` made the write-back go to the new object. FieldWriteAnalysis answers IFieldMutationOracle soundly for the whole compilation, once: a field can't change during any call if it's Const or ReadOnly, or if only this compilation can write it and nothing does outside construction of what holds it. Otherwise it's copied to a temporary. The #909 repro's module is now declared as in VB's default (Friend), like the issue's code, which doesn't show it. With a Public module its Public fields could be written by other assemblies, so they'd be copied. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- CodeConverter/CSharp/ByRefArguments/README.md | 9 +- .../CSharp/ByRefTargetTemporaries.cs | 4 +- CodeConverter/CSharp/FieldWriteAnalysis.cs | 138 +++++++++++++++++- Tests/CSharp/ExpressionTests/ByRefTests.cs | 93 +++++++++++- .../VBToCS/ByRefParameterizedPropertyTests.vb | 31 ++++ 5 files changed, 264 insertions(+), 11 deletions(-) diff --git a/CodeConverter/CSharp/ByRefArguments/README.md b/CodeConverter/CSharp/ByRefArguments/README.md index 8c3689c63..79a1b1807 100644 --- a/CodeConverter/CSharp/ByRefArguments/README.md +++ b/CodeConverter/CSharp/ByRefArguments/README.md @@ -34,13 +34,17 @@ The classes in this folder hold the ByRef-specific decisions. The placement mech Source: Roslyn's [`UseTwiceRewriter.vb`](https://github.com/dotnet/roslyn/blob/main/src/Compilers/VisualBasic/Portable/Lowering/UseTwiceRewriter.vb), which `RewriteByRefArgumentWithCopyBack` uses to read the target and then write it with the setter. Behaviour is covered by `Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedProperty*.vb`. * VB evaluates the target's receiver and index arguments once, and the write-back reuses their values. It copies each into a temporary except literals, constants and `Me`. -* The converter hoists a `tmp` only where the second evaluation could give a different value. A local, parameter or field is reused unless the enclosing expression writes it (as a ByRef argument, or in a lambda): `ByRefTargetTemporaries`. +* The converter hoists a `tmp` only where the second evaluation could give a different value: `ByRefTargetTemporaries`. + * A local or parameter is reused unless the enclosing expression writes it (as a ByRef argument, or in a lambda). Nothing else can. + * A field is reused only if, in addition, the call can't change it (`IFieldMutationOracle.MayChangeDuringCall`). `FieldWriteAnalysis` answers that once per compilation, soundly without knowing what the call reaches: a field can't change if it's `Const` or `ReadOnly`, or if only this compilation can write it (it, or a type containing it, is `Private`, or `Friend` with no `InternalsVisibleTo`) and nothing in it writes it outside construction. A write is an assignment, compound assignment, ByRef or late-bound argument, `For`/`For Each` control variable, `ReDim`, `Erase` or `Mid` statement. Construction (a constructor writing its own instance's field, a shared constructor writing a shared field, or a field or property initializer) has finished before anything can read the field, but a lambda in it may run later, so that isn't excluded. A structure field (other than a primitive or enum) is always treated as changeable, since calling a method on it can change it. + * A call graph of method references could narrow this to the fields the call can transitively write. To stay sound it would treat overridable and interface calls as reaching every implementation, delegate invocations and late-bound calls as reaching anything a delegate or late-bound call could, and calls outside the compilation as reaching any field they can see. * A parameterized property (not the default one) becomes `get_X`/`set_X` methods, so its write-back calls the setter with the same index arguments: `ByRefArgumentHoister.CreateWriteBack`, `AdditionalAssignment.ViaSetter`. It takes its place in the call's reversed write-back order like any other. * A `ReadOnly` property isn't written back (`GetRefConversionForExpression`), so it's evaluated once and needs no temporaries. | VB target | C# | |---|---| -| `Qr(i, 2)`, `other.Qr(_index, 2)` | `get_Qr(i, 2)` … `set_Qr(i, 2, arg)` | +| `Qr(i, 2)`, `other.Qr(_index, 2)` (`_index` a `Private` field written only in constructors) | `get_Qr(i, 2)` … `set_Qr(i, 2, arg)` | +| `other.Qr(_writtenElsewhere, 2)`, `other.Qr(PublicIndex, 2)` | `var tmp = _writtenElsewhere;` … `other.set_Qr(tmp, 2, arg)` | | `other.Qr(NextIndex(), 2)` | `var tmp = NextIndex();` … `other.get_Qr(tmp, 2)` … `other.set_Qr(tmp, 2, arg)` | | `GetC().Qr(1, 2)`, `GetC().Plain` | `var tmp = GetC();` … `tmp.set_Qr(1, 2, arg)`, `tmp.Plain = arg` | | `other(NextIndex())` (default property or indexer) | `var tmp = other; var tmp1 = NextIndex();` … `tmp[tmp1] = arg` (the container is always copied, as before) | @@ -48,7 +52,6 @@ Source: Roslyn's [`UseTwiceRewriter.vb`](https://github.com/dotnet/roslyn/blob/m | `cells(NextIndex()).Text`, `GetHolder().Cell.Text` (`Cell` is a structure) | `var tmp = NextIndex();` … `cells[tmp].Text = arg`, `var tmp = GetHolder();` … `tmp.Cell.Text = arg`: a structure variable is written in place (`ByRefTargetTemporaries.HoistInstance`) | Known gaps: -* A field that the called method itself assigns is read again for the write-back, where VB uses its original value. Detecting it needs analysis of the callee. (The container of an element access is always copied, so `Issue567ExtendedAsync`'s reassigned list keeps VB's behaviour.) * A parameterized property with a `ParamArray` converts to a setter with `params` before the value (CS0231), so it can't be written back. * 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. diff --git a/CodeConverter/CSharp/ByRefTargetTemporaries.cs b/CodeConverter/CSharp/ByRefTargetTemporaries.cs index 62e94cf71..2cf932b71 100644 --- a/CodeConverter/CSharp/ByRefTargetTemporaries.cs +++ b/CodeConverter/CSharp/ByRefTargetTemporaries.cs @@ -10,9 +10,9 @@ namespace ICSharpCode.CodeConverter.CSharp; /// The C# read and write-back are separate expressions, so a part that could have a different value the second time is hoisted into a temporary. /// /// -/// VB copies every part except constants and Me. A local, parameter or field gives the same value again unless it's written while the +/// VB copies every part except constants and Me. A local or parameter gives the same value again unless it's written while the /// enclosing expression runs, so it's only copied when that expression writes it (as a ByRef argument, or by assignment in a lambda). -/// A field that the called method itself assigns is still read again: we can't see that cheaply, and it's rare. +/// A field is also copied when the call could change it (). /// internal class ByRefTargetTemporaries { diff --git a/CodeConverter/CSharp/FieldWriteAnalysis.cs b/CodeConverter/CSharp/FieldWriteAnalysis.cs index 972d06714..85c441a55 100644 --- a/CodeConverter/CSharp/FieldWriteAnalysis.cs +++ b/CodeConverter/CSharp/FieldWriteAnalysis.cs @@ -1,9 +1,139 @@ -namespace ICSharpCode.CodeConverter.CSharp; +using System.Runtime.CompilerServices; +using Microsoft.CodeAnalysis.Operations; +using static Microsoft.CodeAnalysis.VisualBasic.VisualBasicExtensions; +namespace ICSharpCode.CodeConverter.CSharp; + +/// +/// Sound without knowing what a call reaches: a field can only change during a call if something can write it after construction. +/// A field keeps its value while any call runs when it's Const or ReadOnly, or when only this compilation can write it +/// and nothing in it does, outside construction of the object (or type) that holds it. +/// +/// +/// Construction is excluded because it has finished before a caller can read the field: a constructor's writes to its own instance's fields, +/// a shared constructor's writes to shared fields, and field initializers (which run as part of those). A lambda in a constructor can run later, so it isn't excluded. +/// Computed once per compilation, on first use. +/// internal class FieldWriteAnalysis : IFieldMutationOracle { - public static FieldWriteAnalysis For(Compilation compilation) => new(); + private static readonly ConditionalWeakTable PerCompilation = new(); + + private readonly Compilation _compilation; + private readonly Lazy> _fieldsWrittenAfterConstruction; + private readonly Lazy _hasFriendAssemblies; + + private FieldWriteAnalysis(Compilation compilation) + { + _compilation = compilation; + _fieldsWrittenAfterConstruction = new Lazy>(FindFieldsWrittenAfterConstruction); + _hasFriendAssemblies = new Lazy(() => compilation.Assembly.GetAttributes() + .Any(a => a.AttributeClass?.Name == nameof(InternalsVisibleToAttribute))); + } + + public static FieldWriteAnalysis For(Compilation compilation) => PerCompilation.GetValue(compilation, c => new FieldWriteAnalysis(c)); + + /// Ignores : a call graph could narrow the answer to the fields the call can transitively write. + public bool MayChangeDuringCall(IFieldSymbol field, IOperation call) + { + field = field.OriginalDefinition; + if (field.IsConst || field.IsReadOnly) return false; + if (CanBeWrittenOutsideCompilation(field) || CanBeMutatedThroughMembers(field)) return true; + return _fieldsWrittenAfterConstruction.Value.Contains(field); + } + + private bool CanBeWrittenOutsideCompilation(IFieldSymbol field) + { + if (!SymbolEqualityComparer.Default.Equals(field.ContainingAssembly, _compilation.Assembly)) return true; + for (ISymbol symbol = field; symbol is not null and not INamespaceSymbol; symbol = symbol.ContainingSymbol) { + switch (symbol.DeclaredAccessibility) { + case Accessibility.Private: + return false; + case Accessibility.Internal or Accessibility.ProtectedAndInternal: + return _hasFriendAssemblies.Value; + } + } + return true; + } + + /// + /// A structure field can be changed by calling a method on it or assigning one of its members, not just by assigning the field. + /// + private static bool CanBeMutatedThroughMembers(IFieldSymbol field) => + field.Type.IsValueType && field.Type.SpecialType == SpecialType.None && field.Type.TypeKind != TypeKind.Enum; + + private HashSet FindFieldsWrittenAfterConstruction() + { + var written = new HashSet(SymbolEqualityComparer.Default); + foreach (var tree in _compilation.SyntaxTrees) { + var semanticModel = _compilation.GetSemanticModel(tree, true); + foreach (var name in tree.GetRoot().DescendantNodes().OfType()) { + if (semanticModel.GetSymbolInfo(name).Symbol is not IFieldSymbol { IsConst: false, IsReadOnly: false } field) continue; + var reference = name.Parent is VBSyntax.MemberAccessExpressionSyntax maes && maes.Name == name ? (SyntaxNode)maes : name; + if (IsWrite(semanticModel, reference) && !IsDuringConstruction(semanticModel, reference, field)) { + written.Add(field.OriginalDefinition); + } + } + } + return written; + } + + private static bool IsWrite(SemanticModel semanticModel, SyntaxNode reference) + { + if (IsWrittenBySyntax(reference)) return true; + var operation = semanticModel.GetOperation(reference); + return operation?.Parent switch { + IAssignmentOperation a => a.Target == operation, + IArgumentOperation a => a.Parameter?.RefKind is not RefKind.None, + IForToLoopOperation l => l.LoopControlVariable == operation, + IForEachLoopOperation l => l.LoopControlVariable == operation, + IReDimClauseOperation => true, + // Late-bound arguments are copied back when the method found at runtime takes them ByRef + IDynamicInvocationOperation or IDynamicIndexerAccessOperation or IDynamicObjectCreationOperation => true, + _ => false + }; + } + + /// + /// Statements whose operation tree doesn't show the field as written. + /// + private static bool IsWrittenBySyntax(SyntaxNode reference) => reference.Parent switch { + VBSyntax.EraseStatementSyntax => true, + VBSyntax.SimpleArgumentSyntax { Parent.Parent: VBSyntax.MidExpressionSyntax mid } arg => mid.ArgumentList.Arguments.First() == arg, + _ => false + }; + + private static bool IsDuringConstruction(SemanticModel semanticModel, SyntaxNode reference, IFieldSymbol field) + { + if (!field.IsStatic && reference is VBSyntax.MemberAccessExpressionSyntax { Expression: not (VBSyntax.MeExpressionSyntax or VBSyntax.MyClassExpressionSyntax) }) { + return false; + } + foreach (var ancestor in reference.Ancestors()) { + switch (ancestor) { + case VBSyntax.LambdaExpressionSyntax: + return false; + case VBSyntax.ConstructorBlockSyntax ctor: + return IsConstructing(semanticModel.GetDeclaredSymbol(ctor.SubNewStatement), field); + case VBSyntax.FieldDeclarationSyntax or VBSyntax.PropertyStatementSyntax: + var containingType = semanticModel.GetDeclaredSymbol(ancestor.FirstAncestorOrSelf()?.BlockStatement); + return SymbolEqualityComparer.Default.Equals(containingType, field.ContainingType) && IsSharedDeclaration(ancestor) == field.IsStatic; + case VBSyntax.MethodBlockBaseSyntax or VBSyntax.TypeBlockSyntax: + return false; + } + } + return false; + } + + private static bool IsConstructing(IMethodSymbol constructor, IFieldSymbol field) => + SymbolEqualityComparer.Default.Equals(constructor?.ContainingType, field.ContainingType) && constructor.IsStatic == field.IsStatic; - /// Assumes a called method doesn't assign the fields its caller reads. - public bool MayChangeDuringCall(IFieldSymbol field, IOperation call) => false; + private static bool IsSharedDeclaration(SyntaxNode declaration) + { + var modifiers = declaration switch { + VBSyntax.FieldDeclarationSyntax f => f.Modifiers, + VBSyntax.PropertyStatementSyntax p => p.Modifiers, + _ => default + }; + return modifiers.Any(m => m.IsKind(VBasic.SyntaxKind.SharedKeyword)) || + declaration.FirstAncestorOrSelf() is VBSyntax.ModuleBlockSyntax; + } } diff --git a/Tests/CSharp/ExpressionTests/ByRefTests.cs b/Tests/CSharp/ExpressionTests/ByRefTests.cs index eded23428..f05159bef 100644 --- a/Tests/CSharp/ExpressionTests/ByRefTests.cs +++ b/Tests/CSharp/ExpressionTests/ByRefTests.cs @@ -1578,7 +1578,7 @@ End Set End Property End Class -Public Module Euro_Str +Module Euro_Str Public Db As New ClsDb Public QAdr As Integer Public CourseBuffer As Integer @@ -1608,7 +1608,7 @@ public void set_Qr(int tableBuffer, int fieldNumber, string value) } } -public static partial class Euro_Str +internal static partial class Euro_Str { public static ClsDb Db = new ClsDb(); public static int QAdr; @@ -1746,6 +1746,95 @@ public void UsesTwice(C other) SetValueAndIndex(ref argvalue5, ref i); other.set_Qr(tmp5, 2, argvalue5); // i is written by the call } +}"); + } + + [Fact] + public async Task ByRefPropertyTargetCopiesOnlyFieldsThatCanChangeAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Public Class Db + Public Property Qr(a As Integer, b As Integer) As String + Get + Return """" + End Get + Set(value As String) + End Set + End Property +End Class + +Public Class Fields + Private ReadOnly _readOnlyIndex As Integer = 1 + Private _neverWritten As Integer + Private _assignedInConstructor As Integer + Private _writtenElsewhere As Integer + Public PublicIndex As Integer + Private _db As New Db + + Public Sub New() + _assignedInConstructor = 2 + End Sub + + Sub Reset() + _writtenElsewhere = 0 + End Sub + + Sub UsesFields() + SetValue(_db.Qr(_readOnlyIndex, _neverWritten)) + SetValue(_db.Qr(_assignedInConstructor, _writtenElsewhere)) + SetValue(_db.Qr(PublicIndex, 1)) + End Sub + + Shared Sub SetValue(ByRef value As String) + End Sub +End Class", @" +public partial class Db +{ + public string get_Qr(int a, int b) + { + return """"; + } + public void set_Qr(int a, int b, string value) + { + } +} + +public partial class Fields +{ + private readonly int _readOnlyIndex = 1; + private int _neverWritten; + private int _assignedInConstructor; + private int _writtenElsewhere; + public int PublicIndex; + private Db _db = new Db(); + + public Fields() + { + _assignedInConstructor = 2; + } + + public void Reset() + { + _writtenElsewhere = 0; + } + + public void UsesFields() + { + string argvalue = _db.get_Qr(_readOnlyIndex, _neverWritten); + SetValue(ref argvalue); + _db.set_Qr(_readOnlyIndex, _neverWritten, argvalue); + var tmp = _writtenElsewhere; + string argvalue1 = _db.get_Qr(_assignedInConstructor, tmp); + SetValue(ref argvalue1); + _db.set_Qr(_assignedInConstructor, tmp, argvalue1); + var tmp1 = PublicIndex; + string argvalue2 = _db.get_Qr(tmp1, 1); + SetValue(ref argvalue2); + _db.set_Qr(tmp1, 1, argvalue2); + } + + public static void SetValue(ref string value) + { + } }"); } } \ No newline at end of file diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb index fc55ef309..962ff255e 100644 --- a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb @@ -5,6 +5,8 @@ Imports Xunit Public Class ByRefParameterizedPropertyTests Private ReadOnly _log As New List(Of String) Private _fieldIndex As Integer = 1 + Private _db As Db + Private _index As Integer = 1 Public Sub ParameterizedPropertyIsWrittenBackThroughItsSetterIssue909() @@ -66,6 +68,35 @@ Public Class ByRefParameterizedPropertyTests Assert.Equal("get 1,21;set 1,21=changed", LogText()) End Sub + + Public Sub FieldReceiverReassignedByTheCalledMethodIsWrittenBackToTheOriginal() + _db = New Db(_log) + Dim original = _db + ReplaceDbAndSetValue(_db.Qr(1, 21)) + Assert.NotSame(original, _db) + Assert.Equal("changed", original.Qr(1, 21)) + Assert.Equal("get 1,21;set 1,21=changed;get 1,21", LogText()) + End Sub + + Private Sub ReplaceDbAndSetValue(ByRef value As String) + _db = New Db(New List(Of String)) + value = "changed" + End Sub + + + Public Sub FieldIndexChangedByTheCalledMethodUsesItsOriginalValue() + Dim db As New Db(_log) + _index = 1 + ChangeIndexAndSetValue(db.Qr(_index, 21)) + Assert.Equal(7, _index) + Assert.Equal("get 1,21;set 1,21=changed", LogText()) + End Sub + + Private Sub ChangeIndexAndSetValue(ByRef value As String) + _index = 7 + value = "changed" + End Sub + Public Sub ReadOnlyParameterizedPropertyIsNotWrittenBack() Dim db As New Db(_log) From 65c25b5879ef57aac9932bb802ad1215ed62958b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 20:56:04 +0000 Subject: [PATCH 23/56] Copy a ByRef target's local when the call could change it Like a field, a local or parameter used as a ByRef target's index was only copied when the enclosing expression wrote it. The call can also change one by running a lambda from the same method that assigns it, or through a ByRef parameter's alias. Copy those too, so the rule is sound. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- CodeConverter/CSharp/ByRefArguments/README.md | 2 +- .../CSharp/ByRefTargetTemporaries.cs | 24 ++++++++++++------- .../VBToCS/ByRefParameterizedPropertyTests.vb | 23 ++++++++++++++++++ 3 files changed, 40 insertions(+), 9 deletions(-) diff --git a/CodeConverter/CSharp/ByRefArguments/README.md b/CodeConverter/CSharp/ByRefArguments/README.md index 79a1b1807..d79fdd978 100644 --- a/CodeConverter/CSharp/ByRefArguments/README.md +++ b/CodeConverter/CSharp/ByRefArguments/README.md @@ -35,7 +35,7 @@ Source: Roslyn's [`UseTwiceRewriter.vb`](https://github.com/dotnet/roslyn/blob/m * VB evaluates the target's receiver and index arguments once, and the write-back reuses their values. It copies each into a temporary except literals, constants and `Me`. * The converter hoists a `tmp` only where the second evaluation could give a different value: `ByRefTargetTemporaries`. - * A local or parameter is reused unless the enclosing expression writes it (as a ByRef argument, or in a lambda). Nothing else can. + * A local or `ByVal` parameter is reused unless the enclosing expression, or any lambda in the same method (the call could run it), writes it. Only those can. A `ByRef` parameter aliases a variable the call might reach, so it's copied. * A field is reused only if, in addition, the call can't change it (`IFieldMutationOracle.MayChangeDuringCall`). `FieldWriteAnalysis` answers that once per compilation, soundly without knowing what the call reaches: a field can't change if it's `Const` or `ReadOnly`, or if only this compilation can write it (it, or a type containing it, is `Private`, or `Friend` with no `InternalsVisibleTo`) and nothing in it writes it outside construction. A write is an assignment, compound assignment, ByRef or late-bound argument, `For`/`For Each` control variable, `ReDim`, `Erase` or `Mid` statement. Construction (a constructor writing its own instance's field, a shared constructor writing a shared field, or a field or property initializer) has finished before anything can read the field, but a lambda in it may run later, so that isn't excluded. A structure field (other than a primitive or enum) is always treated as changeable, since calling a method on it can change it. * A call graph of method references could narrow this to the fields the call can transitively write. To stay sound it would treat overridable and interface calls as reaching every implementation, delegate invocations and late-bound calls as reaching anything a delegate or late-bound call could, and calls outside the compilation as reaching any field they can see. * A parameterized property (not the default one) becomes `get_X`/`set_X` methods, so its write-back calls the setter with the same index arguments: `ByRefArgumentHoister.CreateWriteBack`, `AdditionalAssignment.ViaSetter`. It takes its place in the call's reversed write-back order like any other. diff --git a/CodeConverter/CSharp/ByRefTargetTemporaries.cs b/CodeConverter/CSharp/ByRefTargetTemporaries.cs index 2cf932b71..bf8ff9ced 100644 --- a/CodeConverter/CSharp/ByRefTargetTemporaries.cs +++ b/CodeConverter/CSharp/ByRefTargetTemporaries.cs @@ -10,8 +10,8 @@ namespace ICSharpCode.CodeConverter.CSharp; /// The C# read and write-back are separate expressions, so a part that could have a different value the second time is hoisted into a temporary. /// /// -/// VB copies every part except constants and Me. A local or parameter gives the same value again unless it's written while the -/// enclosing expression runs, so it's only copied when that expression writes it (as a ByRef argument, or by assignment in a lambda). +/// VB copies every part except constants and Me. A local or ByVal parameter gives the same value again unless it's written while the +/// enclosing expression runs, so it's only copied when that expression, or a lambda the call could run, writes it. /// A field is also copied when the call could change it (). /// internal class ByRefTargetTemporaries @@ -113,7 +113,8 @@ private CSSyntax.ExpressionSyntax HoistInstance(IOperation instance, CSSyntax.Ex IParenthesizedOperation p => IsReusable(p.Operand), IConversionOperation { OperatorMethod: null } c => IsReusable(c.Operand), ILocalReferenceOperation l => !_writtenSymbols.Value.Contains(l.Local), - IParameterReferenceOperation p => !_writtenSymbols.Value.Contains(p.Parameter), + // A ByRef parameter aliases a variable of the caller's, which the call could reach some other way + IParameterReferenceOperation p => p.Parameter.RefKind == RefKind.None && !_writtenSymbols.Value.Contains(p.Parameter), IFieldReferenceOperation f => !_writtenSymbols.Value.Contains(f.Field) && !_fieldMutations.MayChangeDuringCall(f.Field, GetCall()) && IsReusable(f.Instance), _ => false }; @@ -125,7 +126,8 @@ private CSSyntax.ExpressionSyntax HoistValue(CSSyntax.ExpressionSyntax value) => _typeContext.PerScopeState.Hoist(new AdditionalDeclaration("tmp", value, ValidSyntaxFactory.VarType)).IdentifierName; /// - /// The temporaries and write-back are placed around the enclosing expression, so that's what could change a variable in between. + /// The temporaries and write-back are placed around the enclosing expression, so that's what could change a local variable in between. + /// So could any lambda in the same method, since the call could run it. /// private HashSet GetSymbolsWrittenInEnclosingExpression() { @@ -133,14 +135,20 @@ private HashSet GetSymbolsWrittenInEnclosingExpression() while (enclosing.Parent is VBSyntax.ExpressionSyntax or VBSyntax.ArgumentSyntax or VBSyntax.ArgumentListSyntax) { enclosing = enclosing.Parent; } + var lambdasInMember = _vbTarget.Ancestors().LastOrDefault(a => a is VBSyntax.MethodBlockBaseSyntax)?.DescendantNodes().OfType() + ?? Enumerable.Empty(); - var written = _semanticModel.GetOperation(enclosing)?.DescendantsAndSelf().Select(o => o switch { + var written = lambdasInMember.Prepend(enclosing) + .SelectMany(GetVariablesWrittenIn); + return new HashSet(written, SymbolEqualityComparer.Default); + } + + private IEnumerable GetVariablesWrittenIn(SyntaxNode node) => + _semanticModel.GetOperation(node)?.DescendantsAndSelf().Select(o => o switch { IArgumentOperation { Parameter.RefKind: not RefKind.None } a => a.Value, IAssignmentOperation a => a.Target, _ => null - }).Select(GetReferencedVariable).Where(s => s != null); - return new HashSet(written ?? Enumerable.Empty(), SymbolEqualityComparer.Default); - } + }).Select(GetReferencedVariable).Where(s => s != null) ?? Enumerable.Empty(); private static ISymbol GetReferencedVariable(IOperation operation) => operation switch { ILocalReferenceOperation l => l.Local, diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb index 962ff255e..9473ced80 100644 --- a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb @@ -97,6 +97,29 @@ Public Class ByRefParameterizedPropertyTests value = "changed" End Sub + + Public Sub LocalIndexChangedByALambdaTheCalledMethodRunsUsesItsOriginalValue() + Dim db As New Db(_log) + Dim index = 1 + Dim changeIndex As Action = Sub() index = 7 + SetValueAndRun(db.Qr(index, 21), changeIndex) + Assert.Equal(7, index) + Assert.Equal("get 1,21;set 1,21=changed", LogText()) + End Sub + + + Public Sub ByRefParameterIndexChangedByTheCalledMethodUsesItsOriginalValue() + _index = 1 + SetValueIndexedBy(_index) + Assert.Equal(7, _index) + Assert.Equal("get 1,21;set 1,21=changed", LogText()) + End Sub + + Private Sub SetValueIndexedBy(ByRef index As Integer) + Dim db As New Db(_log) + ChangeIndexAndSetValue(db.Qr(index, 21)) + End Sub + Public Sub ReadOnlyParameterizedPropertyIsNotWrittenBack() Dim db As New Db(_log) From 8a399a94ffee5eb2b11f93b9810a70f85bcff6e9 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 20:56:24 +0000 Subject: [PATCH 24/56] Document late-bound ByRef parameterized properties as a gap Found in review: a late-bound `o.Qr(1)` passed ByRef converts to a dynamic method call that throws at runtime, and isn't written back. A fix needs the late-binding helpers for both the read and the write-back, so it's left out. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- CodeConverter/CSharp/ByRefArguments/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CodeConverter/CSharp/ByRefArguments/README.md b/CodeConverter/CSharp/ByRefArguments/README.md index d79fdd978..666944937 100644 --- a/CodeConverter/CSharp/ByRefArguments/README.md +++ b/CodeConverter/CSharp/ByRefArguments/README.md @@ -53,6 +53,7 @@ Source: Roslyn's [`UseTwiceRewriter.vb`](https://github.com/dotnet/roslyn/blob/m Known gaps: * A parameterized property with a `ParamArray` converts to a setter with `params` before the value (CS0231), so it can't be written back. +* A late-bound parameterized property (`SetValue(o.Qr(1))` with `o As Object`) converts to `((dynamic)o).Qr(1)`, which throws `RuntimeBinderException`, and isn't written back. VB reads and writes it through `NewLateBinding.LateGet`/`LateSet` (or `LateIndexGet`/`LateIndexSet`). * 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). From 5a46f1b7fc09206dae6a6ca7692c78b9401e3c9a Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 21:02:34 +0000 Subject: [PATCH 25/56] Test which field writes make a ByRef target copy the field Pins each kind of write FieldWriteAnalysis looks for, and each kind of construction it allows, found untested by coverage. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- Tests/CSharp/ExpressionTests/ByRefTests.cs | 216 +++++++++++++++++++++ 1 file changed, 216 insertions(+) diff --git a/Tests/CSharp/ExpressionTests/ByRefTests.cs b/Tests/CSharp/ExpressionTests/ByRefTests.cs index f05159bef..d810c01d1 100644 --- a/Tests/CSharp/ExpressionTests/ByRefTests.cs +++ b/Tests/CSharp/ExpressionTests/ByRefTests.cs @@ -1837,4 +1837,220 @@ public static void SetValue(ref string value) } }"); } + + [Fact] + public async Task ByRefPropertyTargetCopiesFieldsWrittenAfterConstructionAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Option Strict Off + +Public Class Db + Public Property Qr(a As Object) As String + Get + Return """" + End Get + Set(value As String) + End Set + End Property +End Class + +Public Structure Point + Public X As Integer +End Structure + +Public Class C + Private _forVar As Integer + Private _forEachVar As Integer + Private _reDimmed As Integer() + Private _erased As Integer() + Private _midText As String + Private _lateBoundArg As Integer + Private _writtenInConstructorLambda As Integer + Private _writtenOnOtherInstance As Integer + Private Shared _sharedWrittenInInstanceConstructor As Integer + Private _byInitializer As Integer + Private _initialized As Integer = Inc(_byInitializer) + Private Shared _sharedByInitializer As Integer + Private Shared _sharedInitialized As Integer = Inc(_sharedByInitializer) + Private Shared _sharedInSharedConstructor As Integer + Friend _friendNeverWritten As Integer + Private _point As Point + Private ReadOnly _db As New Db + + Shared Sub New() + _sharedInSharedConstructor = 1 + End Sub + + Public Sub New(other As C) + Dim a As Action = Sub() _writtenInConstructorLambda = 1 + other._writtenOnOtherInstance = 1 + _sharedWrittenInInstanceConstructor = 1 + End Sub + + Sub Writes(o As Object) + For _forVar = 1 To 2 + Next + For Each _forEachVar In {1} + Next + ReDim _reDimmed(3) + Erase _erased + Mid(_midText, 1) = ""x"" + o.Foo(_lateBoundArg) + End Sub + + Sub UsesFields() + SetValue(_db.Qr(_forVar)) + SetValue(_db.Qr(_forEachVar)) + SetValue(_db.Qr(_reDimmed)) + SetValue(_db.Qr(_erased)) + SetValue(_db.Qr(_midText)) + SetValue(_db.Qr(_lateBoundArg)) + SetValue(_db.Qr(_writtenInConstructorLambda)) + SetValue(_db.Qr(_writtenOnOtherInstance)) + SetValue(_db.Qr(_sharedWrittenInInstanceConstructor)) + SetValue(_db.Qr(_byInitializer)) ' Reused from here on + SetValue(_db.Qr(_sharedByInitializer)) + SetValue(_db.Qr(_sharedInSharedConstructor)) + SetValue(_db.Qr(_friendNeverWritten)) + SetValue(_db.Qr(_point)) ' A structure can change without being assigned + End Sub + + Shared Function Inc(ByRef x As Integer) As Integer + x += 1 + Return x + End Function + + Shared Sub SetValue(ByRef value As String) + End Sub +End Class", @"using System; +using Microsoft.VisualBasic.CompilerServices; // Install-Package Microsoft.VisualBasic + +public partial class Db +{ + public string get_Qr(object a) + { + return """"; + } + public void set_Qr(object a, string value) + { + } +} + +public partial struct Point +{ + public int X; +} + +public partial class C +{ + private int _forVar; + private int _forEachVar; + private int[] _reDimmed; + private int[] _erased; + private string _midText; + private int _lateBoundArg; + private int _writtenInConstructorLambda; + private int _writtenOnOtherInstance; + private static int _sharedWrittenInInstanceConstructor; + private int _byInitializer; + private int _initialized; + private static int _sharedByInitializer; + private static int _sharedInitialized = Inc(ref _sharedByInitializer); + private static int _sharedInSharedConstructor; + internal int _friendNeverWritten; + private Point _point; + private readonly Db _db = new Db(); + + static C() + { + _sharedInSharedConstructor = 1; + } + + public C(C other) + { + _initialized = Inc(ref _byInitializer); + Action a = () => _writtenInConstructorLambda = 1; + other._writtenOnOtherInstance = 1; + _sharedWrittenInInstanceConstructor = 1; + } + + public void Writes(object o) + { + for (_forVar = 1; _forVar <= 2; _forVar++) + { + } + foreach (var current_forEachVar in new[] { 1 }) + _forEachVar = current_forEachVar; + _reDimmed = new int[4]; + _erased = null; + StringType.MidStmtStr(ref _midText, 1, ""x"".Length, ""x""); + ((dynamic)o).Foo(_lateBoundArg); + } + + public void UsesFields() + { + var tmp = _forVar; + string argvalue = _db.get_Qr(tmp); + SetValue(ref argvalue); + _db.set_Qr(tmp, argvalue); + var tmp1 = _forEachVar; + string argvalue1 = _db.get_Qr(tmp1); + SetValue(ref argvalue1); + _db.set_Qr(tmp1, argvalue1); + var tmp2 = _reDimmed; + string argvalue2 = _db.get_Qr(tmp2); + SetValue(ref argvalue2); + _db.set_Qr(tmp2, argvalue2); + var tmp3 = _erased; + string argvalue3 = _db.get_Qr(tmp3); + SetValue(ref argvalue3); + _db.set_Qr(tmp3, argvalue3); + var tmp4 = _midText; + string argvalue4 = _db.get_Qr(tmp4); + SetValue(ref argvalue4); + _db.set_Qr(tmp4, argvalue4); + var tmp5 = _lateBoundArg; + string argvalue5 = _db.get_Qr(tmp5); + SetValue(ref argvalue5); + _db.set_Qr(tmp5, argvalue5); + var tmp6 = _writtenInConstructorLambda; + string argvalue6 = _db.get_Qr(tmp6); + SetValue(ref argvalue6); + _db.set_Qr(tmp6, argvalue6); + var tmp7 = _writtenOnOtherInstance; + string argvalue7 = _db.get_Qr(tmp7); + SetValue(ref argvalue7); + _db.set_Qr(tmp7, argvalue7); + var tmp8 = _sharedWrittenInInstanceConstructor; + string argvalue8 = _db.get_Qr(tmp8); + SetValue(ref argvalue8); + _db.set_Qr(tmp8, argvalue8); + string argvalue9 = _db.get_Qr(_byInitializer); + SetValue(ref argvalue9); + _db.set_Qr(_byInitializer, argvalue9); // Reused from here on + string argvalue10 = _db.get_Qr(_sharedByInitializer); + SetValue(ref argvalue10); + _db.set_Qr(_sharedByInitializer, argvalue10); + string argvalue11 = _db.get_Qr(_sharedInSharedConstructor); + SetValue(ref argvalue11); + _db.set_Qr(_sharedInSharedConstructor, argvalue11); + string argvalue12 = _db.get_Qr(_friendNeverWritten); + SetValue(ref argvalue12); + _db.set_Qr(_friendNeverWritten, argvalue12); + var tmp9 = _point; + string argvalue13 = _db.get_Qr(tmp9); + SetValue(ref argvalue13); + _db.set_Qr(tmp9, argvalue13); // A structure can change without being assigned + } + + public static int Inc(ref int x) + { + x += 1; + return x; + } + + public static void SetValue(ref string value) + { + } +}"); + } } \ No newline at end of file From 95006f3cdd74df3601526875f9d116f98841865d Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 21:05:32 +0000 Subject: [PATCH 26/56] Test a ByRef setter write-back before an assignment replaces its target `index = F(db.Qr(index, 21))` and `db = F(db.Qr(1, 21))`: VB writes back through the index and receiver as they were before the assignment. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- .../VBToCS/ByRefParameterizedPropertyTests.vb | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb index 9473ced80..d94e8007c 100644 --- a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb @@ -120,6 +120,35 @@ Public Class ByRefParameterizedPropertyTests ChangeIndexAndSetValue(db.Qr(index, 21)) End Sub + + Public Sub AssignedIndexIsWrittenBackWithItsOriginalValue() + Dim db As New Db(_log) + Dim index = 1 + index = SetValueReturnFive(db.Qr(index, 21)) + Assert.Equal(5, index) + Assert.Equal("get 1,21;set 1,21=changed", LogText()) + End Sub + + Private Shared Function SetValueReturnFive(ByRef value As String) As Integer + value = "changed" + Return 5 + End Function + + + Public Sub AssignedReceiverIsWrittenBackToTheOriginal() + Dim db As New Db(_log) + Dim original = db + db = SetValueReturnNewDb(db.Qr(1, 21)) + Assert.NotSame(original, db) + Assert.Equal("changed", original.Qr(1, 21)) + Assert.Equal("get 1,21;set 1,21=changed;get 1,21", LogText()) + End Sub + + Private Shared Function SetValueReturnNewDb(ByRef value As String) As Db + value = "changed" + Return New Db(New List(Of String)) + End Function + Public Sub ReadOnlyParameterizedPropertyIsNotWrittenBack() Dim db As New Db(_log) From c1e0cf449dfad527973858b48d3c1acf57ad5da9 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 21:49:38 +0000 Subject: [PATCH 27/56] Move the ByRef target temporaries and field analysis into ByRefArguments Pure move, next to ByRefArgumentHoister, which is their only user. Their README section already lives in ByRefArguments/README.md. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- .../CSharp/{ => ByRefArguments}/ByRefTargetTemporaries.cs | 2 +- CodeConverter/CSharp/{ => ByRefArguments}/FieldWriteAnalysis.cs | 2 +- .../CSharp/{ => ByRefArguments}/IFieldMutationOracle.cs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) rename CodeConverter/CSharp/{ => ByRefArguments}/ByRefTargetTemporaries.cs (99%) rename CodeConverter/CSharp/{ => ByRefArguments}/FieldWriteAnalysis.cs (99%) rename CodeConverter/CSharp/{ => ByRefArguments}/IFieldMutationOracle.cs (89%) diff --git a/CodeConverter/CSharp/ByRefTargetTemporaries.cs b/CodeConverter/CSharp/ByRefArguments/ByRefTargetTemporaries.cs similarity index 99% rename from CodeConverter/CSharp/ByRefTargetTemporaries.cs rename to CodeConverter/CSharp/ByRefArguments/ByRefTargetTemporaries.cs index bf8ff9ced..d4b51cc13 100644 --- a/CodeConverter/CSharp/ByRefTargetTemporaries.cs +++ b/CodeConverter/CSharp/ByRefArguments/ByRefTargetTemporaries.cs @@ -1,7 +1,7 @@ using System.Collections.Immutable; using Microsoft.CodeAnalysis.Operations; -namespace ICSharpCode.CodeConverter.CSharp; +namespace ICSharpCode.CodeConverter.CSharp.ByRefArguments; /// /// A ByRef argument that VB copies back is used twice: read before the call, and written after it. diff --git a/CodeConverter/CSharp/FieldWriteAnalysis.cs b/CodeConverter/CSharp/ByRefArguments/FieldWriteAnalysis.cs similarity index 99% rename from CodeConverter/CSharp/FieldWriteAnalysis.cs rename to CodeConverter/CSharp/ByRefArguments/FieldWriteAnalysis.cs index 85c441a55..cc21c9f32 100644 --- a/CodeConverter/CSharp/FieldWriteAnalysis.cs +++ b/CodeConverter/CSharp/ByRefArguments/FieldWriteAnalysis.cs @@ -2,7 +2,7 @@ using Microsoft.CodeAnalysis.Operations; using static Microsoft.CodeAnalysis.VisualBasic.VisualBasicExtensions; -namespace ICSharpCode.CodeConverter.CSharp; +namespace ICSharpCode.CodeConverter.CSharp.ByRefArguments; /// /// Sound without knowing what a call reaches: a field can only change during a call if something can write it after construction. diff --git a/CodeConverter/CSharp/IFieldMutationOracle.cs b/CodeConverter/CSharp/ByRefArguments/IFieldMutationOracle.cs similarity index 89% rename from CodeConverter/CSharp/IFieldMutationOracle.cs rename to CodeConverter/CSharp/ByRefArguments/IFieldMutationOracle.cs index 4b6135d47..84a9a9fdd 100644 --- a/CodeConverter/CSharp/IFieldMutationOracle.cs +++ b/CodeConverter/CSharp/ByRefArguments/IFieldMutationOracle.cs @@ -1,4 +1,4 @@ -namespace ICSharpCode.CodeConverter.CSharp; +namespace ICSharpCode.CodeConverter.CSharp.ByRefArguments; /// /// Answers whether a field can hold a different value after a call than before it, so the converter knows whether reading it again is safe. From 45e5cb4f41457b8c344cc52413d195f8243f873d Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 22:31:25 +0000 Subject: [PATCH 28/56] Extract what counts as writing a variable Pure refactor: FieldWriteAnalysis's list of VB constructs that store to a variable moves to VariableWrites, so ByRefTargetTemporaries can use the same one for locals. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- .../ByRefArguments/FieldWriteAnalysis.cs | 28 ++--------------- .../CSharp/ByRefArguments/VariableWrites.cs | 30 +++++++++++++++++++ 2 files changed, 32 insertions(+), 26 deletions(-) create mode 100644 CodeConverter/CSharp/ByRefArguments/VariableWrites.cs diff --git a/CodeConverter/CSharp/ByRefArguments/FieldWriteAnalysis.cs b/CodeConverter/CSharp/ByRefArguments/FieldWriteAnalysis.cs index cc21c9f32..4545b4055 100644 --- a/CodeConverter/CSharp/ByRefArguments/FieldWriteAnalysis.cs +++ b/CodeConverter/CSharp/ByRefArguments/FieldWriteAnalysis.cs @@ -69,7 +69,8 @@ private HashSet FindFieldsWrittenAfterConstruction() foreach (var name in tree.GetRoot().DescendantNodes().OfType()) { if (semanticModel.GetSymbolInfo(name).Symbol is not IFieldSymbol { IsConst: false, IsReadOnly: false } field) continue; var reference = name.Parent is VBSyntax.MemberAccessExpressionSyntax maes && maes.Name == name ? (SyntaxNode)maes : name; - if (IsWrite(semanticModel, reference) && !IsDuringConstruction(semanticModel, reference, field)) { + if (semanticModel.GetOperation(reference) is { } operation && VariableWrites.IsWrite(operation) && + !IsDuringConstruction(semanticModel, reference, field)) { written.Add(field.OriginalDefinition); } } @@ -77,31 +78,6 @@ private HashSet FindFieldsWrittenAfterConstruction() return written; } - private static bool IsWrite(SemanticModel semanticModel, SyntaxNode reference) - { - if (IsWrittenBySyntax(reference)) return true; - var operation = semanticModel.GetOperation(reference); - return operation?.Parent switch { - IAssignmentOperation a => a.Target == operation, - IArgumentOperation a => a.Parameter?.RefKind is not RefKind.None, - IForToLoopOperation l => l.LoopControlVariable == operation, - IForEachLoopOperation l => l.LoopControlVariable == operation, - IReDimClauseOperation => true, - // Late-bound arguments are copied back when the method found at runtime takes them ByRef - IDynamicInvocationOperation or IDynamicIndexerAccessOperation or IDynamicObjectCreationOperation => true, - _ => false - }; - } - - /// - /// Statements whose operation tree doesn't show the field as written. - /// - private static bool IsWrittenBySyntax(SyntaxNode reference) => reference.Parent switch { - VBSyntax.EraseStatementSyntax => true, - VBSyntax.SimpleArgumentSyntax { Parent.Parent: VBSyntax.MidExpressionSyntax mid } arg => mid.ArgumentList.Arguments.First() == arg, - _ => false - }; - private static bool IsDuringConstruction(SemanticModel semanticModel, SyntaxNode reference, IFieldSymbol field) { if (!field.IsStatic && reference is VBSyntax.MemberAccessExpressionSyntax { Expression: not (VBSyntax.MeExpressionSyntax or VBSyntax.MyClassExpressionSyntax) }) { diff --git a/CodeConverter/CSharp/ByRefArguments/VariableWrites.cs b/CodeConverter/CSharp/ByRefArguments/VariableWrites.cs new file mode 100644 index 000000000..53300edc8 --- /dev/null +++ b/CodeConverter/CSharp/ByRefArguments/VariableWrites.cs @@ -0,0 +1,30 @@ +using Microsoft.CodeAnalysis.Operations; + +namespace ICSharpCode.CodeConverter.CSharp.ByRefArguments; + +/// +/// Every VB construct that stores to a variable (local, parameter or field), so analyses that ask "can this change?" agree on what a write is. +/// +internal static class VariableWrites +{ + /// A local, parameter or field reference. + public static bool IsWrite(IOperation reference) => IsWrittenBySyntax(reference.Syntax) || reference.Parent switch { + IAssignmentOperation a => a.Target == reference, + IArgumentOperation a => a.Parameter?.RefKind is not RefKind.None, + IForToLoopOperation l => l.LoopControlVariable == reference, + IForEachLoopOperation l => l.LoopControlVariable == reference, + IReDimClauseOperation => true, + // Late-bound arguments are copied back when the method found at runtime takes them ByRef + IDynamicInvocationOperation or IDynamicIndexerAccessOperation or IDynamicObjectCreationOperation => true, + _ => false + }; + + /// + /// Statements whose operation tree doesn't show the variable as written. + /// + private static bool IsWrittenBySyntax(SyntaxNode reference) => reference.Parent switch { + VBSyntax.EraseStatementSyntax => true, + VBSyntax.SimpleArgumentSyntax { Parent.Parent: VBSyntax.MidExpressionSyntax mid } arg => mid.ArgumentList.Arguments.First() == arg, + _ => false + }; +} From 70c4196224175fc2f8c6b5a1990d30f3f5e3a53a Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 22:35:38 +0000 Subject: [PATCH 29/56] Test more ByRef property targets that coverage showed untested A Shared parameterized property, a structure field receiver of a parameterized property, a structure returned by a function (copied, like VB), a target in a field initializer, Friend fields with InternalsVisibleTo, and a shared field written by another type's constructor. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- Tests/CSharp/ExpressionTests/ByRefTests.cs | 86 +++++++++++++++++++ .../VBToCS/ByRefParameterizedPropertyTests.vb | 68 +++++++++++++++ 2 files changed, 154 insertions(+) diff --git a/Tests/CSharp/ExpressionTests/ByRefTests.cs b/Tests/CSharp/ExpressionTests/ByRefTests.cs index d810c01d1..3a482d0c7 100644 --- a/Tests/CSharp/ExpressionTests/ByRefTests.cs +++ b/Tests/CSharp/ExpressionTests/ByRefTests.cs @@ -2053,4 +2053,90 @@ public static void SetValue(ref string value) } }"); } + + [Fact] + public async Task ByRefPropertyTargetCopiesFriendFieldsVisibleToFriendAssembliesAsync() + { + await TestConversionVisualBasicToCSharpAsync(@" + +Public Class Db + Public Property Qr(a As Integer) As String + Get + Return """" + End Get + Set(value As String) + End Set + End Property +End Class + +Public Class C + Friend _friendNeverWritten As Integer + Private _privateNeverWritten As Integer + Private Shared _sharedWrittenByAnotherTypesConstructor As Integer + Private ReadOnly _db As New Db + + Private Class Other + Sub New() + C._sharedWrittenByAnotherTypesConstructor = 1 + End Sub + End Class + + Sub UsesFields() + SetValue(_db.Qr(_friendNeverWritten)) + SetValue(_db.Qr(_privateNeverWritten)) + SetValue(_db.Qr(_sharedWrittenByAnotherTypesConstructor)) + End Sub + + Shared Sub SetValue(ByRef value As String) + End Sub +End Class", @"using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo(""Other"")] + +public partial class Db +{ + public string get_Qr(int a) + { + return """"; + } + public void set_Qr(int a, string value) + { + } +} + +public partial class C +{ + internal int _friendNeverWritten; + private int _privateNeverWritten; + private static int _sharedWrittenByAnotherTypesConstructor; + private readonly Db _db = new Db(); + + private partial class Other + { + public Other() + { + _sharedWrittenByAnotherTypesConstructor = 1; + } + } + + public void UsesFields() + { + var tmp = _friendNeverWritten; + string argvalue = _db.get_Qr(tmp); + SetValue(ref argvalue); + _db.set_Qr(tmp, argvalue); + string argvalue1 = _db.get_Qr(_privateNeverWritten); + SetValue(ref argvalue1); + _db.set_Qr(_privateNeverWritten, argvalue1); + var tmp1 = _sharedWrittenByAnotherTypesConstructor; + string argvalue2 = _db.get_Qr(tmp1); + SetValue(ref argvalue2); + _db.set_Qr(tmp1, argvalue2); + } + + public static void SetValue(ref string value) + { + } +}"); + } } \ No newline at end of file diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb index d94e8007c..33aa693cc 100644 --- a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb @@ -149,6 +149,62 @@ Public Class ByRefParameterizedPropertyTests Return New Db(New List(Of String)) End Function + + Public Sub SharedParameterizedPropertyIsWrittenBackThroughItsSetter() + Db.SharedLog = _log + SetValue(Db.SharedQr(NextIndex())) + Assert.Equal("index 1;shared get 1;shared set 1=changed", LogText()) + End Sub + + Private _table As Table + + + Public Sub StructureFieldReceiverOfAParameterizedPropertyIsWrittenInPlace() + SetValue(_table.Cell(NextIndex())) + Assert.Equal("1=changed", _table.Last) + End Sub + + + Public Sub StructureReturnedByAFunctionIsWrittenBackToItsCopy() + SetValue(GetCell().Text) + Assert.Equal("cell", LogText()) + End Sub + + Private Function GetCell() As Cell + _log.Add("cell") + Return New Cell + End Function + + + Public Sub ByRefTargetInAFieldInitializerIsEvaluatedOnce() + Dim initialized As New Initialized + Assert.Equal("changed", initialized.Value) + Assert.Equal("index 1;get 1,1;set 1,1=changed", String.Join(";", initialized.Log)) + End Sub + + Private Class Initialized + Public ReadOnly Log As New List(Of String) + Private ReadOnly _db As New Db(Log) + Public Value As String = SetValue(_db.Qr(NextLoggedIndex(), 1)) + + Private Function NextLoggedIndex() As Integer + Log.Add("index 1") + Return 1 + End Function + End Class + + Private Structure Table + Public Last As String + Public Property Cell(index As Integer) As String + Get + Return Nothing + End Get + Set(value As String) + Last = index & "=" & value + End Set + End Property + End Structure + Public Sub ReadOnlyParameterizedPropertyIsNotWrittenBack() Dim db As New Db(_log) @@ -337,6 +393,18 @@ Public Class ByRefParameterizedPropertyTests End Set End Property + Public Shared SharedLog As List(Of String) + + Public Shared Property SharedQr(index As Integer) As String + Get + SharedLog.Add("shared get " & index) + Return Nothing + End Get + Set(value As String) + SharedLog.Add("shared set " & index & "=" & value) + End Set + End Property + Public Property WithDefault(Optional index As Integer = 7) As String Get _log.Add("get " & index) From 1f631edb7777114064316e59593518cc847a46db Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 22:38:13 +0000 Subject: [PATCH 30/56] Copy a ByRef target's local written by any kind of statement ByRefTargetTemporaries only saw ByRef arguments and assignments, so a lambda the call runs could change an index local with a For loop (or For Each, ReDim, Erase, Mid) and the write-back used the new value. Use the same VariableWrites as FieldWriteAnalysis. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- .../CSharp/ByRefArguments/ByRefTargetTemporaries.cs | 9 ++++----- .../VBToCS/ByRefParameterizedPropertyTests.vb | 13 +++++++++++++ 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/CodeConverter/CSharp/ByRefArguments/ByRefTargetTemporaries.cs b/CodeConverter/CSharp/ByRefArguments/ByRefTargetTemporaries.cs index d4b51cc13..b79f723b7 100644 --- a/CodeConverter/CSharp/ByRefArguments/ByRefTargetTemporaries.cs +++ b/CodeConverter/CSharp/ByRefArguments/ByRefTargetTemporaries.cs @@ -144,11 +144,10 @@ private HashSet GetSymbolsWrittenInEnclosingExpression() } private IEnumerable GetVariablesWrittenIn(SyntaxNode node) => - _semanticModel.GetOperation(node)?.DescendantsAndSelf().Select(o => o switch { - IArgumentOperation { Parameter.RefKind: not RefKind.None } a => a.Value, - IAssignmentOperation a => a.Target, - _ => null - }).Select(GetReferencedVariable).Where(s => s != null) ?? Enumerable.Empty(); + _semanticModel.GetOperation(node)?.DescendantsAndSelf() + .Select(o => (Operation: o, Variable: GetReferencedVariable(o))) + .Where(r => r.Variable != null && VariableWrites.IsWrite(r.Operation)) + .Select(r => r.Variable) ?? Enumerable.Empty(); private static ISymbol GetReferencedVariable(IOperation operation) => operation switch { ILocalReferenceOperation l => l.Local, diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb index 33aa693cc..b35c0b14b 100644 --- a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb @@ -149,6 +149,19 @@ Public Class ByRefParameterizedPropertyTests Return New Db(New List(Of String)) End Function + + Public Sub LocalIndexChangedByALoopInALambdaUsesItsOriginalValue() + Dim db As New Db(_log) + Dim index = 1 + Dim loopOverIndex As Action = Sub() + For index = 5 To 7 + Next + End Sub + SetValueAndRun(db.Qr(index, 1), loopOverIndex) + Assert.Equal(8, index) + Assert.Equal("get 1,1;set 1,1=changed", LogText()) + End Sub + Public Sub SharedParameterizedPropertyIsWrittenBackThroughItsSetter() Db.SharedLog = _log From 222470c796330cf4bc0e6bc46e02c49d6793d901 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 22:40:49 +0000 Subject: [PATCH 31/56] Always copy a Static local used in a ByRef target A Static local outlives the call, like a field, so a recursive call (or any call that reaches its method again) can change it before the write-back. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- .../ByRefArguments/ByRefTargetTemporaries.cs | 3 ++- .../VBToCS/ByRefParameterizedPropertyTests.vb | 15 +++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/CodeConverter/CSharp/ByRefArguments/ByRefTargetTemporaries.cs b/CodeConverter/CSharp/ByRefArguments/ByRefTargetTemporaries.cs index b79f723b7..ca2f7884d 100644 --- a/CodeConverter/CSharp/ByRefArguments/ByRefTargetTemporaries.cs +++ b/CodeConverter/CSharp/ByRefArguments/ByRefTargetTemporaries.cs @@ -112,7 +112,8 @@ private CSSyntax.ExpressionSyntax HoistInstance(IOperation instance, CSSyntax.Ex IInstanceReferenceOperation => true, IParenthesizedOperation p => IsReusable(p.Operand), IConversionOperation { OperatorMethod: null } c => IsReusable(c.Operand), - ILocalReferenceOperation l => !_writtenSymbols.Value.Contains(l.Local), + // A Static local lives as long as its method's object (or type), so another call of the method can change it + ILocalReferenceOperation l => !l.Local.IsStatic && !_writtenSymbols.Value.Contains(l.Local), // A ByRef parameter aliases a variable of the caller's, which the call could reach some other way IParameterReferenceOperation p => p.Parameter.RefKind == RefKind.None && !_writtenSymbols.Value.Contains(p.Parameter), IFieldReferenceOperation f => !_writtenSymbols.Value.Contains(f.Field) && !_fieldMutations.MayChangeDuringCall(f.Field, GetCall()) && IsReusable(f.Instance), diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb index b35c0b14b..81f041220 100644 --- a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb @@ -162,6 +162,21 @@ Public Class ByRefParameterizedPropertyTests Assert.Equal("get 1,1;set 1,1=changed", LogText()) End Sub + + Public Sub StaticLocalIndexChangedByARecursiveCallUsesItsOriginalValue() + Dim db As New Db(_log) + SetWithStaticIndex(db, True) + Assert.Equal("get 1,1;get 2,1;set 2,1=changed;set 1,1=changed", LogText()) + End Sub + + Private Sub SetWithStaticIndex(db As Db, recurse As Boolean) + Static index As Integer = 0 + index += 1 + SetValueAndRun(db.Qr(index, 1), Sub() + If recurse Then SetWithStaticIndex(db, False) + End Sub) + End Sub + Public Sub SharedParameterizedPropertyIsWrittenBackThroughItsSetter() Db.SharedLog = _log From ef133f385aa2d105970258486eace2ef0a6cd03f Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 22:43:21 +0000 Subject: [PATCH 32/56] Treat an auto-property's backing field as changeable VB code can read an auto-property's backing field (`_Idx`) directly, but writes it through the property, which FieldWriteAnalysis doesn't follow, so it looked never written. Copy any field associated with a property, unless it's ReadOnly (a ReadOnly auto-property's backing field). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- .../CSharp/ByRefArguments/FieldWriteAnalysis.cs | 2 ++ .../VBToCS/ByRefParameterizedPropertyTests.vb | 10 ++++++++++ 2 files changed, 12 insertions(+) diff --git a/CodeConverter/CSharp/ByRefArguments/FieldWriteAnalysis.cs b/CodeConverter/CSharp/ByRefArguments/FieldWriteAnalysis.cs index 4545b4055..280bffddd 100644 --- a/CodeConverter/CSharp/ByRefArguments/FieldWriteAnalysis.cs +++ b/CodeConverter/CSharp/ByRefArguments/FieldWriteAnalysis.cs @@ -37,6 +37,8 @@ public bool MayChangeDuringCall(IFieldSymbol field, IOperation call) { field = field.OriginalDefinition; if (field.IsConst || field.IsReadOnly) return false; + // An auto-property's backing field (or a WithEvents variable's) is written through the property, which this doesn't follow + if (field.AssociatedSymbol is IPropertySymbol) return true; if (CanBeWrittenOutsideCompilation(field) || CanBeMutatedThroughMembers(field)) return true; return _fieldsWrittenAfterConstruction.Value.Contains(field); } diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb index 81f041220..3cc8580d0 100644 --- a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb @@ -177,6 +177,16 @@ Public Class ByRefParameterizedPropertyTests End Sub) End Sub + Private Property Idx As Integer = 1 + + + Public Sub AutoPropertyBackingFieldIndexChangedThroughThePropertyUsesItsOriginalValue() + Dim db As New Db(_log) + SetValueAndRun(db.Qr(_Idx, 1), Sub() Idx = 9) + Assert.Equal(9, Idx) + Assert.Equal("get 1,1;set 1,1=changed", LogText()) + End Sub + Public Sub SharedParameterizedPropertyIsWrittenBackThroughItsSetter() Db.SharedLog = _log From 39a43faabf888ef80d329957d2f9c9b947c3f0d7 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 22:48:06 +0000 Subject: [PATCH 33/56] Reuse intrinsic operators on reusable operands in a ByRef target `db.Qr(i + 1, 2)` copied `i + 1` into a temporary. An intrinsic operator gives the same result (or throws the same exception) from the same operands, so evaluating it again is safe. A user-defined operator, or one on Object (late bound, so it can run user code), is still copied. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- .../ByRefArguments/ByRefTargetTemporaries.cs | 6 ++ Tests/CSharp/ExpressionTests/ByRefTests.cs | 69 +++++++++++++++++++ 2 files changed, 75 insertions(+) diff --git a/CodeConverter/CSharp/ByRefArguments/ByRefTargetTemporaries.cs b/CodeConverter/CSharp/ByRefArguments/ByRefTargetTemporaries.cs index ca2f7884d..b36fd08de 100644 --- a/CodeConverter/CSharp/ByRefArguments/ByRefTargetTemporaries.cs +++ b/CodeConverter/CSharp/ByRefArguments/ByRefTargetTemporaries.cs @@ -112,6 +112,10 @@ private CSSyntax.ExpressionSyntax HoistInstance(IOperation instance, CSSyntax.Ex IInstanceReferenceOperation => true, IParenthesizedOperation p => IsReusable(p.Operand), IConversionOperation { OperatorMethod: null } c => IsReusable(c.Operand), + // An intrinsic operator gives the same result (or exception) from the same operands. On Object it's late bound, which can run user code. + IUnaryOperation { OperatorMethod: null } u when !IsObject(u.Operand) => IsReusable(u.Operand), + IBinaryOperation { OperatorMethod: null } b when !IsObject(b.LeftOperand) && !IsObject(b.RightOperand) => + IsReusable(b.LeftOperand) && IsReusable(b.RightOperand), // A Static local lives as long as its method's object (or type), so another call of the method can change it ILocalReferenceOperation l => !l.Local.IsStatic && !_writtenSymbols.Value.Contains(l.Local), // A ByRef parameter aliases a variable of the caller's, which the call could reach some other way @@ -123,6 +127,8 @@ private CSSyntax.ExpressionSyntax HoistInstance(IOperation instance, CSSyntax.Ex /// The call (or object creation, or event raise) that the ByRef target is an argument of. private IOperation GetCall() => _semanticModel.GetOperation(_vbTarget)?.Parent is IArgumentOperation { Parent: var call } ? call : null; + private static bool IsObject(IOperation operand) => operand.Type is null or { SpecialType: SpecialType.System_Object }; + private CSSyntax.ExpressionSyntax HoistValue(CSSyntax.ExpressionSyntax value) => _typeContext.PerScopeState.Hoist(new AdditionalDeclaration("tmp", value, ValidSyntaxFactory.VarType)).IdentifierName; diff --git a/Tests/CSharp/ExpressionTests/ByRefTests.cs b/Tests/CSharp/ExpressionTests/ByRefTests.cs index 3a482d0c7..3f214e682 100644 --- a/Tests/CSharp/ExpressionTests/ByRefTests.cs +++ b/Tests/CSharp/ExpressionTests/ByRefTests.cs @@ -2139,4 +2139,73 @@ public static void SetValue(ref string value) } }"); } + + [Fact] + public async Task ByRefPropertyTargetReusesIntrinsicOperatorsOnReusableOperandsAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Option Strict Off + +Public Structure Money + Public Shared Operator +(a As Money, b As Money) As Integer + Return 0 + End Operator +End Structure + +Public Class C + Public Property Qr(a As Integer, b As Integer) As String + Get + Return """" + End Get + Set(value As String) + End Set + End Property + + Sub UsesOperators(i As Integer, o As Object, m As Money) + SetValue(Qr(i + 1, -i)) + SetValue(Qr(o + 1, 2)) + SetValue(Qr(m + m, 2)) + End Sub + + Shared Sub SetValue(ByRef value As String) + End Sub +End Class", @"using Microsoft.VisualBasic.CompilerServices; // Install-Package Microsoft.VisualBasic + +public partial struct Money +{ + public static int operator +(Money a, Money b) + { + return 0; + } +} + +public partial class C +{ + public string get_Qr(int a, int b) + { + return """"; + } + public void set_Qr(int a, int b, string value) + { + } + + public void UsesOperators(int i, object o, Money m) + { + string argvalue = get_Qr(i + 1, -i); + SetValue(ref argvalue); + set_Qr(i + 1, -i, argvalue); + var tmp = Conversions.ToInteger(Operators.AddObject(o, 1)); + string argvalue1 = get_Qr(tmp, 2); + SetValue(ref argvalue1); + set_Qr(tmp, 2, argvalue1); + var tmp1 = m + m; + string argvalue2 = get_Qr(tmp1, 2); + SetValue(ref argvalue2); + set_Qr(tmp1, 2, argvalue2); + } + + public static void SetValue(ref string value) + { + } +}", incompatibleWithAutomatedCommentTesting: true); // The comment on Option Strict Off is lost before the added using directive + } } \ No newline at end of file From 9f329bce11728eb84cd898937c14b2efde6e242c Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 22:48:41 +0000 Subject: [PATCH 34/56] Document the ByRef target rules found in review Static locals, auto-property backing fields, every kind of write and intrinsic operators. #9's gap about re-evaluating a receiver is fixed here, and two pre-existing gaps are added. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- .../CSharp/ByRefArguments/ByRefTargetTemporaries.cs | 3 ++- CodeConverter/CSharp/ByRefArguments/README.md | 12 +++++++----- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/CodeConverter/CSharp/ByRefArguments/ByRefTargetTemporaries.cs b/CodeConverter/CSharp/ByRefArguments/ByRefTargetTemporaries.cs index b36fd08de..94ad10cb6 100644 --- a/CodeConverter/CSharp/ByRefArguments/ByRefTargetTemporaries.cs +++ b/CodeConverter/CSharp/ByRefArguments/ByRefTargetTemporaries.cs @@ -10,9 +10,10 @@ namespace ICSharpCode.CodeConverter.CSharp.ByRefArguments; /// The C# read and write-back are separate expressions, so a part that could have a different value the second time is hoisted into a temporary. /// /// -/// VB copies every part except constants and Me. A local or ByVal parameter gives the same value again unless it's written while the +/// VB copies every part except constants and Me. A (non-Static) local or ByVal parameter gives the same value again unless it's written while the /// enclosing expression runs, so it's only copied when that expression, or a lambda the call could run, writes it. /// A field is also copied when the call could change it (). +/// An intrinsic operator on such parts gives the same value again too. /// internal class ByRefTargetTemporaries { diff --git a/CodeConverter/CSharp/ByRefArguments/README.md b/CodeConverter/CSharp/ByRefArguments/README.md index 666944937..c22fe5632 100644 --- a/CodeConverter/CSharp/ByRefArguments/README.md +++ b/CodeConverter/CSharp/ByRefArguments/README.md @@ -35,15 +35,17 @@ Source: Roslyn's [`UseTwiceRewriter.vb`](https://github.com/dotnet/roslyn/blob/m * VB evaluates the target's receiver and index arguments once, and the write-back reuses their values. It copies each into a temporary except literals, constants and `Me`. * The converter hoists a `tmp` only where the second evaluation could give a different value: `ByRefTargetTemporaries`. - * A local or `ByVal` parameter is reused unless the enclosing expression, or any lambda in the same method (the call could run it), writes it. Only those can. A `ByRef` parameter aliases a variable the call might reach, so it's copied. - * A field is reused only if, in addition, the call can't change it (`IFieldMutationOracle.MayChangeDuringCall`). `FieldWriteAnalysis` answers that once per compilation, soundly without knowing what the call reaches: a field can't change if it's `Const` or `ReadOnly`, or if only this compilation can write it (it, or a type containing it, is `Private`, or `Friend` with no `InternalsVisibleTo`) and nothing in it writes it outside construction. A write is an assignment, compound assignment, ByRef or late-bound argument, `For`/`For Each` control variable, `ReDim`, `Erase` or `Mid` statement. Construction (a constructor writing its own instance's field, a shared constructor writing a shared field, or a field or property initializer) has finished before anything can read the field, but a lambda in it may run later, so that isn't excluded. A structure field (other than a primitive or enum) is always treated as changeable, since calling a method on it can change it. + * A write is anything in `VariableWrites`: an assignment, compound assignment, ByRef or late-bound argument, `For`/`For Each` control variable, `ReDim`, `Erase` or `Mid` statement. + * A local or `ByVal` parameter is reused unless the enclosing expression, or any lambda in the same method (the call could run it), writes it. Only those can. A `ByRef` parameter aliases a variable the call might reach, and a `Static` local outlives the call like a field, so both are copied. + * An intrinsic unary or binary operator on reusable operands is reused: it gives the same result, or throws the same exception, again. A user-defined operator, or one on `Object` (late bound), is copied. + * A field is reused only if, in addition, the call can't change it (`IFieldMutationOracle.MayChangeDuringCall`). `FieldWriteAnalysis` answers that once per compilation, soundly without knowing what the call reaches: a field can't change if it's `Const` or `ReadOnly`, or if only this compilation can write it (it, or a type containing it, is `Private`, or `Friend` with no `InternalsVisibleTo`) and nothing in it writes it outside construction. Construction (a constructor writing its own instance's field, a shared constructor writing a shared field, or a field or property initializer) has finished before anything can read the field, but a lambda in it may run later, so that isn't excluded. A structure field (other than a primitive or enum) is always treated as changeable, since calling a method on it can change it. So is an auto-property's backing field (`_Idx`), which is written through the property. * A call graph of method references could narrow this to the fields the call can transitively write. To stay sound it would treat overridable and interface calls as reaching every implementation, delegate invocations and late-bound calls as reaching anything a delegate or late-bound call could, and calls outside the compilation as reaching any field they can see. * A parameterized property (not the default one) becomes `get_X`/`set_X` methods, so its write-back calls the setter with the same index arguments: `ByRefArgumentHoister.CreateWriteBack`, `AdditionalAssignment.ViaSetter`. It takes its place in the call's reversed write-back order like any other. * A `ReadOnly` property isn't written back (`GetRefConversionForExpression`), so it's evaluated once and needs no temporaries. | VB target | C# | |---|---| -| `Qr(i, 2)`, `other.Qr(_index, 2)` (`_index` a `Private` field written only in constructors) | `get_Qr(i, 2)` … `set_Qr(i, 2, arg)` | +| `Qr(i, 2)`, `Qr(i + 1, -i)`, `other.Qr(_index, 2)` (`_index` a `Private` field written only in constructors) | `get_Qr(i, 2)` … `set_Qr(i, 2, arg)` | | `other.Qr(_writtenElsewhere, 2)`, `other.Qr(PublicIndex, 2)` | `var tmp = _writtenElsewhere;` … `other.set_Qr(tmp, 2, arg)` | | `other.Qr(NextIndex(), 2)` | `var tmp = NextIndex();` … `other.get_Qr(tmp, 2)` … `other.set_Qr(tmp, 2, arg)` | | `GetC().Qr(1, 2)`, `GetC().Plain` | `var tmp = GetC();` … `tmp.set_Qr(1, 2, arg)`, `tmp.Plain = arg` | @@ -52,7 +54,8 @@ Source: Roslyn's [`UseTwiceRewriter.vb`](https://github.com/dotnet/roslyn/blob/m | `cells(NextIndex()).Text`, `GetHolder().Cell.Text` (`Cell` is a structure) | `var tmp = NextIndex();` … `cells[tmp].Text = arg`, `var tmp = GetHolder();` … `tmp.Cell.Text = arg`: a structure variable is written in place (`ByRefTargetTemporaries.HoistInstance`) | Known gaps: -* A parameterized property with a `ParamArray` converts to a setter with `params` before the value (CS0231), so it can't be written back. +* A parameterized property with a `ParamArray` converts to a setter with `params` before the value (`set_PA(params int[] idx, string value)`, CS0231), so it can't be written back. +* An array element whose array isn't a variable, passed to a ByRef parameter of a wider type (`BumpLong(GetArr()(Next1()))` with an `Integer` array and a `ByRef Long` parameter), isn't written back: `IsRefArrayAcces` only treats it as an array element when the array is passed inline. VB writes it back. * A late-bound parameterized property (`SetValue(o.Qr(1))` with `o As Object`) converts to `((dynamic)o).Qr(1)`, which throws `RuntimeBinderException`, and isn't written back. VB reads and writes it through `NewLateBinding.LateGet`/`LateSet` (or `LateIndexGet`/`LateIndexSet`). * 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. @@ -61,7 +64,6 @@ Known gaps: * `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. From 3e1e94a566c3c1df6cad812df8e6bf9d6b0c0adf Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 22:55:07 +0000 Subject: [PATCH 35/56] Test a Shared structure field receiver written in place Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- .../VBToCS/ByRefParameterizedPropertyTests.vb | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb index 3cc8580d0..e1a7933eb 100644 --- a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb @@ -202,6 +202,14 @@ Public Class ByRefParameterizedPropertyTests Assert.Equal("1=changed", _table.Last) End Sub + Private Shared _sharedTable As Table + + + Public Sub SharedStructureFieldReceiverIsWrittenInPlace() + SetValue(_sharedTable.Cell(NextIndex())) + Assert.Equal("1=changed", _sharedTable.Last) + End Sub + Public Sub StructureReturnedByAFunctionIsWrittenBackToItsCopy() SetValue(GetCell().Text) From da61c89b570feda4e752a517ea129bf7834ff1f5 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 23:15:16 +0000 Subject: [PATCH 36/56] Name the setter by renaming the getter call's last identifier Pure refactor: the getter call always arrives qualified (the simplifier reduces it later), so the bare-name and unsupported-shape arms were unreachable. Renaming the rightmost identifier handles any shape without them. Pins a Module's parameterized property, whose converted call is static. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- .../ByRefArguments/ByRefArgumentHoister.cs | 8 +-- Tests/CSharp/ExpressionTests/ByRefTests.cs | 49 +++++++++++++++++++ 2 files changed, 51 insertions(+), 6 deletions(-) diff --git a/CodeConverter/CSharp/ByRefArguments/ByRefArgumentHoister.cs b/CodeConverter/CSharp/ByRefArguments/ByRefArgumentHoister.cs index 0509b89ea..b6e860e24 100644 --- a/CodeConverter/CSharp/ByRefArguments/ByRefArgumentHoister.cs +++ b/CodeConverter/CSharp/ByRefArguments/ByRefArgumentHoister.cs @@ -85,12 +85,8 @@ private AdditionalAssignment CreateWriteBack(VBSyntax.ExpressionSyntax vbTarget, private static CSSyntax.InvocationExpressionSyntax CreateSetterCall(CSSyntax.InvocationExpressionSyntax getterCall, IPropertySymbol property, CSSyntax.ExpressionSyntax value) { - var setterName = ValidSyntaxFactory.IdentifierName(property.SetMethod.Name); - CSSyntax.ExpressionSyntax setter = getterCall.Expression switch { - CSSyntax.MemberAccessExpressionSyntax maes => maes.WithName(setterName), - CSSyntax.SimpleNameSyntax => setterName, - var other => throw new NotSupportedException($"Parameterized property getter call {other.Kind()}") - }; + var getterName = getterCall.Expression.DescendantTokens().Last(t => t.IsKind(CS.SyntaxKind.IdentifierToken)); + var setter = getterCall.Expression.ReplaceToken(getterName, CS.SyntaxFactory.Identifier(property.SetMethod.Name).WithTriviaFrom(getterName)); return CS.SyntaxFactory.InvocationExpression(setter, CommonConversions.AddSetterValueArgument(getterCall.ArgumentList, property, value)); } } diff --git a/Tests/CSharp/ExpressionTests/ByRefTests.cs b/Tests/CSharp/ExpressionTests/ByRefTests.cs index 3f214e682..24eaa052e 100644 --- a/Tests/CSharp/ExpressionTests/ByRefTests.cs +++ b/Tests/CSharp/ExpressionTests/ByRefTests.cs @@ -2208,4 +2208,53 @@ public static void SetValue(ref string value) } }", incompatibleWithAutomatedCommentTesting: true); // The comment on Option Strict Off is lost before the added using directive } + + [Fact] + public async Task ModuleParameterizedPropertyIsWrittenBackThroughItsSetterAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Module M + Private ReadOnly _values As New System.Collections.Generic.Dictionary(Of Integer, String) + + Property Qr(i As Integer) As String + Get + Return _values(i) + End Get + Set(value As String) + _values(i) = value + End Set + End Property + + Sub UsesQr() + SetValue(Qr(1)) + End Sub + + Sub SetValue(ByRef value As String) + End Sub +End Module", @"using System.Collections.Generic; + +internal static partial class M +{ + private readonly static Dictionary _values = new Dictionary(); + + public static string get_Qr(int i) + { + return _values[i]; + } + public static void set_Qr(int i, string value) + { + _values[i] = value; + } + + public static void UsesQr() + { + string argvalue = get_Qr(1); + SetValue(ref argvalue); + set_Qr(1, argvalue); + } + + public static void SetValue(ref string value) + { + } +}"); + } } \ No newline at end of file From d3a4aa2cc78bdfeaa9959a09538835dde14d99a7 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 23:16:01 +0000 Subject: [PATCH 37/56] Make two write-analysis assumptions explicit Pure refactor: an argument without a known parameter counts as a write on purpose, not by `null is not RefKind.None`. IsSharedDeclaration only gets field declarations and property statements, so drop its dead default arm. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- CodeConverter/CSharp/ByRefArguments/FieldWriteAnalysis.cs | 7 ++----- CodeConverter/CSharp/ByRefArguments/VariableWrites.cs | 3 ++- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/CodeConverter/CSharp/ByRefArguments/FieldWriteAnalysis.cs b/CodeConverter/CSharp/ByRefArguments/FieldWriteAnalysis.cs index 280bffddd..11241006b 100644 --- a/CodeConverter/CSharp/ByRefArguments/FieldWriteAnalysis.cs +++ b/CodeConverter/CSharp/ByRefArguments/FieldWriteAnalysis.cs @@ -104,13 +104,10 @@ private static bool IsDuringConstruction(SemanticModel semanticModel, SyntaxNode private static bool IsConstructing(IMethodSymbol constructor, IFieldSymbol field) => SymbolEqualityComparer.Default.Equals(constructor?.ContainingType, field.ContainingType) && constructor.IsStatic == field.IsStatic; + /// A field declaration or property statement. private static bool IsSharedDeclaration(SyntaxNode declaration) { - var modifiers = declaration switch { - VBSyntax.FieldDeclarationSyntax f => f.Modifiers, - VBSyntax.PropertyStatementSyntax p => p.Modifiers, - _ => default - }; + var modifiers = declaration is VBSyntax.FieldDeclarationSyntax f ? f.Modifiers : ((VBSyntax.PropertyStatementSyntax)declaration).Modifiers; return modifiers.Any(m => m.IsKind(VBasic.SyntaxKind.SharedKeyword)) || declaration.FirstAncestorOrSelf() is VBSyntax.ModuleBlockSyntax; } diff --git a/CodeConverter/CSharp/ByRefArguments/VariableWrites.cs b/CodeConverter/CSharp/ByRefArguments/VariableWrites.cs index 53300edc8..64194192d 100644 --- a/CodeConverter/CSharp/ByRefArguments/VariableWrites.cs +++ b/CodeConverter/CSharp/ByRefArguments/VariableWrites.cs @@ -10,7 +10,8 @@ internal static class VariableWrites /// A local, parameter or field reference. public static bool IsWrite(IOperation reference) => IsWrittenBySyntax(reference.Syntax) || reference.Parent switch { IAssignmentOperation a => a.Target == reference, - IArgumentOperation a => a.Parameter?.RefKind is not RefKind.None, + // Without a known parameter (in code that doesn't compile), assume it could be ByRef + IArgumentOperation a => a.Parameter is null || a.Parameter.RefKind != RefKind.None, IForToLoopOperation l => l.LoopControlVariable == reference, IForEachLoopOperation l => l.LoopControlVariable == reference, IReDimClauseOperation => true, From 0b16c8f128ab561b9abe095dc13a78389e382e26 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 23:25:12 +0000 Subject: [PATCH 38/56] Copy a ByRef target's culture-dependent operators and conversions `db.Qs(d & "")` and `db.Qs(CStr(d))` were reused, but formatting a number reads the current culture, which the call can change: VB's setter got "1.5" and the C# one "1,5" after the call switched to de-DE. The same goes for Date conversions, string comparison and Like. Reuse an intrinsic operator or conversion only between numeric, Boolean, Char and enum types (or their nullables), plus identity, widening reference and boxing conversions, which only change the static type. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- .../ByRefArguments/ByRefTargetTemporaries.cs | 27 +++++++++++++---- .../VBToCS/ByRefParameterizedPropertyTests.vb | 30 +++++++++++++++++++ 2 files changed, 52 insertions(+), 5 deletions(-) diff --git a/CodeConverter/CSharp/ByRefArguments/ByRefTargetTemporaries.cs b/CodeConverter/CSharp/ByRefArguments/ByRefTargetTemporaries.cs index 94ad10cb6..49016c1a6 100644 --- a/CodeConverter/CSharp/ByRefArguments/ByRefTargetTemporaries.cs +++ b/CodeConverter/CSharp/ByRefArguments/ByRefTargetTemporaries.cs @@ -112,10 +112,9 @@ private CSSyntax.ExpressionSyntax HoistInstance(IOperation instance, CSSyntax.Ex { ConstantValue.HasValue: true } => true, IInstanceReferenceOperation => true, IParenthesizedOperation p => IsReusable(p.Operand), - IConversionOperation { OperatorMethod: null } c => IsReusable(c.Operand), - // An intrinsic operator gives the same result (or exception) from the same operands. On Object it's late bound, which can run user code. - IUnaryOperation { OperatorMethod: null } u when !IsObject(u.Operand) => IsReusable(u.Operand), - IBinaryOperation { OperatorMethod: null } b when !IsObject(b.LeftOperand) && !IsObject(b.RightOperand) => + IConversionOperation { OperatorMethod: null } c when IsRepeatable(c) => IsReusable(c.Operand), + IUnaryOperation { OperatorMethod: null } u when IsCultureFree(u.Type) && IsCultureFree(u.Operand.Type) => IsReusable(u.Operand), + IBinaryOperation { OperatorMethod: null } b when IsCultureFree(b.Type) && IsCultureFree(b.LeftOperand.Type) && IsCultureFree(b.RightOperand.Type) => IsReusable(b.LeftOperand) && IsReusable(b.RightOperand), // A Static local lives as long as its method's object (or type), so another call of the method can change it ILocalReferenceOperation l => !l.Local.IsStatic && !_writtenSymbols.Value.Contains(l.Local), @@ -128,7 +127,25 @@ private CSSyntax.ExpressionSyntax HoistInstance(IOperation instance, CSSyntax.Ex /// The call (or object creation, or event raise) that the ByRef target is an argument of. private IOperation GetCall() => _semanticModel.GetOperation(_vbTarget)?.Parent is IArgumentOperation { Parent: var call } ? call : null; - private static bool IsObject(IOperation operand) => operand.Type is null or { SpecialType: SpecialType.System_Object }; + /// + /// An intrinsic operator or conversion between these types gives the same result (or exception) from the same operands. + /// One involving String or Date can read the current culture, which the call could change, and one on Object is late bound, which can run user code. + /// + private static bool IsCultureFree(ITypeSymbol type) + { + if (type is INamedTypeSymbol { OriginalDefinition.SpecialType: SpecialType.System_Nullable_T } nullable) type = nullable.TypeArguments[0]; + return type is { TypeKind: TypeKind.Enum } or { SpecialType: SpecialType.System_Boolean or SpecialType.System_Char or SpecialType.System_SByte + or SpecialType.System_Byte or SpecialType.System_Int16 or SpecialType.System_UInt16 or SpecialType.System_Int32 or SpecialType.System_UInt32 + or SpecialType.System_Int64 or SpecialType.System_UInt64 or SpecialType.System_Single or SpecialType.System_Double or SpecialType.System_Decimal }; + } + + /// + /// Besides conversions between culture-free types, a widening reference or boxing conversion only changes the static type. + /// + private static bool IsRepeatable(IConversionOperation conversion) => + conversion.Conversion.IsIdentity || + conversion.Conversion.IsImplicit && (conversion.Conversion.IsReference || conversion.Operand.Type is { IsValueType: true } && conversion.Type is { IsReferenceType: true }) || + IsCultureFree(conversion.Operand.Type) && IsCultureFree(conversion.Type); private CSSyntax.ExpressionSyntax HoistValue(CSSyntax.ExpressionSyntax value) => _typeContext.PerScopeState.Hoist(new AdditionalDeclaration("tmp", value, ValidSyntaxFactory.VarType)).IdentifierName; diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb index e1a7933eb..fa9a1b8d0 100644 --- a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb @@ -187,6 +187,26 @@ Public Class ByRefParameterizedPropertyTests Assert.Equal("get 1,1;set 1,1=changed", LogText()) End Sub + + Public Sub NumberToStringIndexUsesTheCultureBeforeTheCall() + Dim original = Threading.Thread.CurrentThread.CurrentCulture + Try + Threading.Thread.CurrentThread.CurrentCulture = Globalization.CultureInfo.InvariantCulture + Dim db As New Db(_log) + Dim d As Double = 1.5 + SetTwoValuesInGermanCulture(db.Qs(d & ""), db.Qs(CStr(d))) + Assert.Equal("get 1.5;get 1.5;set 1.5=changed;set 1.5=changed", LogText()) + Finally + Threading.Thread.CurrentThread.CurrentCulture = original + End Try + End Sub + + Private Shared Sub SetTwoValuesInGermanCulture(ByRef first As String, ByRef second As String) + Threading.Thread.CurrentThread.CurrentCulture = New Globalization.CultureInfo("de-DE") + first = "changed" + second = "changed" + End Sub + Public Sub SharedParameterizedPropertyIsWrittenBackThroughItsSetter() Db.SharedLog = _log @@ -439,6 +459,16 @@ Public Class ByRefParameterizedPropertyTests End Set End Property + Public Property Qs(key As String) As String + Get + _log.Add("get " & key) + Return Nothing + End Get + Set(value As String) + _log.Add("set " & key & "=" & value) + End Set + End Property + Public Shared SharedLog As List(Of String) Public Shared Property SharedQr(index As Integer) As String From 47bddb04b2d263371b7b65af3a07dd72cca5d21a Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 23:27:42 +0000 Subject: [PATCH 39/56] Look for lambdas that write a local in an initializer's lambda too A ByRef target inside a lambda in a field initializer has no enclosing method block, so no lambda was searched for writes, and a local the call could change through another lambda was reused. Search the outermost enclosing method or lambda, which holds every scope a local can be written in. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- .../ByRefArguments/ByRefTargetTemporaries.cs | 6 ++++-- .../VBToCS/ByRefParameterizedPropertyTests.vb | 17 +++++++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/CodeConverter/CSharp/ByRefArguments/ByRefTargetTemporaries.cs b/CodeConverter/CSharp/ByRefArguments/ByRefTargetTemporaries.cs index 49016c1a6..564e6674a 100644 --- a/CodeConverter/CSharp/ByRefArguments/ByRefTargetTemporaries.cs +++ b/CodeConverter/CSharp/ByRefArguments/ByRefTargetTemporaries.cs @@ -152,7 +152,7 @@ private CSSyntax.ExpressionSyntax HoistValue(CSSyntax.ExpressionSyntax value) => /// /// The temporaries and write-back are placed around the enclosing expression, so that's what could change a local variable in between. - /// So could any lambda in the same method, since the call could run it. + /// So could any lambda in the same method (or, outside a method, in the same outermost lambda), since the call could run it. /// private HashSet GetSymbolsWrittenInEnclosingExpression() { @@ -160,7 +160,9 @@ private HashSet GetSymbolsWrittenInEnclosingExpression() while (enclosing.Parent is VBSyntax.ExpressionSyntax or VBSyntax.ArgumentSyntax or VBSyntax.ArgumentListSyntax) { enclosing = enclosing.Parent; } - var lambdasInMember = _vbTarget.Ancestors().LastOrDefault(a => a is VBSyntax.MethodBlockBaseSyntax)?.DescendantNodes().OfType() + // A local can only be written in the scope that declares it, which is inside the outermost method or lambda + var scopeOfLocals = _vbTarget.Ancestors().LastOrDefault(a => a is VBSyntax.MethodBlockBaseSyntax or VBSyntax.LambdaExpressionSyntax); + var lambdasInMember = scopeOfLocals?.DescendantNodes().OfType() ?? Enumerable.Empty(); var written = lambdasInMember.Prepend(enclosing) diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb index fa9a1b8d0..2ee04bda3 100644 --- a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb @@ -207,6 +207,23 @@ Public Class ByRefParameterizedPropertyTests second = "changed" End Sub + + Public Sub LocalInALambdaInAFieldInitializerChangedByAnotherLambdaUsesItsOriginalValue() + Dim db As New Db(_log) + Dim initialized As New InitializedLambda + initialized.SetThroughLocal(db) + Assert.Equal("get 1,1;set 1,1=changed", LogText()) + End Sub + + Private Class InitializedLambda + Public ReadOnly SetThroughLocal As Func(Of Db, String) = Function(db As Db) + Dim i = 1 + Dim changeIndex As Action = Sub() i = 5 + SetValueAndRun(db.Qr(i, 1), changeIndex) + Return Nothing + End Function + End Class + Public Sub SharedParameterizedPropertyIsWrittenBackThroughItsSetter() Db.SharedLog = _log From 898def8ff861fcf526168c399fd22e79297454eb Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 23:33:41 +0000 Subject: [PATCH 40/56] Test a property passed as a ByRef extension receiver Covers the write-back hoisted outside any argument list. A parameterized property, or a receiver with side effects, as a ByRef extension receiver can't be handled the same way: Roslyn gives that receiver an empty NoneOperation. Documented as a gap. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- CodeConverter/CSharp/ByRefArguments/README.md | 1 + .../VBToCS/ByRefParameterizedPropertyTests.vb | 14 ++++++++++++++ 2 files changed, 15 insertions(+) diff --git a/CodeConverter/CSharp/ByRefArguments/README.md b/CodeConverter/CSharp/ByRefArguments/README.md index c22fe5632..ee8c9cc9b 100644 --- a/CodeConverter/CSharp/ByRefArguments/README.md +++ b/CodeConverter/CSharp/ByRefArguments/README.md @@ -56,6 +56,7 @@ Source: Roslyn's [`UseTwiceRewriter.vb`](https://github.com/dotnet/roslyn/blob/m Known gaps: * A parameterized property with a `ParamArray` converts to a setter with `params` before the value (`set_PA(params int[] idx, string value)`, CS0231), so it can't be written back. * An array element whose array isn't a variable, passed to a ByRef parameter of a wider type (`BumpLong(GetArr()(Next1()))` with an `Integer` array and a `ByRef Long` parameter), isn't written back: `IsRefArrayAcces` only treats it as an array element when the array is passed inline. VB writes it back. +* The receiver of an extension method that takes it ByRef has an empty `NoneOperation` in Roslyn's VB operation tree, so it gets none of the above: a parameterized property there stays `this.Qr(2)` (CS1061), and a receiver like `GetC().Plain` is evaluated twice. A fix would rebuild the target from symbols and syntax. * A late-bound parameterized property (`SetValue(o.Qr(1))` with `o As Object`) converts to `((dynamic)o).Qr(1)`, which throws `RuntimeBinderException`, and isn't written back. VB reads and writes it through `NewLateBinding.LateGet`/`LateSet` (or `LateIndexGet`/`LateIndexSet`). * 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. diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb index 2ee04bda3..d30b449d5 100644 --- a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb @@ -187,6 +187,13 @@ Public Class ByRefParameterizedPropertyTests Assert.Equal("get 1,1;set 1,1=changed", LogText()) End Sub + + Public Sub ByRefExtensionReceiverPropertyIsWrittenBack() + Dim db As New Db(_log) + db.Plain.ChangeByRef() + Assert.Equal("plain get;plain set=changed", LogText()) + End Sub + Public Sub NumberToStringIndexUsesTheCultureBeforeTheCall() Dim original = Threading.Thread.CurrentThread.CurrentCulture @@ -542,3 +549,10 @@ Public Class ByRefParameterizedPropertyTests End Function End Class End Class + +Public Module ByRefParameterizedPropertyExtensions + + Public Sub ChangeByRef(ByRef value As String) + value = "changed" + End Sub +End Module From 7020f3734258fc094c94d77761a35be5c2c5fb2d Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 23:33:58 +0000 Subject: [PATCH 41/56] Document the culture-free and initializer-lambda rules Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- CodeConverter/CSharp/ByRefArguments/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CodeConverter/CSharp/ByRefArguments/README.md b/CodeConverter/CSharp/ByRefArguments/README.md index ee8c9cc9b..4dd255a9d 100644 --- a/CodeConverter/CSharp/ByRefArguments/README.md +++ b/CodeConverter/CSharp/ByRefArguments/README.md @@ -36,8 +36,8 @@ Source: Roslyn's [`UseTwiceRewriter.vb`](https://github.com/dotnet/roslyn/blob/m * VB evaluates the target's receiver and index arguments once, and the write-back reuses their values. It copies each into a temporary except literals, constants and `Me`. * The converter hoists a `tmp` only where the second evaluation could give a different value: `ByRefTargetTemporaries`. * A write is anything in `VariableWrites`: an assignment, compound assignment, ByRef or late-bound argument, `For`/`For Each` control variable, `ReDim`, `Erase` or `Mid` statement. - * A local or `ByVal` parameter is reused unless the enclosing expression, or any lambda in the same method (the call could run it), writes it. Only those can. A `ByRef` parameter aliases a variable the call might reach, and a `Static` local outlives the call like a field, so both are copied. - * An intrinsic unary or binary operator on reusable operands is reused: it gives the same result, or throws the same exception, again. A user-defined operator, or one on `Object` (late bound), is copied. + * A local or `ByVal` parameter is reused unless the enclosing expression, or any lambda in the same method (outside a method, the outermost enclosing lambda), writes it: the call could run that lambda. Only those can. A `ByRef` parameter aliases a variable the call might reach, and a `Static` local outlives the call like a field, so both are copied. + * An intrinsic unary or binary operator, or a conversion, on reusable operands is reused when it gives the same result, or throws the same exception, again: between numeric, `Boolean`, `Char` and enum types (or their nullables), or an identity, widening reference or boxing conversion. Anything involving `String` or `Date` can read the current culture, which the call can change (`d & ""` gives `1.5` or `1,5`), one on `Object` is late bound, and a user-defined one runs user code, so those are copied. * A field is reused only if, in addition, the call can't change it (`IFieldMutationOracle.MayChangeDuringCall`). `FieldWriteAnalysis` answers that once per compilation, soundly without knowing what the call reaches: a field can't change if it's `Const` or `ReadOnly`, or if only this compilation can write it (it, or a type containing it, is `Private`, or `Friend` with no `InternalsVisibleTo`) and nothing in it writes it outside construction. Construction (a constructor writing its own instance's field, a shared constructor writing a shared field, or a field or property initializer) has finished before anything can read the field, but a lambda in it may run later, so that isn't excluded. A structure field (other than a primitive or enum) is always treated as changeable, since calling a method on it can change it. So is an auto-property's backing field (`_Idx`), which is written through the property. * A call graph of method references could narrow this to the fields the call can transitively write. To stay sound it would treat overridable and interface calls as reaching every implementation, delegate invocations and late-bound calls as reaching anything a delegate or late-bound call could, and calls outside the compilation as reaching any field they can see. * A parameterized property (not the default one) becomes `get_X`/`set_X` methods, so its write-back calls the setter with the same index arguments: `ByRefArgumentHoister.CreateWriteBack`, `AdditionalAssignment.ViaSetter`. It takes its place in the call's reversed write-back order like any other. From 733bd61059323eb9a557a1751e8269db019adcd5 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 20:37:39 +0000 Subject: [PATCH 42/56] Build the field write analysis once per project Pure refactor (no output change). Each document is converted with its own compilation after expanding its root, so caching per compilation scanned the whole project once per document that asked about a field: measured 7 analyses and 6 scans converting a 7-document project, now 1 and 1. VBToCSProjectContentsConverter creates it, like typeToInheritors, and fields are matched by documentation ID across the documents' compilations. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg # Conflicts: # CodeConverter/CSharp/ExpressionNodeVisitor.cs --- CodeConverter/CSharp/ArgumentConverter.cs | 5 ++-- .../ByRefArguments/ByRefArgumentHoister.cs | 4 ++-- .../ByRefArguments/FieldWriteAnalysis.cs | 23 ++++++++----------- CodeConverter/CSharp/ByRefArguments/README.md | 2 +- .../CSharp/DeclarationNodeVisitor.cs | 6 +++-- CodeConverter/CSharp/ExpressionNodeVisitor.cs | 6 +++-- .../CSharp/VBToCSProjectContentsConverter.cs | 7 ++++-- CodeConverter/CSharp/VisualBasicConverter.cs | 8 ++++--- 8 files changed, 34 insertions(+), 27 deletions(-) diff --git a/CodeConverter/CSharp/ArgumentConverter.cs b/CodeConverter/CSharp/ArgumentConverter.cs index adf31ce65..601de8a00 100644 --- a/CodeConverter/CSharp/ArgumentConverter.cs +++ b/CodeConverter/CSharp/ArgumentConverter.cs @@ -12,14 +12,15 @@ internal class ArgumentConverter private CommentConvertingVisitorWrapper TriviaConvertingExpressionVisitor { get; } public ByRefArgumentHoister ByRefArgumentHoister { get; } - public ArgumentConverter(VisualBasicEqualityComparison visualBasicEqualityComparison, ITypeContext typeContext, SemanticModel semanticModel, CommonConversions commonConversions) + public ArgumentConverter(VisualBasicEqualityComparison visualBasicEqualityComparison, ITypeContext typeContext, SemanticModel semanticModel, CommonConversions commonConversions, + IFieldMutationOracle fieldMutations) { CommonConversions = commonConversions; _visualBasicEqualityComparison = visualBasicEqualityComparison; _typeContext = typeContext; _semanticModel = semanticModel; TriviaConvertingExpressionVisitor = commonConversions.TriviaConvertingExpressionVisitor; - ByRefArgumentHoister = new ByRefArgumentHoister(typeContext, semanticModel, commonConversions); + ByRefArgumentHoister = new ByRefArgumentHoister(typeContext, semanticModel, commonConversions, fieldMutations); } public async Task ConvertSimpleArgumentAsync(VBSyntax.SimpleArgumentSyntax node) diff --git a/CodeConverter/CSharp/ByRefArguments/ByRefArgumentHoister.cs b/CodeConverter/CSharp/ByRefArguments/ByRefArgumentHoister.cs index b6e860e24..61333d145 100644 --- a/CodeConverter/CSharp/ByRefArguments/ByRefArgumentHoister.cs +++ b/CodeConverter/CSharp/ByRefArguments/ByRefArgumentHoister.cs @@ -17,11 +17,11 @@ internal class ByRefArgumentHoister /// private readonly Stack> _writeBacksPerCall = new(); - public ByRefArgumentHoister(ITypeContext typeContext, SemanticModel semanticModel, CommonConversions commonConversions) + public ByRefArgumentHoister(ITypeContext typeContext, SemanticModel semanticModel, CommonConversions commonConversions, IFieldMutationOracle fieldMutations) { _typeContext = typeContext; _semanticModel = semanticModel; - _fieldMutations = FieldWriteAnalysis.For(semanticModel.Compilation); + _fieldMutations = fieldMutations; CommonConversions = commonConversions; } diff --git a/CodeConverter/CSharp/ByRefArguments/FieldWriteAnalysis.cs b/CodeConverter/CSharp/ByRefArguments/FieldWriteAnalysis.cs index 11241006b..736511fa6 100644 --- a/CodeConverter/CSharp/ByRefArguments/FieldWriteAnalysis.cs +++ b/CodeConverter/CSharp/ByRefArguments/FieldWriteAnalysis.cs @@ -12,26 +12,23 @@ namespace ICSharpCode.CodeConverter.CSharp.ByRefArguments; /// /// Construction is excluded because it has finished before a caller can read the field: a constructor's writes to its own instance's fields, /// a shared constructor's writes to shared fields, and field initializers (which run as part of those). A lambda in a constructor can run later, so it isn't excluded. -/// Computed once per compilation, on first use. +/// Computed once per project, on first use. Each document is converted with a compilation of its own (after expanding its root), +/// so fields are matched by documentation ID rather than by symbol. /// internal class FieldWriteAnalysis : IFieldMutationOracle { - private static readonly ConditionalWeakTable PerCompilation = new(); - private readonly Compilation _compilation; - private readonly Lazy> _fieldsWrittenAfterConstruction; + private readonly Lazy> _fieldsWrittenAfterConstruction; private readonly Lazy _hasFriendAssemblies; - private FieldWriteAnalysis(Compilation compilation) + public FieldWriteAnalysis(Compilation compilation) { _compilation = compilation; - _fieldsWrittenAfterConstruction = new Lazy>(FindFieldsWrittenAfterConstruction); + _fieldsWrittenAfterConstruction = new Lazy>(FindFieldsWrittenAfterConstruction); _hasFriendAssemblies = new Lazy(() => compilation.Assembly.GetAttributes() .Any(a => a.AttributeClass?.Name == nameof(InternalsVisibleToAttribute))); } - public static FieldWriteAnalysis For(Compilation compilation) => PerCompilation.GetValue(compilation, c => new FieldWriteAnalysis(c)); - /// Ignores : a call graph could narrow the answer to the fields the call can transitively write. public bool MayChangeDuringCall(IFieldSymbol field, IOperation call) { @@ -40,12 +37,12 @@ public bool MayChangeDuringCall(IFieldSymbol field, IOperation call) // An auto-property's backing field (or a WithEvents variable's) is written through the property, which this doesn't follow if (field.AssociatedSymbol is IPropertySymbol) return true; if (CanBeWrittenOutsideCompilation(field) || CanBeMutatedThroughMembers(field)) return true; - return _fieldsWrittenAfterConstruction.Value.Contains(field); + return _fieldsWrittenAfterConstruction.Value.Contains(field.GetDocumentationCommentId()); } private bool CanBeWrittenOutsideCompilation(IFieldSymbol field) { - if (!SymbolEqualityComparer.Default.Equals(field.ContainingAssembly, _compilation.Assembly)) return true; + if (field.ContainingAssembly?.Name != _compilation.AssemblyName) return true; for (ISymbol symbol = field; symbol is not null and not INamespaceSymbol; symbol = symbol.ContainingSymbol) { switch (symbol.DeclaredAccessibility) { case Accessibility.Private: @@ -63,9 +60,9 @@ private bool CanBeWrittenOutsideCompilation(IFieldSymbol field) private static bool CanBeMutatedThroughMembers(IFieldSymbol field) => field.Type.IsValueType && field.Type.SpecialType == SpecialType.None && field.Type.TypeKind != TypeKind.Enum; - private HashSet FindFieldsWrittenAfterConstruction() + private HashSet FindFieldsWrittenAfterConstruction() { - var written = new HashSet(SymbolEqualityComparer.Default); + var written = new HashSet(StringComparer.Ordinal); foreach (var tree in _compilation.SyntaxTrees) { var semanticModel = _compilation.GetSemanticModel(tree, true); foreach (var name in tree.GetRoot().DescendantNodes().OfType()) { @@ -73,7 +70,7 @@ private HashSet FindFieldsWrittenAfterConstruction() var reference = name.Parent is VBSyntax.MemberAccessExpressionSyntax maes && maes.Name == name ? (SyntaxNode)maes : name; if (semanticModel.GetOperation(reference) is { } operation && VariableWrites.IsWrite(operation) && !IsDuringConstruction(semanticModel, reference, field)) { - written.Add(field.OriginalDefinition); + written.Add(field.OriginalDefinition.GetDocumentationCommentId()); } } } diff --git a/CodeConverter/CSharp/ByRefArguments/README.md b/CodeConverter/CSharp/ByRefArguments/README.md index 4dd255a9d..55eb1b751 100644 --- a/CodeConverter/CSharp/ByRefArguments/README.md +++ b/CodeConverter/CSharp/ByRefArguments/README.md @@ -38,7 +38,7 @@ Source: Roslyn's [`UseTwiceRewriter.vb`](https://github.com/dotnet/roslyn/blob/m * A write is anything in `VariableWrites`: an assignment, compound assignment, ByRef or late-bound argument, `For`/`For Each` control variable, `ReDim`, `Erase` or `Mid` statement. * A local or `ByVal` parameter is reused unless the enclosing expression, or any lambda in the same method (outside a method, the outermost enclosing lambda), writes it: the call could run that lambda. Only those can. A `ByRef` parameter aliases a variable the call might reach, and a `Static` local outlives the call like a field, so both are copied. * An intrinsic unary or binary operator, or a conversion, on reusable operands is reused when it gives the same result, or throws the same exception, again: between numeric, `Boolean`, `Char` and enum types (or their nullables), or an identity, widening reference or boxing conversion. Anything involving `String` or `Date` can read the current culture, which the call can change (`d & ""` gives `1.5` or `1,5`), one on `Object` is late bound, and a user-defined one runs user code, so those are copied. - * A field is reused only if, in addition, the call can't change it (`IFieldMutationOracle.MayChangeDuringCall`). `FieldWriteAnalysis` answers that once per compilation, soundly without knowing what the call reaches: a field can't change if it's `Const` or `ReadOnly`, or if only this compilation can write it (it, or a type containing it, is `Private`, or `Friend` with no `InternalsVisibleTo`) and nothing in it writes it outside construction. Construction (a constructor writing its own instance's field, a shared constructor writing a shared field, or a field or property initializer) has finished before anything can read the field, but a lambda in it may run later, so that isn't excluded. A structure field (other than a primitive or enum) is always treated as changeable, since calling a method on it can change it. So is an auto-property's backing field (`_Idx`), which is written through the property. + * A field is reused only if, in addition, the call can't change it (`IFieldMutationOracle.MayChangeDuringCall`). `FieldWriteAnalysis` answers that once per project (created by `VBToCSProjectContentsConverter`, matching fields by documentation ID since each document gets its own compilation), soundly without knowing what the call reaches: a field can't change if it's `Const` or `ReadOnly`, or if only this compilation can write it (it, or a type containing it, is `Private`, or `Friend` with no `InternalsVisibleTo`) and nothing in it writes it outside construction. Construction (a constructor writing its own instance's field, a shared constructor writing a shared field, or a field or property initializer) has finished before anything can read the field, but a lambda in it may run later, so that isn't excluded. A structure field (other than a primitive or enum) is always treated as changeable, since calling a method on it can change it. So is an auto-property's backing field (`_Idx`), which is written through the property. * A call graph of method references could narrow this to the fields the call can transitively write. To stay sound it would treat overridable and interface calls as reaching every implementation, delegate invocations and late-bound calls as reaching anything a delegate or late-bound call could, and calls outside the compilation as reaching any field they can see. * A parameterized property (not the default one) becomes `get_X`/`set_X` methods, so its write-back calls the setter with the same index arguments: `ByRefArgumentHoister.CreateWriteBack`, `AdditionalAssignment.ViaSetter`. It takes its place in the call's reversed write-back order like any other. * A `ReadOnly` property isn't written back (`GetRefConversionForExpression`), so it's evaluated once and needs no temporaries. diff --git a/CodeConverter/CSharp/DeclarationNodeVisitor.cs b/CodeConverter/CSharp/DeclarationNodeVisitor.cs index 7f4caab5f..23310bfc1 100644 --- a/CodeConverter/CSharp/DeclarationNodeVisitor.cs +++ b/CodeConverter/CSharp/DeclarationNodeVisitor.cs @@ -1,3 +1,4 @@ +using ICSharpCode.CodeConverter.CSharp.ByRefArguments; using System.Collections.Immutable; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.Classification; @@ -42,7 +43,8 @@ internal class DeclarationNodeVisitor : VBasic.VisualBasicSyntaxVisitor _typeContext.PerScopeState; public DeclarationNodeVisitor(Document document, Compilation compilation, SemanticModel semanticModel, - CSharpCompilation csCompilation, SyntaxGenerator csSyntaxGenerator, ILookup typeToInheritors) + CSharpCompilation csCompilation, SyntaxGenerator csSyntaxGenerator, ILookup typeToInheritors, + IFieldMutationOracle fieldMutations) { _vbCompilation = compilation; _csSyntaxGenerator = csSyntaxGenerator; @@ -55,7 +57,7 @@ public DeclarationNodeVisitor(Document document, Compilation compilation, Semant var nullableExpressionsConverter = new VisualBasicNullableExpressionsConverter(_semanticModel); var typeConversionAnalyzer = new TypeConversionAnalyzer(semanticModel, csCompilation, _extraUsingDirectives, _csSyntaxGenerator, expressionEvaluator, nullableExpressionsConverter); CommonConversions = new CommonConversions(document, semanticModel, typeConversionAnalyzer, csSyntaxGenerator, compilation, csCompilation, _typeContext, _visualBasicEqualityComparison); - var expressionNodeVisitor = new ExpressionNodeVisitor(semanticModel, _visualBasicEqualityComparison, _typeContext, CommonConversions, _extraUsingDirectives, _xmlImportContext, nullableExpressionsConverter); + var expressionNodeVisitor = new ExpressionNodeVisitor(semanticModel, _visualBasicEqualityComparison, _typeContext, CommonConversions, _extraUsingDirectives, _xmlImportContext, nullableExpressionsConverter, fieldMutations); _accessorDeclarationNodeConverter = new AccessorDeclarationNodeConverter(semanticModel, CommonConversions, TriviaConvertingDeclarationVisitor, _additionalDeclarations, expressionNodeVisitor.ConvertMethodBodyStatementsAsync); _triviaConvertingExpressionVisitor = CommonConversions.TriviaConvertingExpressionVisitor; _convertMethodBodyStatementsAsync = expressionNodeVisitor.ConvertMethodBodyStatementsAsync; diff --git a/CodeConverter/CSharp/ExpressionNodeVisitor.cs b/CodeConverter/CSharp/ExpressionNodeVisitor.cs index 837cc47b7..6297bea8f 100644 --- a/CodeConverter/CSharp/ExpressionNodeVisitor.cs +++ b/CodeConverter/CSharp/ExpressionNodeVisitor.cs @@ -1,3 +1,4 @@ +using ICSharpCode.CodeConverter.CSharp.ByRefArguments; using ICSharpCode.CodeConverter.CSharp.Queries; using ICSharpCode.CodeConverter.Util.FromRoslyn; using Microsoft.CodeAnalysis.CSharp; @@ -36,7 +37,8 @@ internal partial class ExpressionNodeVisitor : VBasic.VisualBasicSyntaxVisitor extraUsingDirectives, XmlImportContext xmlImportContext, VisualBasicNullableExpressionsConverter visualBasicNullableTypesConverter) + HashSet extraUsingDirectives, XmlImportContext xmlImportContext, VisualBasicNullableExpressionsConverter visualBasicNullableTypesConverter, + IFieldMutationOracle fieldMutations) { _semanticModel = semanticModel; CommonConversions = commonConversions; @@ -48,7 +50,7 @@ public ExpressionNodeVisitor(SemanticModel semanticModel, _typeContext = typeContext; _extraUsingDirectives = extraUsingDirectives; _valueTupleCreationConverter = new ValueTupleCreationConverter(semanticModel, commonConversions); - _argumentConverter = new ArgumentConverter(visualBasicEqualityComparison, typeContext, semanticModel, commonConversions); + _argumentConverter = new ArgumentConverter(visualBasicEqualityComparison, typeContext, semanticModel, commonConversions, fieldMutations); _xmlExpressionConverter = new XmlExpressionConverter(xmlImportContext, extraUsingDirectives, commonConversions, semanticModel, _withBlockLhs, _generatedNames, _conditionalAccessReceivers); _nameExpressionNodeVisitor = new NameExpressionNodeVisitor(semanticModel, _generatedNames, typeContext, extraUsingDirectives, _tempNameForAnonymousScope, _withBlockLhs, commonConversions, _argumentConverter, TriviaConvertingExpressionVisitor, _conditionalAccessReceivers, rangeVariableReplacements); _operatorConverter = VbOperatorConversion.Create(TriviaConvertingExpressionVisitor, semanticModel, visualBasicEqualityComparison, commonConversions.TypeConversionAnalyzer); diff --git a/CodeConverter/CSharp/VBToCSProjectContentsConverter.cs b/CodeConverter/CSharp/VBToCSProjectContentsConverter.cs index f42879716..702ecfbe0 100644 --- a/CodeConverter/CSharp/VBToCSProjectContentsConverter.cs +++ b/CodeConverter/CSharp/VBToCSProjectContentsConverter.cs @@ -1,4 +1,5 @@ -using System.Runtime.CompilerServices; +using ICSharpCode.CodeConverter.CSharp.ByRefArguments; +using System.Runtime.CompilerServices; using System.Xml.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.VisualBasic; @@ -21,6 +22,7 @@ internal class VBToCSProjectContentsConverter : IProjectContentsConverter private readonly IProgress _progress; private readonly CancellationToken _cancellationToken; private ILookup _typeToInheritors; + private IFieldMutationOracle _fieldMutations; public VBToCSProjectContentsConverter(ConversionOptions conversionOptions, bool useProjectLevelWinformsAdjustments, @@ -47,6 +49,7 @@ public async Task InitializeSourceAsync(Project project) _csharpViewOfVbSymbols = (CSharpCompilation)await _csharpReferenceProject.GetCompilationAsync(_cancellationToken); _designerToResxRelativePath = project.ReadVbEmbeddedResources().ToDictionary(r => r.LastGenOutput, r => r.RelativePath); SourceProject = await WithProjectLevelWinformsAdjustmentsAsync(project); + _fieldMutations = new FieldWriteAnalysis(await SourceProject.GetCompilationAsync(_cancellationToken)); var compilation = await project.GetCompilationAsync(_cancellationToken); #pragma warning disable RS1024 // Compare symbols correctly - analzyer bug, I'm intentionally using my own comparer, not the default ambiguous one. The default comparer wouldn't manage with cross-compilation comparison in all cases @@ -76,7 +79,7 @@ private async Task WithProjectLevelWinformsAdjustmentsAsync(Project pro public async Task SingleFirstPassAsync(Document document) { - return await VisualBasicConverter.ConvertCompilationTreeAsync(document, _csharpViewOfVbSymbols, _csharpReferenceProject, OptionalOperations, _typeToInheritors, _cancellationToken); + return await VisualBasicConverter.ConvertCompilationTreeAsync(document, _csharpViewOfVbSymbols, _csharpReferenceProject, OptionalOperations, _typeToInheritors, _fieldMutations, _cancellationToken); } public async Task<(Project project, List> firstPassDocIds)> GetConvertedProjectAsync(WipFileConversion[] firstPassResults) diff --git a/CodeConverter/CSharp/VisualBasicConverter.cs b/CodeConverter/CSharp/VisualBasicConverter.cs index 017c4e37b..40a55965a 100644 --- a/CodeConverter/CSharp/VisualBasicConverter.cs +++ b/CodeConverter/CSharp/VisualBasicConverter.cs @@ -1,4 +1,5 @@ -using Microsoft.CodeAnalysis.CSharp; +using ICSharpCode.CodeConverter.CSharp.ByRefArguments; +using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Editing; namespace ICSharpCode.CodeConverter.CSharp; @@ -7,7 +8,8 @@ internal static class VisualBasicConverter { public static async Task ConvertCompilationTreeAsync(Document document, CSharpCompilation csharpViewOfVbSymbols, Project csharpReferenceProject, - OptionalOperations optionalOperations, ILookup typeToInheritors, CancellationToken cancellationToken) + OptionalOperations optionalOperations, ILookup typeToInheritors, IFieldMutationOracle fieldMutations, + CancellationToken cancellationToken) { document = await document.WithExpandedRootAsync(cancellationToken); var root = await document.GetSyntaxRootAsync(cancellationToken) as VBSyntax.CompilationUnitSyntax ?? @@ -20,7 +22,7 @@ public static async Task ConvertCompilationTreeAsync(Document docume var csSyntaxGenerator = SyntaxGenerator.GetGenerator(csharpReferenceProject); var semanticModel = compilation.GetSemanticModel(tree, true); var visualBasicSyntaxVisitor = new - DeclarationNodeVisitor(document, compilation, semanticModel, csharpViewOfVbSymbols, csSyntaxGenerator, typeToInheritors); + DeclarationNodeVisitor(document, compilation, semanticModel, csharpViewOfVbSymbols, csSyntaxGenerator, typeToInheritors, fieldMutations); var converted = await root.AcceptAsync(visualBasicSyntaxVisitor.TriviaConvertingDeclarationVisitor); return optionalOperations.MapSourceTriviaToTargetHandled(root, converted, document); From 21f9b1eee83f3cf0c16488cef313e8bb13bfaf44 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 14:22:39 +0000 Subject: [PATCH 43/56] Copy a structure's instance field used in a ByRef target A structure's instance field was reused when it was ReadOnly or only written in a constructor, but assigning the whole structure (`gs = New S(9)`) overwrites every field, so a call that replaced the structure made the write-back use the new value. Treat any instance field of a value type as changeable. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- .../ByRefArguments/FieldWriteAnalysis.cs | 5 ++- CodeConverter/CSharp/ByRefArguments/README.md | 2 +- .../VBToCS/ByRefParameterizedPropertyTests.vb | 35 +++++++++++++++++++ 3 files changed, 40 insertions(+), 2 deletions(-) diff --git a/CodeConverter/CSharp/ByRefArguments/FieldWriteAnalysis.cs b/CodeConverter/CSharp/ByRefArguments/FieldWriteAnalysis.cs index 736511fa6..4787ee5c0 100644 --- a/CodeConverter/CSharp/ByRefArguments/FieldWriteAnalysis.cs +++ b/CodeConverter/CSharp/ByRefArguments/FieldWriteAnalysis.cs @@ -33,7 +33,10 @@ public FieldWriteAnalysis(Compilation compilation) public bool MayChangeDuringCall(IFieldSymbol field, IOperation call) { field = field.OriginalDefinition; - if (field.IsConst || field.IsReadOnly) return false; + if (field.IsConst) return false; + // Assigning a whole structure (`s = New S(9)`) overwrites every instance field, ReadOnly or not + if (!field.IsStatic && field.ContainingType.IsValueType) return true; + if (field.IsReadOnly) return false; // An auto-property's backing field (or a WithEvents variable's) is written through the property, which this doesn't follow if (field.AssociatedSymbol is IPropertySymbol) return true; if (CanBeWrittenOutsideCompilation(field) || CanBeMutatedThroughMembers(field)) return true; diff --git a/CodeConverter/CSharp/ByRefArguments/README.md b/CodeConverter/CSharp/ByRefArguments/README.md index 55eb1b751..bfbe5e2c6 100644 --- a/CodeConverter/CSharp/ByRefArguments/README.md +++ b/CodeConverter/CSharp/ByRefArguments/README.md @@ -38,7 +38,7 @@ Source: Roslyn's [`UseTwiceRewriter.vb`](https://github.com/dotnet/roslyn/blob/m * A write is anything in `VariableWrites`: an assignment, compound assignment, ByRef or late-bound argument, `For`/`For Each` control variable, `ReDim`, `Erase` or `Mid` statement. * A local or `ByVal` parameter is reused unless the enclosing expression, or any lambda in the same method (outside a method, the outermost enclosing lambda), writes it: the call could run that lambda. Only those can. A `ByRef` parameter aliases a variable the call might reach, and a `Static` local outlives the call like a field, so both are copied. * An intrinsic unary or binary operator, or a conversion, on reusable operands is reused when it gives the same result, or throws the same exception, again: between numeric, `Boolean`, `Char` and enum types (or their nullables), or an identity, widening reference or boxing conversion. Anything involving `String` or `Date` can read the current culture, which the call can change (`d & ""` gives `1.5` or `1,5`), one on `Object` is late bound, and a user-defined one runs user code, so those are copied. - * A field is reused only if, in addition, the call can't change it (`IFieldMutationOracle.MayChangeDuringCall`). `FieldWriteAnalysis` answers that once per project (created by `VBToCSProjectContentsConverter`, matching fields by documentation ID since each document gets its own compilation), soundly without knowing what the call reaches: a field can't change if it's `Const` or `ReadOnly`, or if only this compilation can write it (it, or a type containing it, is `Private`, or `Friend` with no `InternalsVisibleTo`) and nothing in it writes it outside construction. Construction (a constructor writing its own instance's field, a shared constructor writing a shared field, or a field or property initializer) has finished before anything can read the field, but a lambda in it may run later, so that isn't excluded. A structure field (other than a primitive or enum) is always treated as changeable, since calling a method on it can change it. So is an auto-property's backing field (`_Idx`), which is written through the property. + * A field is reused only if, in addition, the call can't change it (`IFieldMutationOracle.MayChangeDuringCall`). `FieldWriteAnalysis` answers that once per project (created by `VBToCSProjectContentsConverter`, matching fields by documentation ID since each document gets its own compilation), soundly without knowing what the call reaches: a field can't change if it's `Const` or `ReadOnly`, or if only this compilation can write it (it, or a type containing it, is `Private`, or `Friend` with no `InternalsVisibleTo`) and nothing in it writes it outside construction. Construction (a constructor writing its own instance's field, a shared constructor writing a shared field, or a field or property initializer) has finished before anything can read the field, but a lambda in it may run later, so that isn't excluded. A structure field (other than a primitive or enum) is always treated as changeable, since calling a method on it can change it. So is an auto-property's backing field (`_Idx`), which is written through the property, and any instance field of a structure, even `ReadOnly`: assigning the whole structure (`s = New S(9)`) overwrites it. * A call graph of method references could narrow this to the fields the call can transitively write. To stay sound it would treat overridable and interface calls as reaching every implementation, delegate invocations and late-bound calls as reaching anything a delegate or late-bound call could, and calls outside the compilation as reaching any field they can see. * A parameterized property (not the default one) becomes `get_X`/`set_X` methods, so its write-back calls the setter with the same index arguments: `ByRefArgumentHoister.CreateWriteBack`, `AdditionalAssignment.ViaSetter`. It takes its place in the call's reversed write-back order like any other. * A `ReadOnly` property isn't written back (`GetRefConversionForExpression`), so it's evaluated once and needs no temporaries. diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb index d30b449d5..fb419b645 100644 --- a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb @@ -231,6 +231,41 @@ Public Class ByRefParameterizedPropertyTests End Function End Class + Private Shared _replacedIndexer As IndexHolder + + + Public Sub StructureFieldIndexOverwrittenByAssigningTheStructureUsesItsOriginalValue() + Dim db As New Db(_log) + _replacedIndexer = New IndexHolder(1) + _replacedIndexer.SetValueReplacingMe(db) + Assert.Equal("get 1,21;set 1,21=changed;get 2,22;set 2,22=changed", LogText()) + End Sub + + Private Shared Sub ReplaceIndexHolderAndSetValue(ByRef value As String) + _replacedIndexer = New IndexHolder(9) + value = "changed" + End Sub + + Private Structure IndexHolder + Private ReadOnly _readOnlyIndex As Integer + Private _constructorIndex As Integer + + Public Sub New(index As Integer) + _readOnlyIndex = index + _constructorIndex = index + 1 + End Sub + + Public Sub SetValueReplacingMe(db As Db) + ReplaceIndexHolderAndSetValue(db.Qr(_readOnlyIndex, 21)) + _replacedIndexer = New IndexHolder(1) + _replacedIndexer.SetConstructorIndexReplacingMe(db) + End Sub + + Public Sub SetConstructorIndexReplacingMe(db As Db) + ReplaceIndexHolderAndSetValue(db.Qr(_constructorIndex, 22)) + End Sub + End Structure + Public Sub SharedParameterizedPropertyIsWrittenBackThroughItsSetter() Db.SharedLog = _log From e194d7e32d91504ef50b3b4d6b57277618e2d120 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 14:28:19 +0000 Subject: [PATCH 44/56] Copy an element access's container only when it could change `SetValue(Me(i, 5))` gave `var tmp = this; ... tmp[i, 5] = arg`, because the container of every ByRef element access was copied before ByRefTargetTemporaries could see it was reusable. Apply the receiver rules to the container too, so Me, and a local array or object that the call can't change, are used directly. Without a write-back the container is evaluated once anyway, so it isn't copied. BinaryExpressionRefParameterAsync: `wideArray` is a local the call can't change, so its write-back uses it directly instead of a `tmp` copy. Issue567ExtendedAsync is unchanged: the callee reassigns those fields, so they're still copied. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- .../ByRefArguments/ByRefArgumentHoister.cs | 6 -- .../ByRefArguments/ByRefTargetTemporaries.cs | 9 ++- CodeConverter/CSharp/ByRefArguments/README.md | 2 +- Tests/CSharp/ExpressionTests/ByRefTests.cs | 79 ++++++++++++++++--- 4 files changed, 76 insertions(+), 20 deletions(-) diff --git a/CodeConverter/CSharp/ByRefArguments/ByRefArgumentHoister.cs b/CodeConverter/CSharp/ByRefArguments/ByRefArgumentHoister.cs index 61333d145..68e95d444 100644 --- a/CodeConverter/CSharp/ByRefArguments/ByRefArgumentHoister.cs +++ b/CodeConverter/CSharp/ByRefArguments/ByRefArgumentHoister.cs @@ -50,12 +50,6 @@ public CSSyntax.ExpressionSyntax HoistByRefDeclaration(VBSyntax.ExpressionSyntax 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); - } - if (refType == SemanticModelExtensions.RefConversion.PreAndPostAssignment) { refLValue = ByRefTargetTemporaries.Hoist(_semanticModel, _typeContext, _fieldMutations, node, refLValue); } diff --git a/CodeConverter/CSharp/ByRefArguments/ByRefTargetTemporaries.cs b/CodeConverter/CSharp/ByRefArguments/ByRefTargetTemporaries.cs index 564e6674a..5b9bafc3b 100644 --- a/CodeConverter/CSharp/ByRefArguments/ByRefTargetTemporaries.cs +++ b/CodeConverter/CSharp/ByRefArguments/ByRefTargetTemporaries.cs @@ -44,15 +44,18 @@ private CSSyntax.ExpressionSyntax Hoist(CSSyntax.ExpressionSyntax csTarget) getterCall.WithExpression(HoistReceiver(getterCall.Expression, pro)) .WithArgumentList(getterCall.ArgumentList.WithArguments(HoistArguments(getterCall.ArgumentList.Arguments, pro))), (IPropertyReferenceOperation pro, CSSyntax.ElementAccessExpressionSyntax indexer) => - indexer.WithArgumentList(indexer.ArgumentList.WithArguments(HoistArguments(indexer.ArgumentList.Arguments, pro))), + indexer.WithExpression(HoistInstance(pro.Instance, indexer.Expression)) + .WithArgumentList(indexer.ArgumentList.WithArguments(HoistArguments(indexer.ArgumentList.Arguments, pro))), (IArrayElementReferenceOperation element, CSSyntax.ElementAccessExpressionSyntax elementAccess) => - elementAccess.WithArgumentList(elementAccess.ArgumentList.WithArguments(HoistIndices(elementAccess.ArgumentList.Arguments, element.Indices))), + elementAccess.WithExpression(HoistInstance(element.ArrayReference, elementAccess.Expression)) + .WithArgumentList(elementAccess.ArgumentList.WithArguments(HoistIndices(elementAccess.ArgumentList.Arguments, element.Indices))), (IPropertyReferenceOperation pro, CSSyntax.MemberAccessExpressionSyntax) => HoistReceiver(csTarget, pro), + // E.g. late bound: without an operation to tell what's reusable, copy the container as VB does + (_, CSSyntax.ElementAccessExpressionSyntax elementAccess) => elementAccess.WithExpression(HoistValue(elementAccess.Expression)), _ => csTarget }; } - /// The container of an element access is already hoisted by the caller. private CSSyntax.ExpressionSyntax HoistReceiver(CSSyntax.ExpressionSyntax memberExpression, IPropertyReferenceOperation pro) { if (memberExpression is not CSSyntax.MemberAccessExpressionSyntax maes || pro.Property.IsStatic) { diff --git a/CodeConverter/CSharp/ByRefArguments/README.md b/CodeConverter/CSharp/ByRefArguments/README.md index bfbe5e2c6..5210231cb 100644 --- a/CodeConverter/CSharp/ByRefArguments/README.md +++ b/CodeConverter/CSharp/ByRefArguments/README.md @@ -49,7 +49,7 @@ Source: Roslyn's [`UseTwiceRewriter.vb`](https://github.com/dotnet/roslyn/blob/m | `other.Qr(_writtenElsewhere, 2)`, `other.Qr(PublicIndex, 2)` | `var tmp = _writtenElsewhere;` … `other.set_Qr(tmp, 2, arg)` | | `other.Qr(NextIndex(), 2)` | `var tmp = NextIndex();` … `other.get_Qr(tmp, 2)` … `other.set_Qr(tmp, 2, arg)` | | `GetC().Qr(1, 2)`, `GetC().Plain` | `var tmp = GetC();` … `tmp.set_Qr(1, 2, arg)`, `tmp.Plain = arg` | -| `other(NextIndex())` (default property or indexer) | `var tmp = other; var tmp1 = NextIndex();` … `tmp[tmp1] = arg` (the container is always copied, as before) | +| `other(NextIndex())`, `Me(i, 5)` (default property, indexer or array) | `var tmp = NextIndex();` … `other[tmp] = arg`, `this[i, 5] = arg`: the container follows the receiver rules | | `Two(other.Qr(i, 2), i)` | `var tmp = i;` … `other.set_Qr(tmp, 2, arg)` | | `cells(NextIndex()).Text`, `GetHolder().Cell.Text` (`Cell` is a structure) | `var tmp = NextIndex();` … `cells[tmp].Text = arg`, `var tmp = GetHolder();` … `tmp.Cell.Text = arg`: a structure variable is written in place (`ByRefTargetTemporaries.HoistInstance`) | diff --git a/Tests/CSharp/ExpressionTests/ByRefTests.cs b/Tests/CSharp/ExpressionTests/ByRefTests.cs index 24eaa052e..c26eb56b8 100644 --- a/Tests/CSharp/ExpressionTests/ByRefTests.cs +++ b/Tests/CSharp/ExpressionTests/ByRefTests.cs @@ -896,10 +896,9 @@ public static void Main() LogAndReset(ref argarg); wide = argarg; object[] wideArray = new object[] { 3, 4, 4 }; - var tmp = wideArray; - int argarg1 = Conversions.ToInteger(tmp[1]); + int argarg1 = Conversions.ToInteger(wideArray[1]); LogAndReset(ref argarg1); - tmp[1] = argarg1; + wideArray[1] = argarg1; short narrow = 3; int argarg2 = narrow; LogAndReset(ref argarg2); @@ -1736,15 +1735,14 @@ public void UsesTwice(C other) string argvalue3 = tmp2.Plain; SetValue(ref argvalue3); tmp2.Plain = argvalue3; - var tmp3 = other; - var tmp4 = NextIndex(); - string argvalue4 = tmp3[tmp4]; + var tmp3 = NextIndex(); + string argvalue4 = other[tmp3]; SetValue(ref argvalue4); - tmp3[tmp4] = argvalue4; - var tmp5 = i; - string argvalue5 = other.get_Qr(tmp5, 2); + other[tmp3] = argvalue4; + var tmp4 = i; + string argvalue5 = other.get_Qr(tmp4, 2); SetValueAndIndex(ref argvalue5, ref i); - other.set_Qr(tmp5, 2, argvalue5); // i is written by the call + other.set_Qr(tmp4, 2, argvalue5); // i is written by the call } }"); } @@ -2255,6 +2253,67 @@ public static void UsesQr() public static void SetValue(ref string value) { } +}"); + } + + [Fact] + public async Task ByRefDefaultPropertyOnMeIsWrittenBackWithoutCopyingMeAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Public Class C + Default Public Property Item(i As Integer, j As Integer) As String + Get + Return """" + End Get + Set(value As String) + End Set + End Property + + Sub M(i As Integer, values As Object()) + SetValue(Me(i, 5)) + SetValue(Me.Item(i, 6)) + SetNumber(values(i)) + End Sub + + Shared Sub SetValue(ByRef value As String) + End Sub + + Shared Sub SetNumber(ByRef value As Integer) + End Sub +End Class", @"using Microsoft.VisualBasic.CompilerServices; // Install-Package Microsoft.VisualBasic + +public partial class C +{ + public string this[int i, int j] + { + get + { + return """"; + } + set + { + } + } + + public void M(int i, object[] values) + { + string argvalue = this[i, 5]; + SetValue(ref argvalue); + this[i, 5] = argvalue; + string argvalue1 = this[i, 6]; + SetValue(ref argvalue1); + this[i, 6] = argvalue1; + int argvalue2 = Conversions.ToInteger(values[i]); + SetNumber(ref argvalue2); + values[i] = argvalue2; + } + + public static void SetValue(ref string value) + { + } + + public static void SetNumber(ref int value) + { + } }"); } } \ No newline at end of file From 5896c826caa9d0e8d51f83a274e1ce9e28ced881 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 15:54:42 +0000 Subject: [PATCH 45/56] Test a ByRef default property on MyBase Copying an element access's container unconditionally gave `var tmp = base;` for `SetValue(MyBase.Item(i))` (CS0175). Since the container follows the receiver rules (fae13b0), MyBase is used directly: `base[i] = argvalue`. Pins it with a conversion and a self-verifying test. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- Tests/CSharp/ExpressionTests/ByRefTests.cs | 53 +++++++++++++++++++ .../VBToCS/ByRefParameterizedPropertyTests.vb | 19 +++++++ 2 files changed, 72 insertions(+) diff --git a/Tests/CSharp/ExpressionTests/ByRefTests.cs b/Tests/CSharp/ExpressionTests/ByRefTests.cs index c26eb56b8..1e639378b 100644 --- a/Tests/CSharp/ExpressionTests/ByRefTests.cs +++ b/Tests/CSharp/ExpressionTests/ByRefTests.cs @@ -2314,6 +2314,59 @@ public static void SetValue(ref string value) public static void SetNumber(ref int value) { } +}"); + } + + [Fact] + public async Task ByRefDefaultPropertyOnMyBaseIsWrittenBackThroughBaseAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Public Class B + Default Public Property Item(i As Integer) As String + Get + Return """" + End Get + Set(value As String) + End Set + End Property +End Class + +Public Class C + Inherits B + + Sub M(i As Integer) + SetValue(MyBase.Item(i)) + End Sub + + Shared Sub SetValue(ByRef value As String) + End Sub +End Class", @" +public partial class B +{ + public string this[int i] + { + get + { + return """"; + } + set + { + } + } +} + +public partial class C : B +{ + + public void M(int i) + { + string argvalue = base[i]; + SetValue(ref argvalue); + base[i] = argvalue; + } + + public static void SetValue(ref string value) + { + } }"); } } \ No newline at end of file diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb index fb419b645..106c2afee 100644 --- a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb @@ -266,6 +266,25 @@ Public Class ByRefParameterizedPropertyTests End Sub End Structure + + Public Sub MyBaseDefaultPropertyIsWrittenBack() + Dim db As New DerivedDb(_log) + db.SetBaseItem() + Assert.Equal("item get 1;item set 1=changed", LogText()) + End Sub + + Private Class DerivedDb + Inherits Db + + Public Sub New(log As List(Of String)) + MyBase.New(log) + End Sub + + Public Sub SetBaseItem() + SetValue(MyBase.Item(1)) + End Sub + End Class + Public Sub SharedParameterizedPropertyIsWrittenBackThroughItsSetter() Db.SharedLog = _log From 879fd3873a9e504f066616f9a1af3ce705b1e403 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 20:56:45 +0000 Subject: [PATCH 46/56] Pass only the ByRef parameters the local function's body uses 067bc7f resolved a With block's implicit receiver to the whole With expression, so a ByRef parameter that only the With header used (With arr(i), With GetBox(b)) became an unused ref parameter whenever the header was evaluated into withBlock. Decide from the converted body instead, as for this: a parent ByRef parameter is passed when its name is used there. This also removes a null-operation precedence slip. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- CodeConverter/CSharp/ByRefArguments/README.md | 2 +- .../ByRefArguments/WriteBackPlacement.cs | 37 ++++++----- Tests/CSharp/ExpressionTests/ByRefTests.cs | 63 +++++++++++++++++++ 3 files changed, 84 insertions(+), 18 deletions(-) diff --git a/CodeConverter/CSharp/ByRefArguments/README.md b/CodeConverter/CSharp/ByRefArguments/README.md index de6cf0937..e1f022cfb 100644 --- a/CodeConverter/CSharp/ByRefArguments/README.md +++ b/CodeConverter/CSharp/ByRefArguments/README.md @@ -29,7 +29,7 @@ Within each of these, one call's write-backs are hoisted after its whole argumen In a `Structure`, a local function can't use `this` (CS1673). When the call uses an instance member, the local function takes `ref S self` and is called with `ref this`, and its body uses `self` for `this` (the converted body always qualifies instance members, which are only simplified later). `ref this` is legal wherever VB can use `Me` in a structure; VB has no read-only members (where it's CS1605) and no `Me` in a structure's lambdas (BC36638): `WriteBackPlacement.HoistAndCallLocalFunctionAsync`. -A local function can't use a ref local either (CS8175), such as the `ref var withBlock` of a `With` over a structure field. References to a ref local are marked with its type, and the local function takes each one it uses from outside its body as a `ref` parameter of the same name: `RefLocalReferences`. The enclosing method's ByRef parameters are passed the same way (CS1628), including one reused directly as a `With` receiver (`With b : Inc(.X)` becomes `Inc(ref b.X)`): `WriteBackPlacement.DescendantsResolvingWithReceivers`. +A local function can't use a ref local either (CS8175), such as the `ref var withBlock` of a `With` over a structure field. References to a ref local are marked with its type, and the local function takes each one it uses from outside its body as a `ref` parameter of the same name: `RefLocalReferences`. The enclosing method's ByRef parameters are passed the same way (CS1628), including one reused directly as a `With` receiver (`With b : Inc(.X)` becomes `Inc(ref b.X)`): `WriteBackPlacement.RefParametersUsedIn`. 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). diff --git a/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs b/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs index f815be80e..2313cddae 100644 --- a/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs +++ b/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs @@ -47,7 +47,6 @@ public async Task HoistAndCallLocalFunctionAsync(VBa var returnType = CommonConversions.GetTypeSyntax(invocationSymbol.ReturnType); var enclosingSymbol = _semanticModel.GetEnclosingSymbol(invocation.SpanStart); - var operation = _semanticModel.GetOperation(invocation); var arguments = new List(); var parameters = new List(); if (IsInStructAndUsesThis(enclosingSymbol, block)) { @@ -57,12 +56,7 @@ public async Task HoistAndCallLocalFunctionAsync(VBa parameters.Add(RefParameter(selfName, CommonConversions.GetTypeSyntax(enclosingSymbol.ContainingType))); } - // Parent ByRef parameters cannot be captured, including references in receivers, With receivers and nested argument expressions. - var refParametersOfParent = (operation is null ? null : DescendantsResolvingWithReceivers(operation) - .OfType().Select(p => p.Parameter) ?? Enumerable.Empty()) - .Where(p => p.RefKind != RefKind.None && SymbolEqualityComparer.Default.Equals(p.ContainingSymbol, enclosingSymbol)) - .Distinct(SymbolEqualityComparer.Default).ToList(); - AddArgumentsAndParameters(refParametersOfParent); + AddArgumentsAndParameters(RefParametersUsedIn(block, enclosingSymbol)); foreach (var (reference, type) in RefLocalReferences.FindIn(block)) { arguments.Add(SyntaxFactory.Argument(reference).WithRefKindKeyword(SyntaxFactory.Token(SyntaxKind.RefKeyword))); @@ -89,17 +83,26 @@ void AddArgumentsAndParameters(List parameterSymbols) } /// - /// The operations within , where a With block's implicit receiver is replaced by the operations of the With expression. - /// The converter reuses a With expression such as a ByRef parameter directly as the receiver (With b : Inc(.X) becomes Inc(ref b.X)), - /// so the local function uses whatever that expression uses. + /// A local function can't use the enclosing method's ByRef parameters (CS1628), so it takes each one its converted body uses as a ref parameter. + /// Deciding from the converted body covers a parameter that's only reached through a With block's implicit receiver + /// (With b : Inc(.X) becomes Inc(ref b.X)), and leaves out one that the With header already evaluated into withBlock. + /// VB doesn't allow a local or lambda parameter to shadow a parameter, so a name in the body can only refer to that parameter or a member. /// - private IEnumerable DescendantsResolvingWithReceivers(IOperation operation) => - operation.DescendantsAndSelf().SelectMany(o => - o is IInstanceReferenceOperation { ReferenceKind: InstanceReferenceKind.ImplicitReceiver } && - o.Syntax is VBSyntax.ExpressionSyntax { Parent: VBSyntax.WithStatementSyntax } withExpression && - _semanticModel.GetOperation(withExpression) is { } withOperation - ? DescendantsResolvingWithReceivers(withOperation) - : new[] { o }); + private static List RefParametersUsedIn(BlockSyntax block, ISymbol enclosingSymbol) + { + var refParameters = (enclosingSymbol as IMethodSymbol)?.Parameters.Where(p => p.RefKind != RefKind.None).ToList(); + if (refParameters is not { Count: > 0 }) return new List(); + var namesUsed = block.DescendantNodes().OfType().Where(IsNotAMemberName).Select(n => n.Identifier.ValueText).ToList(); + return refParameters.Where(p => namesUsed.Contains(p.Name, StringComparer.OrdinalIgnoreCase)) + .OrderBy(p => namesUsed.FindIndex(n => string.Equals(n, p.Name, StringComparison.OrdinalIgnoreCase))).ToList(); + + static bool IsNotAMemberName(IdentifierNameSyntax name) => + name.Parent switch { + MemberAccessExpressionSyntax member => member.Expression == name, + MemberBindingExpressionSyntax or NameColonSyntax => false, + _ => true + }; + } public bool RequiresLocalFunction(VBSyntax.InvocationExpressionSyntax invocation, IMethodSymbol invocationSymbol) { diff --git a/Tests/CSharp/ExpressionTests/ByRefTests.cs b/Tests/CSharp/ExpressionTests/ByRefTests.cs index 944bb75d7..0656950ef 100644 --- a/Tests/CSharp/ExpressionTests/ByRefTests.cs +++ b/Tests/CSharp/ExpressionTests/ByRefTests.cs @@ -1866,6 +1866,69 @@ public void M(ref Box b, ref T p) if (localInc1(ref p) > 0) p.P = 0; } +}"); + } + [Fact] + public async Task ByRefParameterOnlyInAWithHeaderIsNotPassedAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Public Class Box + Public Property X As Integer +End Class + +Public Class C + Shared Function Inc(ByRef v As Integer) As Integer + v += 1 + Return v + End Function + + Shared Function GetBox(ByRef b As Box) As Box + Return b + End Function + + Sub M(ByRef arr As Box(), i As Integer, ByRef b As Box) + With arr(i) + If Inc(.X) > 0 Then .X = 0 + End With + With GetBox(b) + If Inc(.X) > 0 Then .X = 0 + End With + End Sub +End Class", @" +public partial class Box +{ + public int X { get; set; } +} + +public partial class C +{ + public static int Inc(ref int v) + { + v += 1; + return v; + } + + public static Box GetBox(ref Box b) + { + return b; + } + + public void M(ref Box[] arr, int i, ref Box b) + { + { + ref var withBlock = ref arr[i]; + int localInc(ref Box withBlock) { int argv = withBlock.X; var ret = Inc(ref argv); withBlock.X = argv; return ret; } + + if (localInc(ref withBlock) > 0) + withBlock.X = 0; + } + { + var withBlock1 = GetBox(ref b); + int localInc1() { int argv1 = withBlock1.X; var ret = Inc(ref argv1); withBlock1.X = argv1; return ret; } + + if (localInc1() > 0) + withBlock1.X = 0; + } + } }"); } [Fact] From 4645ea1bd177761485bccc4b04c4c1761ecd98d0 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 20:57:28 +0000 Subject: [PATCH 47/56] Throw when a ref local reference has no recorded type Every annotation comes from Mark, which records the type, so a miss is a bug; a null type would only surface later as broken output. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- CodeConverter/CSharp/ByRefArguments/RefLocalReferences.cs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/CodeConverter/CSharp/ByRefArguments/RefLocalReferences.cs b/CodeConverter/CSharp/ByRefArguments/RefLocalReferences.cs index 0c8e396cc..9a3de0962 100644 --- a/CodeConverter/CSharp/ByRefArguments/RefLocalReferences.cs +++ b/CodeConverter/CSharp/ByRefArguments/RefLocalReferences.cs @@ -31,6 +31,11 @@ public static IdentifierNameSyntax Mark(IdentifierNameSyntax reference, TypeSynt .Where(n => !declaredInside.Contains(n.Identifier.ValueText)) .GroupBy(n => n.Identifier.ValueText) .Select(g => g.First()) - .Select(n => (n, RefLocalTypes.TryGetValue(n.GetAnnotations(AnnotationKind).First(), out var type) ? type : null)); + .Select(n => (n, GetRefLocalType(n))); } + + private static TypeSyntax GetRefLocalType(IdentifierNameSyntax reference) => + RefLocalTypes.TryGetValue(reference.GetAnnotations(AnnotationKind).First(), out var type) + ? type + : throw new InvalidOperationException($"Ref local reference {reference} was annotated without {nameof(Mark)}"); } From 553c78ef19b5b83978411c4a6ee6a8cd6606bfd8 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 20:58:18 +0000 Subject: [PATCH 48/56] Pin that a structure's Shared member's local function takes no self Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- Tests/CSharp/ExpressionTests/ByRefTests.cs | 36 ++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/Tests/CSharp/ExpressionTests/ByRefTests.cs b/Tests/CSharp/ExpressionTests/ByRefTests.cs index 0656950ef..2c83fb65e 100644 --- a/Tests/CSharp/ExpressionTests/ByRefTests.cs +++ b/Tests/CSharp/ExpressionTests/ByRefTests.cs @@ -1929,6 +1929,42 @@ public void M(ref Box[] arr, int i, ref Box b) withBlock1.X = 0; } } +}"); + } + [Fact] + public async Task StructureSharedMemberDoesNotPassThisAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Public Structure S + Public Shared Property Total As Integer + + Shared Function Inc(ByRef v As Integer) As Integer + v += 1 + Return v + End Function + + Shared Function M() As Boolean + If Inc(Total) > 0 Then Return Total = 1 + Return False + End Function +End Structure", @" +public partial struct S +{ + public static int Total { get; set; } + + public static int Inc(ref int v) + { + v += 1; + return v; + } + + public static bool M() + { + int localInc() { int argv = Total; var ret = Inc(ref argv); Total = argv; return ret; } + + if (localInc() > 0) + return Total == 1; + return false; + } }"); } [Fact] From bc8edc01ad0539382e51de813f9744b72b881234 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 21:08:30 +0000 Subject: [PATCH 49/56] Copy a With block's class reference instead of taking a ref to it VB evaluates a With expression once. For a structure variable it then works on the variable in place, but for a class it keeps the reference, so reassigning the variable inside the block doesn't change the object the block uses. ref var withBlock = ref b followed the reassignment (VB "1,0", C# "0,1"). This existed before this branch. Only a value (or unconstrained) type now gets a ref local. Changed expectations, both class types: - MethodStatementTests.WithBlockWithNullConditionalAccessAsync: ref var withBlock = ref _Data; -> var withBlock = _Data; - ByRefTests.ByRefParameterOnlyInAWithHeaderIsNotPassedAsync: var withBlock = arr[i]; so the local function takes no withBlock. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- .../CSharp/MethodBodyExecutableStatementVisitor.cs | 3 ++- Tests/CSharp/ExpressionTests/ByRefTests.cs | 6 +++--- Tests/CSharp/StatementTests/MethodStatementTests.cs | 2 +- .../VBToCS/ByRefWriteBackPlacementTests.vb | 10 ++++++++++ 4 files changed, 16 insertions(+), 5 deletions(-) diff --git a/CodeConverter/CSharp/MethodBodyExecutableStatementVisitor.cs b/CodeConverter/CSharp/MethodBodyExecutableStatementVisitor.cs index 577f78d56..9d2a20c4e 100644 --- a/CodeConverter/CSharp/MethodBodyExecutableStatementVisitor.cs +++ b/CodeConverter/CSharp/MethodBodyExecutableStatementVisitor.cs @@ -1004,7 +1004,8 @@ private static CasePatternSwitchLabelSyntax VarWhen(SyntaxToken varName, Express reusableExprWithoutSideEffects = expr.WithoutSourceMapping(); } else { TypeSyntax forceType = null; - if (_semanticModel.GetOperation(vbExpr.SkipIntoParens()).IsAssignableExpression()) { + // VB's With uses a structure variable in place, but only copies a reference, so it keeps the original object even if the variable is reassigned + if (_semanticModel.GetTypeInfo(vbExpr).Type?.IsReferenceType != true && _semanticModel.GetOperation(vbExpr.SkipIntoParens()).IsAssignableExpression()) { forceType = SyntaxFactory.RefType(ValidSyntaxFactory.VarType); expr = SyntaxFactory.RefExpression(expr); } diff --git a/Tests/CSharp/ExpressionTests/ByRefTests.cs b/Tests/CSharp/ExpressionTests/ByRefTests.cs index 2c83fb65e..863d61f13 100644 --- a/Tests/CSharp/ExpressionTests/ByRefTests.cs +++ b/Tests/CSharp/ExpressionTests/ByRefTests.cs @@ -1915,10 +1915,10 @@ public static Box GetBox(ref Box b) public void M(ref Box[] arr, int i, ref Box b) { { - ref var withBlock = ref arr[i]; - int localInc(ref Box withBlock) { int argv = withBlock.X; var ret = Inc(ref argv); withBlock.X = argv; return ret; } + var withBlock = arr[i]; + int localInc() { int argv = withBlock.X; var ret = Inc(ref argv); withBlock.X = argv; return ret; } - if (localInc(ref withBlock) > 0) + if (localInc() > 0) withBlock.X = 0; } { diff --git a/Tests/CSharp/StatementTests/MethodStatementTests.cs b/Tests/CSharp/StatementTests/MethodStatementTests.cs index 1bcc291c6..27e708dee 100644 --- a/Tests/CSharp/StatementTests/MethodStatementTests.cs +++ b/Tests/CSharp/StatementTests/MethodStatementTests.cs @@ -1782,7 +1782,7 @@ public partial class TestClass public void TestMethod() { { - ref var withBlock = ref _Data; + var withBlock = _Data; x = withBlock.x?.Name; } } diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb index 9cef412bd..c5d60f607 100644 --- a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb @@ -685,6 +685,16 @@ Public Class ByRefWriteBackPlacementTests Assert.Equal(11, CounterHolder.IncrementInWithByRefParameters(h, c)) Assert.Equal(1, c.P) End Sub + + Public Sub WithOverAReassignedClassVariableKeepsTheOriginalObject() + Dim h As New CounterHolder + Dim original = h + With h + h = New CounterHolder + .Total = 1 + End With + Assert.Equal("1,0", original.Total & "," & h.Total) + End Sub Private Class CounterHolder Public Inner As Counter Public Property Total As Integer From 0d0ecc2f6c888569a3ae9901ba80e49ed71f0ede Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 21:09:18 +0000 Subject: [PATCH 50/56] Note that MyBase can't reach a structure's local function The suggested gap, MyBase.GetHashCode() in a hoisted argument in a Structure, isn't valid VB: the source gives BC30044 ('MyBase' is not valid within a structure), so there's no conversion to get wrong. Record that in the README rather than listing it as a gap. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- CodeConverter/CSharp/ByRefArguments/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CodeConverter/CSharp/ByRefArguments/README.md b/CodeConverter/CSharp/ByRefArguments/README.md index e1f022cfb..72dffc1eb 100644 --- a/CodeConverter/CSharp/ByRefArguments/README.md +++ b/CodeConverter/CSharp/ByRefArguments/README.md @@ -27,7 +27,7 @@ Sources: [passing arguments by value and by reference](https://learn.microsoft.c 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`. -In a `Structure`, a local function can't use `this` (CS1673). When the call uses an instance member, the local function takes `ref S self` and is called with `ref this`, and its body uses `self` for `this` (the converted body always qualifies instance members, which are only simplified later). `ref this` is legal wherever VB can use `Me` in a structure; VB has no read-only members (where it's CS1605) and no `Me` in a structure's lambdas (BC36638): `WriteBackPlacement.HoistAndCallLocalFunctionAsync`. +In a `Structure`, a local function can't use `this` (CS1673). When the call uses an instance member, the local function takes `ref S self` and is called with `ref this`, and its body uses `self` for `this` (the converted body always qualifies instance members, which are only simplified later). `ref this` is legal wherever VB can use `Me` in a structure; VB has no read-only members (where it's CS1605), no `Me` in a structure's lambdas (BC36638) and no `MyBase` in a structure (BC30044, so an unqualified base call can't be hoisted): `WriteBackPlacement.HoistAndCallLocalFunctionAsync`. A local function can't use a ref local either (CS8175), such as the `ref var withBlock` of a `With` over a structure field. References to a ref local are marked with its type, and the local function takes each one it uses from outside its body as a `ref` parameter of the same name: `RefLocalReferences`. The enclosing method's ByRef parameters are passed the same way (CS1628), including one reused directly as a `With` receiver (`With b : Inc(.X)` becomes `Inc(ref b.X)`): `WriteBackPlacement.RefParametersUsedIn`. From 12ba18608fcd3f4ce22537363ce2580d092990e9 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 21:14:34 +0000 Subject: [PATCH 51/56] Test ByRef parameterized properties in a structure and in With blocks #9 now passes `ref this`, With ref locals and ByRef parameters to the write-back local function. Pin that a parameterized property's setter write-back and its index temporaries go through those: `self.set_Qr(tmp, ...)`, `self[i] = ...` for `Me(i)`, and `withBlock`/`s` for a With over a structure field or ByRef parameter, in If and While conditions and in an operand. No converter change was needed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- Tests/CSharp/ExpressionTests/ByRefTests.cs | 143 +++++++++++++ ...efParameterizedPropertyInStructureTests.vb | 199 ++++++++++++++++++ 2 files changed, 342 insertions(+) create mode 100644 Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyInStructureTests.vb diff --git a/Tests/CSharp/ExpressionTests/ByRefTests.cs b/Tests/CSharp/ExpressionTests/ByRefTests.cs index 97b6415b1..a75e052c9 100644 --- a/Tests/CSharp/ExpressionTests/ByRefTests.cs +++ b/Tests/CSharp/ExpressionTests/ByRefTests.cs @@ -2796,6 +2796,149 @@ public void M(int i) public static void SetValue(ref string value) { } +}"); + } + + [Fact] + public async Task ParameterizedPropertyInAStructureOrWithBlockIsWrittenBackInTheLocalFunctionAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Public Structure S + Private _n As Integer + + Public Property Qr(a As Integer, b As Integer) As String + Get + Return """" + End Get + Set(value As String) + End Set + End Property + + Default Public Property Item(a As Integer) As String + Get + Return """" + End Get + Set(value As String) + End Set + End Property + + Public Function NextIndex() As Integer + _n += 1 + Return _n + End Function + + Public Sub M(i As Integer) + If SetValue(Qr(NextIndex(), 2)) Then + End If + If SetValue(Me(i)) Then + End If + End Sub + + Public Shared Sub WithByRef(ByRef s As S) + With s + If SetValue(.Qr(.NextIndex(), 2)) Then + End If + End With + End Sub + + Private Shared Function SetValue(ByRef v As String) As Boolean + v = ""changed"" + Return True + End Function +End Structure + +Public Class Holder + Public F As S + + Public Sub WithField() + With F + If SetValue(.Qr(.NextIndex(), 2)) Then + End If + End With + End Sub + + Private Shared Function SetValue(ByRef v As String) As Boolean + Return True + End Function +End Class", @" +public partial struct S +{ + private int _n; + + public string get_Qr(int a, int b) + { + return """"; + } + public void set_Qr(int a, int b, string value) + { + } + + public string this[int a] + { + get + { + return """"; + } + set + { + } + } + + public int NextIndex() + { + _n += 1; + return _n; + } + + public void M(int i) + { + bool localSetValue(ref S self) { var tmp = self.NextIndex(); string argv = self.get_Qr(tmp, 2); var ret = SetValue(ref argv); self.set_Qr(tmp, 2, argv); return ret; } + + if (localSetValue(ref this)) + { + } + bool localSetValue1(ref S self) { string argv1 = self[i]; var ret = SetValue(ref argv1); self[i] = argv1; return ret; } + + if (localSetValue1(ref this)) + { + } + } + + public static void WithByRef(ref S s) + { + bool localSetValue(ref S s) { var tmp1 = s.NextIndex(); string argv2 = s.get_Qr(tmp1, 2); var ret = SetValue(ref argv2); s.set_Qr(tmp1, 2, argv2); return ret; } + + if (localSetValue(ref s)) + { + } + } + + private static bool SetValue(ref string v) + { + v = ""changed""; + return true; + } +} + +public partial class Holder +{ + public S F; + + public void WithField() + { + { + ref var withBlock = ref F; + bool localSetValue(ref S withBlock) { var tmp2 = withBlock.NextIndex(); string argv3 = withBlock.get_Qr(tmp2, 2); var ret = SetValue(ref argv3); withBlock.set_Qr(tmp2, 2, argv3); return ret; } + + if (localSetValue(ref withBlock)) + { + } + } + } + + private static bool SetValue(ref string v) + { + return true; + } }"); } } \ No newline at end of file diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyInStructureTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyInStructureTests.vb new file mode 100644 index 000000000..d5c44b7a8 --- /dev/null +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyInStructureTests.vb @@ -0,0 +1,199 @@ +Imports System +Imports System.Collections.Generic +Imports Xunit + +Public Class ByRefParameterizedPropertyInStructureTests + + + Public Sub StructureParameterizedPropertyInIfConditionWritesBackBeforeTheBody() + Dim s As New SDb + Assert.Equal("index 1;get 1,2;set 1,2=changed;body changed", s.ParamPropInIf()) + End Sub + + + Public Sub StructureDefaultPropertyOnMeInIfConditionEvaluatesItsIndexOnce() + Dim s As New SDb + Assert.Equal("index 1;getd 1;setd 1=changed;body changed", s.MeDefaultInIf()) + End Sub + + + Public Sub StructureDefaultPropertyOnMeInIfConditionWritesBack() + Dim s As New SDb + Assert.Equal("getd 3;setd 3=changed;body changed", s.MeDefaultPlainInIf(3)) + End Sub + + + Public Sub StructureParameterizedPropertyOperandWritesBackBeforeTheNextOperand() + Dim s As New SDb + Assert.Equal("index 1;get 1,2;set 1,2=changed;10", s.ParamPropOperand()) + End Sub + + + Public Sub StructureWithMeParameterizedPropertyInIfConditionWritesBack() + Dim s As New SDb + Assert.Equal("index 1;get 1,2;set 1,2=changed;body changed", s.WithMeInIf()) + End Sub + + + Public Sub WithStructureFieldParameterizedPropertyInIfConditionWritesBackInPlace() + Dim h As New Holder + Assert.Equal("index 1;get 1,2;set 1,2=changed;body changed", h.WithFieldInIf()) + Assert.Equal("changed", h.S.Stored) + End Sub + + + Public Sub WithByRefStructureParameterParameterizedPropertyInIfConditionWritesBackInPlace() + Dim s As New SDb + Assert.Equal("index 1;get 1,2;set 1,2=changed;body changed", Holder.WithByRefInIf(s)) + Assert.Equal("changed", s.Stored) + End Sub + + + Public Sub WithClassLocalParameterizedPropertyInIfConditionWritesBack() + Assert.Equal("index 1;get 1,2;set 1,2=changed;body changed", Holder.WithClassInIf()) + End Sub + + + Public Sub StructureParameterizedPropertyInWhileConditionWritesBackEachTime() + Dim s As New SDb + Assert.Equal("index 1;get 1,2;set 1,2=changed;loop;index 2;get 2,2;set 2,2=changed;", s.WhileLoop()) + End Sub + + Public Class CDb + Public Log As String = "" + Public Stored As String = "orig" + Public Property Qr(a As Integer, b As Integer) As String + Get + Log &= "get " & a & "," & b & ";" + Return Stored + End Get + Set(value As String) + Log &= "set " & a & "," & b & "=" & value & ";" + Stored = value + End Set + End Property + Public Function NextIndex() As Integer + Log &= "index 1;" + Return 1 + End Function + End Class + + Public Structure SDb + Public Log As String + Public Stored As String + Private _n As Integer + + Public Property Qr(a As Integer, b As Integer) As String + Get + Log &= "get " & a & "," & b & ";" + Return Stored + End Get + Set(value As String) + Log &= "set " & a & "," & b & "=" & value & ";" + Stored = value + End Set + End Property + + Default Public Property Item(a As Integer) As String + Get + Log &= "getd " & a & ";" + Return Stored + End Get + Set(value As String) + Log &= "setd " & a & "=" & value & ";" + Stored = value + End Set + End Property + + Public Function NextIndex() As Integer + _n += 1 + Log &= "index " & _n & ";" + Return _n + End Function + + Public Function ParamPropInIf() As String + If SetValue(Qr(NextIndex(), 2)) Then + Log &= "body " & Stored + End If + Return Log + End Function + + Public Function MeDefaultInIf() As String + If SetValue(Me(NextIndex())) Then + Log &= "body " & Stored + End If + Return Log + End Function + + Public Function MeDefaultPlainInIf(i As Integer) As String + If SetValue(Me(i)) Then + Log &= "body " & Stored + End If + Return Log + End Function + + Public Function ParamPropOperand() As String + Dim r = Len(SetValueS(Qr(NextIndex(), 2))) + Len(Stored) + Return Log & (r - 4) + End Function + + Public Function WithMeInIf() As String + With Me + If SetValue(.Qr(.NextIndex(), 2)) Then + Log &= "body " & .Stored + End If + End With + Return Log + End Function + + Public Function WhileLoop() As String + While SetValue(Qr(NextIndex(), 2)) AndAlso _n < 2 + Log &= "loop;" + Stored = "orig" + End While + Return Log + End Function + End Structure + + Public Class Holder + Public S As SDb + + Public Function WithFieldInIf() As String + With S + If SetValue(.Qr(.NextIndex(), 2)) Then + .Log &= "body " & .Stored + End If + End With + Return S.Log + End Function + + Public Shared Function WithByRefInIf(ByRef s As SDb) As String + With s + If SetValue(.Qr(.NextIndex(), 2)) Then + .Log &= "body " & .Stored + End If + End With + Return s.Log + End Function + + Public Shared Function WithClassInIf() As String + Dim c As New CDb + With c + If SetValue(.Qr(.NextIndex(), 2)) Then + .Log &= "body " & .Stored + End If + End With + Return c.Log + End Function + End Class + + Private Shared Function SetValue(ByRef v As String) As Boolean + v = "changed" + Return True + End Function + + Private Shared Function SetValueS(ByRef v As String) As String + v = "changed" + Return v + End Function +End Class From c15ced0c915566365daff322b82da1d3fe75f3c5 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 21:51:29 +0000 Subject: [PATCH 52/56] Take a local function's ByRef parameters from the VB call's references 879fd38 matched a parent ByRef parameter by name in the converted body, case-insensitively, so a type named like the parameter counted as a use: H.S beside ByRef h As H passed ref h (CS0269, unassigned out parameter), and New H() beside ByRef h As Integer passed an unused ref h. The candidates now come from the parameters the VB operations reference, with a With block's implicit receiver resolved to its With expression, as before 879fd38. The converted body is then used only to drop candidates it no longer mentions, i.e. a header evaluated into withBlock. Names compare ordinally, since the converter writes a parameter reference with its declared casing. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- CodeConverter/CSharp/ByRefArguments/README.md | 2 +- .../ByRefArguments/WriteBackPlacement.cs | 36 ++++++--- Tests/CSharp/ExpressionTests/ByRefTests.cs | 74 +++++++++++++++++++ .../VBToCS/ByRefWriteBackPlacementTests.vb | 18 +++++ 4 files changed, 119 insertions(+), 11 deletions(-) diff --git a/CodeConverter/CSharp/ByRefArguments/README.md b/CodeConverter/CSharp/ByRefArguments/README.md index 72dffc1eb..2ca2c98ab 100644 --- a/CodeConverter/CSharp/ByRefArguments/README.md +++ b/CodeConverter/CSharp/ByRefArguments/README.md @@ -29,7 +29,7 @@ Within each of these, one call's write-backs are hoisted after its whole argumen In a `Structure`, a local function can't use `this` (CS1673). When the call uses an instance member, the local function takes `ref S self` and is called with `ref this`, and its body uses `self` for `this` (the converted body always qualifies instance members, which are only simplified later). `ref this` is legal wherever VB can use `Me` in a structure; VB has no read-only members (where it's CS1605), no `Me` in a structure's lambdas (BC36638) and no `MyBase` in a structure (BC30044, so an unqualified base call can't be hoisted): `WriteBackPlacement.HoistAndCallLocalFunctionAsync`. -A local function can't use a ref local either (CS8175), such as the `ref var withBlock` of a `With` over a structure field. References to a ref local are marked with its type, and the local function takes each one it uses from outside its body as a `ref` parameter of the same name: `RefLocalReferences`. The enclosing method's ByRef parameters are passed the same way (CS1628), including one reused directly as a `With` receiver (`With b : Inc(.X)` becomes `Inc(ref b.X)`): `WriteBackPlacement.RefParametersUsedIn`. +A local function can't use a ref local either (CS8175), such as the `ref var withBlock` of a `With` over a structure field. References to a ref local are marked with its type, and the local function takes each one it uses from outside its body as a `ref` parameter of the same name: `RefLocalReferences`. The enclosing method's ByRef parameters are passed the same way (CS1628), including one reused directly as a `With` receiver (`With b : Inc(.X)` becomes `Inc(ref b.X)`). The candidates are the parameters the VB operations reference, so a type named like a parameter isn't one, and the converted body then drops those it no longer mentions (a header evaluated into `withBlock`): `WriteBackPlacement.RefParametersUsedIn`. 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). diff --git a/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs b/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs index 2313cddae..c5ff3f7b8 100644 --- a/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs +++ b/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs @@ -56,7 +56,7 @@ public async Task HoistAndCallLocalFunctionAsync(VBa parameters.Add(RefParameter(selfName, CommonConversions.GetTypeSyntax(enclosingSymbol.ContainingType))); } - AddArgumentsAndParameters(RefParametersUsedIn(block, enclosingSymbol)); + AddArgumentsAndParameters(RefParametersUsedIn(invocation, block, enclosingSymbol)); foreach (var (reference, type) in RefLocalReferences.FindIn(block)) { arguments.Add(SyntaxFactory.Argument(reference).WithRefKindKeyword(SyntaxFactory.Token(SyntaxKind.RefKeyword))); @@ -84,17 +84,22 @@ void AddArgumentsAndParameters(List parameterSymbols) /// /// A local function can't use the enclosing method's ByRef parameters (CS1628), so it takes each one its converted body uses as a ref parameter. - /// Deciding from the converted body covers a parameter that's only reached through a With block's implicit receiver - /// (With b : Inc(.X) becomes Inc(ref b.X)), and leaves out one that the With header already evaluated into withBlock. - /// VB doesn't allow a local or lambda parameter to shadow a parameter, so a name in the body can only refer to that parameter or a member. + /// The candidates are the parameters the VB call references, so a type or namespace with the same name as a parameter (H.S beside h As H) isn't one. + /// A With block's implicit receiver counts as its With expression, because the converter may reuse that expression directly + /// (With b : Inc(.X) becomes Inc(ref b.X)). + /// A candidate is then dropped if the converted body doesn't mention it, i.e. the With header was evaluated into withBlock (With arr(i)). + /// The converter writes a parameter reference with the declared casing, so the names compare ordinally. /// - private static List RefParametersUsedIn(BlockSyntax block, ISymbol enclosingSymbol) + private List RefParametersUsedIn(VBasic.VisualBasicSyntaxNode invocation, BlockSyntax block, ISymbol enclosingSymbol) { - var refParameters = (enclosingSymbol as IMethodSymbol)?.Parameters.Where(p => p.RefKind != RefKind.None).ToList(); - if (refParameters is not { Count: > 0 }) return new List(); - var namesUsed = block.DescendantNodes().OfType().Where(IsNotAMemberName).Select(n => n.Identifier.ValueText).ToList(); - return refParameters.Where(p => namesUsed.Contains(p.Name, StringComparer.OrdinalIgnoreCase)) - .OrderBy(p => namesUsed.FindIndex(n => string.Equals(n, p.Name, StringComparison.OrdinalIgnoreCase))).ToList(); + if (_semanticModel.GetOperation(invocation) is not { } operation) return new List(); + var candidates = DescendantsResolvingWithReceivers(operation) + .OfType().Select(p => p.Parameter) + .Where(p => p.RefKind != RefKind.None && SymbolEqualityComparer.Default.Equals(p.ContainingSymbol, enclosingSymbol)) + .Distinct(SymbolEqualityComparer.Default).ToList(); + if (candidates.Count == 0) return candidates; + var namesUsed = new HashSet(block.DescendantNodes().OfType().Where(IsNotAMemberName).Select(n => n.Identifier.ValueText), StringComparer.Ordinal); + return candidates.Where(p => namesUsed.Contains(p.Name)).ToList(); static bool IsNotAMemberName(IdentifierNameSyntax name) => name.Parent switch { @@ -104,6 +109,17 @@ static bool IsNotAMemberName(IdentifierNameSyntax name) => }; } + /// + /// The operations within , where a With block's implicit receiver is replaced by the operations of the With expression. + /// + private IEnumerable DescendantsResolvingWithReceivers(IOperation operation) => + operation.DescendantsAndSelf().SelectMany(o => + o is IInstanceReferenceOperation { ReferenceKind: InstanceReferenceKind.ImplicitReceiver } && + o.Syntax is VBSyntax.ExpressionSyntax { Parent: VBSyntax.WithStatementSyntax } withExpression && + _semanticModel.GetOperation(withExpression) is { } withOperation + ? DescendantsResolvingWithReceivers(withOperation) + : new[] { o }); + public bool RequiresLocalFunction(VBSyntax.InvocationExpressionSyntax invocation, IMethodSymbol invocationSymbol) { if (IsLoopCondition(invocation)) { diff --git a/Tests/CSharp/ExpressionTests/ByRefTests.cs b/Tests/CSharp/ExpressionTests/ByRefTests.cs index 863d61f13..7d3316be3 100644 --- a/Tests/CSharp/ExpressionTests/ByRefTests.cs +++ b/Tests/CSharp/ExpressionTests/ByRefTests.cs @@ -1965,6 +1965,80 @@ public static bool M() return Total == 1; return false; } +}"); + } + [Fact] + public async Task TypeNamedLikeAByRefParameterIsNotPassedAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Public Class H + Public Shared Property S As Integer + Public Property Q As Integer +End Class + +Public Class C + Shared Function Inc(ByRef v As Integer) As Integer + v += 1 + Return v + End Function + + Shared Function GetH(q As Integer) As H + Return New H + End Function + + Shared Function M( ByRef h As H) As Boolean + If Inc(H.S) > 0 Then + h = New H + Return True + End If + h = Nothing + Return False + End Function + + Shared Function M2(ByRef h As Integer, x As H) As Boolean + If Inc(GetH(New H().Q).Q) > 0 Then Return True + Return False + End Function +End Class", @" +public partial class H +{ + public static int S { get; set; } + public int Q { get; set; } +} + +public partial class C +{ + public static int Inc(ref int v) + { + v += 1; + return v; + } + + public static H GetH(int q) + { + return new H(); + } + + public static bool M(out H h) + { + int localInc() { int argv = H.S; var ret = Inc(ref argv); H.S = argv; return ret; } + + if (localInc() > 0) + { + h = new H(); + return true; + } + h = null; + return false; + } + + public static bool M2(ref int h, H x) + { + int localInc() { int argv1 = GetH(new H().Q).Q; var ret = Inc(ref argv1); GetH(new H().Q).Q = argv1; return ret; } + + if (localInc() > 0) + return true; + return false; + } }"); } [Fact] diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb index c5d60f607..580c87a7e 100644 --- a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb @@ -695,6 +695,24 @@ Public Class ByRefWriteBackPlacementTests End With Assert.Equal("1,0", original.Total & "," & h.Total) End Sub + + Public Sub OutParameterNamedLikeItsTypeIsNotPassedToTheLocalFunction() + Tally.Count = 0 + Dim created As Tally = Nothing + Assert.True(TryCreateTally(created)) + Assert.Equal("1,True", Tally.Count & "," & (created IsNot Nothing)) + End Sub + Private Shared Function TryCreateTally( ByRef tally As Tally) As Boolean + If Increment(Tally.Count) > 0 Then + tally = New Tally + Return True + End If + tally = Nothing + Return False + End Function + Private Class Tally + Public Shared Property Count As Integer + End Class Private Class CounterHolder Public Inner As Counter Public Property Total As Integer From b870edb3ccacb36bf359791f128d42d76a3aa97d Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 22:06:26 +0000 Subject: [PATCH 53/56] Evaluate the receiver once in #9's TypeNamedLikeAByRefParameterIsNotPassed test #9's new test expected `GetH(new H().Q).Q` read and then written back by calling `GetH` again. This branch's receiver temporaries evaluate it once, as VB does (UseTwiceRewriter), and write back to the same object: `var tmp = GetH(new H().Q); ... tmp.Q = argv1;`. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- Tests/CSharp/ExpressionTests/ByRefTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tests/CSharp/ExpressionTests/ByRefTests.cs b/Tests/CSharp/ExpressionTests/ByRefTests.cs index 5e8b22147..92e27906f 100644 --- a/Tests/CSharp/ExpressionTests/ByRefTests.cs +++ b/Tests/CSharp/ExpressionTests/ByRefTests.cs @@ -2032,7 +2032,7 @@ public static bool M(out H h) public static bool M2(ref int h, H x) { - int localInc() { int argv1 = GetH(new H().Q).Q; var ret = Inc(ref argv1); GetH(new H().Q).Q = argv1; return ret; } + int localInc() { var tmp = GetH(new H().Q); int argv1 = tmp.Q; var ret = Inc(ref argv1); tmp.Q = argv1; return ret; } if (localInc() > 0) return true; From 666d5768457b660c2807c0b59adb95830e7e8882 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 22:20:21 +0000 Subject: [PATCH 54/56] Pass a ByRef parameter with a keyword name to the local function `ByRef [class] As Box` converts to `@class`, and CsEscapedIdentifier's token keeps the `@` in its ValueText. RefParametersUsedIn compared the body's names with the unescaped `p.Name`, so the parameter wasn't passed and the local function used it directly (CS1628). Compare against the escaped name, and declare and pass the parameter with the same escaped identifier, so the tree binds as its text does (`ref @params`). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- .../ByRefArguments/WriteBackPlacement.cs | 8 ++-- Tests/CSharp/ExpressionTests/ByRefTests.cs | 46 +++++++++++++++++++ .../VBToCS/ByRefWriteBackPlacementTests.vb | 12 +++++ 3 files changed, 62 insertions(+), 4 deletions(-) diff --git a/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs b/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs index c5ff3f7b8..2d198f7a7 100644 --- a/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs +++ b/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs @@ -74,10 +74,10 @@ static ParameterSyntax RefParameter(string name, TypeSyntax type) => void AddArgumentsAndParameters(List parameterSymbols) { foreach (var p in parameterSymbols) { - var arg = (ArgumentSyntax)CommonConversions.CsSyntaxGenerator.Argument(p.RefKind, SyntaxFactory.IdentifierName(p.Name)); + var arg = (ArgumentSyntax)CommonConversions.CsSyntaxGenerator.Argument(p.RefKind, ValidSyntaxFactory.IdentifierName(p.Name)); arguments.Add(arg); var par = (ParameterSyntax)CommonConversions.CsSyntaxGenerator.ParameterDeclaration(p); - parameters.Add(par.WithDefault(null)); + parameters.Add(par.WithIdentifier(CommonConversions.CsEscapedIdentifier(p.Name)).WithDefault(null)); } } } @@ -88,7 +88,7 @@ void AddArgumentsAndParameters(List parameterSymbols) /// A With block's implicit receiver counts as its With expression, because the converter may reuse that expression directly /// (With b : Inc(.X) becomes Inc(ref b.X)). /// A candidate is then dropped if the converted body doesn't mention it, i.e. the With header was evaluated into withBlock (With arr(i)). - /// The converter writes a parameter reference with the declared casing, so the names compare ordinally. + /// The converter writes a parameter reference with the declared casing, escaped like any identifier (@params, whose token text keeps the @), so the names compare ordinally after the same escaping. /// private List RefParametersUsedIn(VBasic.VisualBasicSyntaxNode invocation, BlockSyntax block, ISymbol enclosingSymbol) { @@ -99,7 +99,7 @@ private List RefParametersUsedIn(VBasic.VisualBasicSyntaxNode .Distinct(SymbolEqualityComparer.Default).ToList(); if (candidates.Count == 0) return candidates; var namesUsed = new HashSet(block.DescendantNodes().OfType().Where(IsNotAMemberName).Select(n => n.Identifier.ValueText), StringComparer.Ordinal); - return candidates.Where(p => namesUsed.Contains(p.Name)).ToList(); + return candidates.Where(p => namesUsed.Contains(CommonConversions.CsEscapedIdentifier(p.Name).ValueText)).ToList(); static bool IsNotAMemberName(IdentifierNameSyntax name) => name.Parent switch { diff --git a/Tests/CSharp/ExpressionTests/ByRefTests.cs b/Tests/CSharp/ExpressionTests/ByRefTests.cs index 92e27906f..622150d99 100644 --- a/Tests/CSharp/ExpressionTests/ByRefTests.cs +++ b/Tests/CSharp/ExpressionTests/ByRefTests.cs @@ -1966,6 +1966,52 @@ public static bool M() } }"); } + [Fact] + public async Task KeywordNamedByRefParametersArePassedToTheLocalFunctionAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Public Class Box + Public Property P As Integer +End Class + +Public Class C + Shared Function Inc(ByRef v As Integer) As Integer + v += 1 + Return v + End Function + + Shared Function M(ByRef [class] As Box, ByRef params As Box, ByRef [string] As Box) As Boolean + If Inc([class].P) + Inc(params.P) + Inc([string].P) > 0 Then Return True + Return False + End Function +End Class", @" +public partial class Box +{ + public int P { get; set; } +} + +public partial class C +{ + public static int Inc(ref int v) + { + v += 1; + return v; + } + + public static bool M(ref Box @class, ref Box @params, ref Box @string) + { + int localInc(ref Box @class) { var tmp = @class; int argv = tmp.P; var ret = Inc(ref argv); tmp.P = argv; return ret; } + + int localInc1(ref Box @params) { var tmp1 = @params; int argv1 = tmp1.P; var ret = Inc(ref argv1); tmp1.P = argv1; return ret; } + + int localInc2(ref Box @string) { var tmp2 = @string; int argv2 = tmp2.P; var ret = Inc(ref argv2); tmp2.P = argv2; return ret; } + + if (localInc(ref @class) + localInc1(ref @params) + localInc2(ref @string) > 0) + return true; + return false; + } +}"); + } + [Fact] public async Task TypeNamedLikeAByRefParameterIsNotPassedAsync() { diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb index 580c87a7e..e73e7ddcb 100644 --- a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb @@ -696,6 +696,18 @@ Public Class ByRefWriteBackPlacementTests Assert.Equal("1,0", original.Total & "," & h.Total) End Sub + Public Sub ByRefParametersWithKeywordNamesArePassedToTheLocalFunction() + Dim a As New Counter, b As New Counter, c As New Counter + Assert.True(IncrementKeywordNamedParameters(a, b, c)) + Assert.Equal("1,1,1", a.P & "," & b.P & "," & c.P) + End Sub + Private Shared Function IncrementKeywordNamedParameters(ByRef [class] As Counter, ByRef params As Counter, ByRef [string] As Counter) As Boolean + If Increment([class].P) + Increment(params.P) + Increment([string].P) = 3 Then + Return [class].P + params.P + [string].P = 3 + End If + Return False + End Function + Public Sub OutParameterNamedLikeItsTypeIsNotPassedToTheLocalFunction() Tally.Count = 0 Dim created As Tally = Nothing From bcdfa5fd37d52b3aff69e36cf76cbc334ff82f0d Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 22:21:58 +0000 Subject: [PATCH 55/56] Don't pass a ByRef parameter named only by an anonymous-type member In `With arr(i)`, `Inc(Take(New With {.i = 1}, .Inner).P)` with a ByRef `i` gave `localInc(ref int i)`: the body's `new { i = 1 }` counted as a use of `i`. A NameEquals name is a member name, like a NameColon one. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- .../ByRefArguments/WriteBackPlacement.cs | 2 +- Tests/CSharp/ExpressionTests/ByRefTests.cs | 56 +++++++++++++++++++ 2 files changed, 57 insertions(+), 1 deletion(-) diff --git a/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs b/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs index 2d198f7a7..099a18490 100644 --- a/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs +++ b/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs @@ -104,7 +104,7 @@ private List RefParametersUsedIn(VBasic.VisualBasicSyntaxNode static bool IsNotAMemberName(IdentifierNameSyntax name) => name.Parent switch { MemberAccessExpressionSyntax member => member.Expression == name, - MemberBindingExpressionSyntax or NameColonSyntax => false, + MemberBindingExpressionSyntax or NameColonSyntax or NameEqualsSyntax => false, _ => true }; } diff --git a/Tests/CSharp/ExpressionTests/ByRefTests.cs b/Tests/CSharp/ExpressionTests/ByRefTests.cs index 622150d99..11e8e68e2 100644 --- a/Tests/CSharp/ExpressionTests/ByRefTests.cs +++ b/Tests/CSharp/ExpressionTests/ByRefTests.cs @@ -2012,6 +2012,62 @@ public static bool M(ref Box @class, ref Box @params, ref Box @string) }"); } + [Fact] + public async Task AnonymousTypeMemberNamedLikeAByRefParameterIsNotPassedAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Public Class Box + Public Property P As Integer + Public Property Inner As Box +End Class + +Public Class C + Shared Function Inc(ByRef v As Integer) As Integer + v += 1 + Return v + End Function + + Shared Function Take(o As Object, b As Box) As Box + Return b + End Function + + Sub M(arr As Box(), ByRef i As Integer) + With arr(i) + If Inc(Take(New With {.i = 1}, .Inner).P) > 0 Then .P = 0 + End With + End Sub +End Class", @" +public partial class Box +{ + public int P { get; set; } + public Box Inner { get; set; } +} + +public partial class C +{ + public static int Inc(ref int v) + { + v += 1; + return v; + } + + public static Box Take(object o, Box b) + { + return b; + } + + public void M(Box[] arr, ref int i) + { + { + var withBlock = arr[i]; + int localInc() { var tmp = Take(new { i = 1 }, withBlock.Inner); int argv = tmp.P; var ret = Inc(ref argv); tmp.P = argv; return ret; } + + if (localInc() > 0) + withBlock.P = 0; + } + } +}"); + } + [Fact] public async Task TypeNamedLikeAByRefParameterIsNotPassedAsync() { From 7c244dd9810c199c616ebbad204864308e1a3556 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 22:39:31 +0000 Subject: [PATCH 56/56] Don't pass a ByRef parameter named only by an object-initializer member In `With arr(i)`, `Inc(Take(New Box With {.i = 1}, .Inner).P)` with a ByRef `i` gave `localInc(ref int i)`: the body's `new Box() { i = 1 }` counted as a use of `i`. The left side of an object initializer's assignment is a member name, like a NameEquals one. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- .../ByRefArguments/WriteBackPlacement.cs | 1 + Tests/CSharp/ExpressionTests/ByRefTests.cs | 58 +++++++++++++++++++ 2 files changed, 59 insertions(+) diff --git a/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs b/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs index 099a18490..f97ca8995 100644 --- a/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs +++ b/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs @@ -105,6 +105,7 @@ static bool IsNotAMemberName(IdentifierNameSyntax name) => name.Parent switch { MemberAccessExpressionSyntax member => member.Expression == name, MemberBindingExpressionSyntax or NameColonSyntax or NameEqualsSyntax => false, + AssignmentExpressionSyntax { Parent: InitializerExpressionSyntax initializer } assignment when initializer.IsKind(CS.SyntaxKind.ObjectInitializerExpression) => assignment.Left != name, _ => true }; } diff --git a/Tests/CSharp/ExpressionTests/ByRefTests.cs b/Tests/CSharp/ExpressionTests/ByRefTests.cs index 11e8e68e2..f6cd5ce67 100644 --- a/Tests/CSharp/ExpressionTests/ByRefTests.cs +++ b/Tests/CSharp/ExpressionTests/ByRefTests.cs @@ -2068,6 +2068,64 @@ public void M(Box[] arr, ref int i) }"); } + [Fact] + public async Task ObjectInitializerMemberNamedLikeAByRefParameterIsNotPassedAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Public Class Box + Public Property P As Integer + Public i As Integer + Public Property Inner As Box +End Class + +Public Class C + Shared Function Inc(ByRef v As Integer) As Integer + v += 1 + Return v + End Function + + Shared Function Take(o As Object, b As Box) As Box + Return b + End Function + + Sub M(arr As Box(), ByRef i As Integer) + With arr(i) + If Inc(Take(New Box With {.i = 1}, .Inner).P) > 0 Then .P = 0 + End With + End Sub +End Class", @" +public partial class Box +{ + public int P { get; set; } + public int i; + public Box Inner { get; set; } +} + +public partial class C +{ + public static int Inc(ref int v) + { + v += 1; + return v; + } + + public static Box Take(object o, Box b) + { + return b; + } + + public void M(Box[] arr, ref int i) + { + { + var withBlock = arr[i]; + int localInc() { var tmp = Take(new Box() { i = 1 }, withBlock.Inner); int argv = tmp.P; var ret = Inc(ref argv); tmp.P = argv; return ret; } + + if (localInc() > 0) + withBlock.P = 0; + } + } +}"); + } + [Fact] public async Task TypeNamedLikeAByRefParameterIsNotPassedAsync() {