Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
9c3ed81
Write back ByRef arguments before return, throw and yield (#896)
claude Nov 11, 2026
be0f178
Write back ByRef arguments in block headers before the body
claude Nov 11, 2026
e5728f8
Move write-back-before-use into PerScopeState
claude Nov 11, 2026
d636135
Keep ByRef temporaries of field initializers in a method (#1081)
claude Nov 11, 2026
24fab8d
Make partial-class initial value functions instance methods
claude Nov 12, 2026
b842673
Document where ByRef temporaries and write-backs are placed
claude Nov 12, 2026
7377689
Drop unreachable case when naming a field initializer method
claude Nov 12, 2026
c34406e
Emit each field initializer method once, including for WithEvents
claude Nov 12, 2026
e360aff
Document remaining ByRef write-back gaps found in review
claude Nov 12, 2026
d7f02d1
Drop dead renaming of hoisted initializer methods
claude Nov 12, 2026
5043b0f
Give field initializer methods names unused by other members
claude Nov 12, 2026
9031b61
Document further pre-existing ByRef gaps found in review
claude Nov 12, 2026
0cffd9b
Write back a call's ByRef arguments in reverse order, like VB
claude Nov 16, 2026
9967913
Write back each Dim declarator before the next is evaluated
claude Nov 17, 2026
912e14d
Write back before an assignment stores to what's written back
claude Nov 17, 2026
c39d4ca
Say "multiple" rather than "several" declarators
claude Nov 17, 2026
74a6a79
Extract ByRef argument handling into CSharp/ByRefArguments
claude Nov 17, 2026
92e89b1
Remove the byte order mark added to NameExpressionNodeVisitor.cs
claude Nov 17, 2026
47b99ef
Name a local function's result so it can't hide a name in use
claude Nov 17, 2026
81f4e51
Assign through a result local when a simple target is written back
claude Nov 17, 2026
d1d4226
Keep statement placement in a struct where a local function needs this
claude Nov 17, 2026
a09e199
Treat a ByRef extension receiver like a written-back argument
claude Nov 17, 2026
a2a214d
Document further ByRef write-back gaps found in review
claude Nov 17, 2026
d22baa0
Never move a struct call that uses this into a local function
claude Nov 17, 2026
c8c3931
Cover the remaining write-back placement branches with tests
claude Nov 17, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 6 additions & 28 deletions CodeConverter/CSharp/ArgumentConverter.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Microsoft.VisualBasic;
using ICSharpCode.CodeConverter.CSharp.ByRefArguments;
using Microsoft.VisualBasic;

namespace ICSharpCode.CodeConverter.CSharp;

Expand All @@ -9,6 +10,7 @@ internal class ArgumentConverter
private readonly ITypeContext _typeContext;
private readonly SemanticModel _semanticModel;
private CommentConvertingVisitorWrapper TriviaConvertingExpressionVisitor { get; }
public ByRefArgumentHoister ByRefArgumentHoister { get; }

public ArgumentConverter(VisualBasicEqualityComparison visualBasicEqualityComparison, ITypeContext typeContext, SemanticModel semanticModel, CommonConversions commonConversions)
{
Expand All @@ -17,6 +19,7 @@ public ArgumentConverter(VisualBasicEqualityComparison visualBasicEqualityCompar
_typeContext = typeContext;
_semanticModel = semanticModel;
TriviaConvertingExpressionVisitor = commonConversions.TriviaConvertingExpressionVisitor;
ByRefArgumentHoister = new ByRefArgumentHoister(typeContext, semanticModel, commonConversions);
}

public async Task<CSharpSyntaxNode> ConvertSimpleArgumentAsync(VBSyntax.SimpleArgumentSyntax node)
Expand All @@ -35,7 +38,7 @@ public async Task<CSharpSyntaxNode> ConvertSimpleArgumentAsync(VBSyntax.SimpleAr
var refType = CommonConversions.GetRefConversionType(node, argList, possibleParameters.Value, out var argName, out var refKind);
token = CommonConversions.GetRefToken(refKind);
if (refType != SemanticModelExtensions.RefConversion.Inline) {
convertedArgExpression = HoistByRefDeclaration(node.Expression, convertedArgExpression, refType, argName, refKind);
convertedArgExpression = ByRefArgumentHoister.HoistByRefDeclaration(node.Expression, convertedArgExpression, refType, argName, refKind);
} else {
convertedArgExpression = typeConversionAnalyzer.AddExplicitConversion(node.Expression, convertedArgExpression, defaultToCast: refKind != RefKind.None);
}
Expand All @@ -54,7 +57,7 @@ public async Task<CSharpSyntaxNode> ConvertSimpleArgumentAsync(VBSyntax.SimpleAr
var invocationHasOverloads = invocationSymbol.HasOverloads();

var processedParameters = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var argumentSyntaxs = (await node.Arguments.SelectAsync(ConvertArg)).Where(a => a != null);
var argumentSyntaxs = (await ByRefArgumentHoister.WithWriteBacksInVbOrderAsync(() => node.Arguments.SelectAsync(ConvertArg))).Where(a => a != null);
return Enumerable.Concat(argumentSyntaxs, GetAdditionalRequiredArgs(node.Arguments, processedParameters, invocationSymbol, invocationHasOverloads));

async Task<CSSyntax.ArgumentSyntax> ConvertArg(VBSyntax.ArgumentSyntax arg, int argIndex)
Expand Down Expand Up @@ -119,31 +122,6 @@ CSSyntax.ArgumentSyntax ConvertOmittedArgument(IParameterSymbol parameter)
}


internal CSSyntax.ExpressionSyntax HoistByRefDeclaration(VBSyntax.ExpressionSyntax node, CSSyntax.ExpressionSyntax refLValue, SemanticModelExtensions.RefConversion refType, string argName, RefKind refKind)
{
string prefix = $"arg{argName}";
var expressionTypeInfo = _semanticModel.GetTypeInfo(node);
bool useVar = expressionTypeInfo.Type?.Equals(expressionTypeInfo.ConvertedType, SymbolEqualityComparer.IncludeNullability) == true && !CommonConversions.ShouldPreferExplicitType(node, expressionTypeInfo.ConvertedType, out var _);
var typeSyntax = CommonConversions.GetTypeSyntax(expressionTypeInfo.ConvertedType, useVar);

if (refLValue is CSSyntax.ElementAccessExpressionSyntax eae) {
//Hoist out the container so we can assign back to the same one after (like VB does)
var tmpContainer = _typeContext.PerScopeState.Hoist(new AdditionalDeclaration("tmp", eae.Expression, ValidSyntaxFactory.VarType));
refLValue = eae.WithExpression(tmpContainer.IdentifierName);
}

var withCast = CommonConversions.TypeConversionAnalyzer.AddExplicitConversion(node, refLValue, defaultToCast: refKind != RefKind.None);

var local = _typeContext.PerScopeState.Hoist(new AdditionalDeclaration(prefix, withCast, typeSyntax));

if (refType == SemanticModelExtensions.RefConversion.PreAndPostAssignment) {
var convertedLocalIdentifier = CommonConversions.TypeConversionAnalyzer.AddExplicitConversion(node, local.IdentifierName, forceSourceType: expressionTypeInfo.ConvertedType, forceTargetType: expressionTypeInfo.Type);
_typeContext.PerScopeState.Hoist(new AdditionalAssignment(refLValue, convertedLocalIdentifier));
}

return local.IdentifierName;
}

private static CSSyntax.ExpressionSyntax LiteralOrDefault(object value, ITypeSymbol paramType)
{
if (value is null && paramType.IsValueType) {
Expand Down
68 changes: 68 additions & 0 deletions CodeConverter/CSharp/ByRefArguments/ByRefArgumentHoister.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
namespace ICSharpCode.CodeConverter.CSharp.ByRefArguments;

/// <summary>
/// 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.
/// </summary>
internal class ByRefArgumentHoister
{
private readonly ITypeContext _typeContext;
private readonly SemanticModel _semanticModel;
private CommonConversions CommonConversions { get; }

/// <summary>
/// The write-backs of each argument list being converted, innermost call on top.
/// </summary>
private readonly Stack<List<AdditionalAssignment>> _writeBacksPerCall = new();

public ByRefArgumentHoister(ITypeContext typeContext, SemanticModel semanticModel, CommonConversions commonConversions)
{
_typeContext = typeContext;
_semanticModel = semanticModel;
CommonConversions = commonConversions;
}

/// <summary>
/// VB copies back a call's ByRef arguments from the last to the first (copyBackArray.ReverseContents() in Roslyn's LocalRewriter_Call.vb),
/// which is observable when two arguments write back to the same place.
/// A nested call has already written back by then, so only this call's own write-backs are reversed.
/// </summary>
public async Task<T> WithWriteBacksInVbOrderAsync<T>(Func<Task<T>> convertArguments)
{
_writeBacksPerCall.Push(new List<AdditionalAssignment>());
T converted;
try {
converted = await convertArguments();
} finally {
var writeBacks = _writeBacksPerCall.Pop();
foreach (var writeBack in Enumerable.Reverse(writeBacks)) _typeContext.PerScopeState.Hoist(writeBack);
}
return converted;
}

public CSSyntax.ExpressionSyntax HoistByRefDeclaration(VBSyntax.ExpressionSyntax node, CSSyntax.ExpressionSyntax refLValue, SemanticModelExtensions.RefConversion refType, string argName, RefKind refKind)
{
string prefix = $"arg{argName}";
var expressionTypeInfo = _semanticModel.GetTypeInfo(node);
bool useVar = expressionTypeInfo.Type?.Equals(expressionTypeInfo.ConvertedType, SymbolEqualityComparer.IncludeNullability) == true && !CommonConversions.ShouldPreferExplicitType(node, expressionTypeInfo.ConvertedType, out var _);
var typeSyntax = CommonConversions.GetTypeSyntax(expressionTypeInfo.ConvertedType, useVar);

if (refLValue is CSSyntax.ElementAccessExpressionSyntax eae) {
//Hoist out the container so we can assign back to the same one after (like VB does)
var tmpContainer = _typeContext.PerScopeState.Hoist(new AdditionalDeclaration("tmp", eae.Expression, ValidSyntaxFactory.VarType));
refLValue = eae.WithExpression(tmpContainer.IdentifierName);
}

var withCast = CommonConversions.TypeConversionAnalyzer.AddExplicitConversion(node, refLValue, defaultToCast: refKind != RefKind.None);

var local = _typeContext.PerScopeState.Hoist(new AdditionalDeclaration(prefix, withCast, typeSyntax));

if (refType == SemanticModelExtensions.RefConversion.PreAndPostAssignment) {
var convertedLocalIdentifier = CommonConversions.TypeConversionAnalyzer.AddExplicitConversion(node, local.IdentifierName, forceSourceType: expressionTypeInfo.ConvertedType, forceTargetType: expressionTypeInfo.Type);
var writeBack = new AdditionalAssignment(refLValue, convertedLocalIdentifier);
if (_writeBacksPerCall.Count > 0) _writeBacksPerCall.Peek().Add(writeBack);
else _typeContext.PerScopeState.Hoist(writeBack);
}

return local.IdentifierName;
}
}
45 changes: 45 additions & 0 deletions CodeConverter/CSharp/ByRefArguments/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# VB → C# ByRef arguments that need a temporary

Sources: [passing arguments by value and by reference](https://learn.microsoft.com/dotnet/visual-basic/programming-guide/language-features/procedures/passing-arguments-by-value-and-by-reference) and Roslyn's VB lowering in [`LocalRewriter_Call.vb`](https://github.com/dotnet/roslyn/blob/main/src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_Call.vb): `RewriteByRefArgumentWithCopyBack` creates the temporary, and `VisitCall` wraps the call in a sequence whose side effects after the value are the copy-backs. Behaviour below is covered by `Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb`.

## VB

* A ByRef parameter accepts any expression. If it isn't a variable (a property, a method result, a constant, an omitted `Optional` argument), VB passes a temporary.
* For a writable property (or a `ReadOnly` auto-property inside its constructor), VB copies the temporary back **straight after the call returns**, before the rest of the enclosing expression or statement runs.
* One call copies back its arguments from the last to the first (`copyBackArray.ReverseContents()` in `LocalRewriter_Call.vb`). It's observable when two arguments write back to the same place, e.g. `Two(p.Value, p.Value)`. A call nested in an argument has already copied back by then.

## C#

* `ref`/`out` need a variable, so the temporary must be declared in a statement before the call.
* There is no expression-level copy-back, so a write-back is a statement too.

## Implementation

`ByRefArgumentHoister.HoistByRefDeclaration` hoists the temporary (`AdditionalDeclaration`) and, when VB copies back, the write-back (`AdditionalAssignment`) into the current `PerScopeState` scope. `PerScopeState.CreateLocalsAsync` emits them before and after the converted statement. The output takes the simplest form that keeps VB's timing:

| Where the call is | C# | Code |
|---|---|---|
| A statement, as the last thing evaluated, including the right of an assignment whose target isn't read by the write-back (`Q = F(P)`) | temporary before, write-back after the statement | `PerScopeState.CreateLocalsAsync` |
| `=` to a plain name or `Me.X` that the write-back reads (`P = F(P)`, `x = F(h.Items(x))`, `h = F(h.P)`) | `var ret = call; write-back; P = ret;` | `WriteBackPlacement.IsSimpleTargetReadByWriteBack`, `MethodBodyExecutableStatementVisitor.VisitAssignmentStatement` |
| `Return`, `Throw`, `Yield` | `var ret = call; write-back; return ret;` (only when there is a write-back) | `PerScopeState.WithWriteBacksBefore` |
| Followed by other evaluation, or in a condition or block header (`If`, `ElseIf`, loops, `Select Case`, `Case`, `For`, `For Each`, `Using`, `SyncLock`, `With`, `Catch When`), or in one of multiple `Dim` declarators, or the right of a compound assignment, or one whose target has a receiver or index, that the write-back reads (`h.P = F(h.P)`, `x += F(h.Items(x))`): C# evaluates the target first and stores last, as VB does, and the write-back happens in between | a local function that declares, calls and writes back, called in place | `WriteBackPlacement.RequiresLocalFunction`, `HoistAndCallLocalFunctionAsync` |
| A field initializer | a method that declares, writes back and returns, called from the field (static) or the constructor (instance) | `CommonConversions.WithHoistedNodesInMethodAsync`, `PerScopeState.CreateReturnBlockAsync` |

Within each of these, one call's write-backs are hoisted after its whole argument list, last argument first, so a nested call's come before them: `ByRefArgumentHoister.WithWriteBacksInVbOrderAsync`.

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:
* `h1.P = F(h2.P)` where `h1 Is h2` still writes back after the assignment.
* `a.P = F(b.P)` takes the local function even when `a` and `b` are different objects, because two names can always refer to the same object.
* `WF = New W(WF.Name)`, a ByRef constructor argument in an assignment, writes back to the new object: object creation doesn't take the assignment placement.
* The write-back re-evaluates the target's receiver, so `F(GetH(h).P)` calls `GetH` twice. Hoisting the receiver into a temporary is left to the parameterized-property work (#909), which adds that for its own targets.
* A setter with side effects on the written-back target, e.g. `Other = F(P)` where `Other`'s setter writes `P`, runs before the write-back instead of after it.
* A lambda parameter inside a ByRef argument (`Function(x) Inc(x.P)`) hoists the local function outside the lambda, where `x` isn't in scope (CS0103).
* An auto-property initializer (`Public Property X As Integer = Inc(P)`) leaves a `ph…` placeholder (CS0103): it doesn't go through the field initializer path.
* Partial-class instance initializers run in part order rather than declaration order.
* 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.
Loading
Loading