diff --git a/CodeConverter/CSharp/ArgumentConverter.cs b/CodeConverter/CSharp/ArgumentConverter.cs index 6eec58ac3..adf31ce65 100644 --- a/CodeConverter/CSharp/ArgumentConverter.cs +++ b/CodeConverter/CSharp/ArgumentConverter.cs @@ -1,4 +1,5 @@ -using Microsoft.VisualBasic; +using ICSharpCode.CodeConverter.CSharp.ByRefArguments; +using Microsoft.VisualBasic; namespace ICSharpCode.CodeConverter.CSharp; @@ -9,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) { @@ -17,6 +19,7 @@ public ArgumentConverter(VisualBasicEqualityComparison visualBasicEqualityCompar _typeContext = typeContext; _semanticModel = semanticModel; TriviaConvertingExpressionVisitor = commonConversions.TriviaConvertingExpressionVisitor; + ByRefArgumentHoister = new ByRefArgumentHoister(typeContext, semanticModel, commonConversions); } public async Task ConvertSimpleArgumentAsync(VBSyntax.SimpleArgumentSyntax node) @@ -35,7 +38,7 @@ public async Task ConvertSimpleArgumentAsync(VBSyntax.SimpleAr var refType = CommonConversions.GetRefConversionType(node, argList, possibleParameters.Value, out var argName, out var refKind); token = CommonConversions.GetRefToken(refKind); if (refType != SemanticModelExtensions.RefConversion.Inline) { - convertedArgExpression = HoistByRefDeclaration(node.Expression, convertedArgExpression, refType, argName, refKind); + convertedArgExpression = ByRefArgumentHoister.HoistByRefDeclaration(node.Expression, convertedArgExpression, refType, argName, refKind); } else { convertedArgExpression = typeConversionAnalyzer.AddExplicitConversion(node.Expression, convertedArgExpression, defaultToCast: refKind != RefKind.None); } @@ -54,7 +57,7 @@ public async Task ConvertSimpleArgumentAsync(VBSyntax.SimpleAr var invocationHasOverloads = invocationSymbol.HasOverloads(); var processedParameters = new HashSet(StringComparer.OrdinalIgnoreCase); - var argumentSyntaxs = (await node.Arguments.SelectAsync(ConvertArg)).Where(a => a != null); + var argumentSyntaxs = (await ByRefArgumentHoister.WithWriteBacksInVbOrderAsync(() => node.Arguments.SelectAsync(ConvertArg))).Where(a => a != null); return Enumerable.Concat(argumentSyntaxs, GetAdditionalRequiredArgs(node.Arguments, processedParameters, invocationSymbol, invocationHasOverloads)); async Task ConvertArg(VBSyntax.ArgumentSyntax arg, int argIndex) @@ -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) { diff --git a/CodeConverter/CSharp/ByRefArguments/ByRefArgumentHoister.cs b/CodeConverter/CSharp/ByRefArguments/ByRefArgumentHoister.cs new file mode 100644 index 000000000..abd89565e --- /dev/null +++ b/CodeConverter/CSharp/ByRefArguments/ByRefArgumentHoister.cs @@ -0,0 +1,68 @@ +namespace ICSharpCode.CodeConverter.CSharp.ByRefArguments; + +/// +/// C# can only pass a variable by reference, so a ByRef argument that isn't one gets a temporary, and VB's copy-back becomes a write-back statement. +/// +internal class ByRefArgumentHoister +{ + private readonly ITypeContext _typeContext; + private readonly SemanticModel _semanticModel; + private CommonConversions CommonConversions { get; } + + /// + /// The write-backs of each argument list being converted, innermost call on top. + /// + private readonly Stack> _writeBacksPerCall = new(); + + public ByRefArgumentHoister(ITypeContext typeContext, SemanticModel semanticModel, CommonConversions commonConversions) + { + _typeContext = typeContext; + _semanticModel = semanticModel; + CommonConversions = commonConversions; + } + + /// + /// VB copies back a call's ByRef arguments from the last to the first (copyBackArray.ReverseContents() in Roslyn's LocalRewriter_Call.vb), + /// which is observable when two arguments write back to the same place. + /// A nested call has already written back by then, so only this call's own write-backs are reversed. + /// + public async Task WithWriteBacksInVbOrderAsync(Func> convertArguments) + { + _writeBacksPerCall.Push(new List()); + T converted; + try { + converted = await convertArguments(); + } finally { + var writeBacks = _writeBacksPerCall.Pop(); + foreach (var writeBack in Enumerable.Reverse(writeBacks)) _typeContext.PerScopeState.Hoist(writeBack); + } + return converted; + } + + public CSSyntax.ExpressionSyntax HoistByRefDeclaration(VBSyntax.ExpressionSyntax node, CSSyntax.ExpressionSyntax refLValue, SemanticModelExtensions.RefConversion refType, string argName, RefKind refKind) + { + string prefix = $"arg{argName}"; + var expressionTypeInfo = _semanticModel.GetTypeInfo(node); + bool useVar = expressionTypeInfo.Type?.Equals(expressionTypeInfo.ConvertedType, SymbolEqualityComparer.IncludeNullability) == true && !CommonConversions.ShouldPreferExplicitType(node, expressionTypeInfo.ConvertedType, out var _); + var typeSyntax = CommonConversions.GetTypeSyntax(expressionTypeInfo.ConvertedType, useVar); + + if (refLValue is CSSyntax.ElementAccessExpressionSyntax eae) { + //Hoist out the container so we can assign back to the same one after (like VB does) + var tmpContainer = _typeContext.PerScopeState.Hoist(new AdditionalDeclaration("tmp", eae.Expression, ValidSyntaxFactory.VarType)); + refLValue = eae.WithExpression(tmpContainer.IdentifierName); + } + + var withCast = CommonConversions.TypeConversionAnalyzer.AddExplicitConversion(node, refLValue, defaultToCast: refKind != RefKind.None); + + var local = _typeContext.PerScopeState.Hoist(new AdditionalDeclaration(prefix, withCast, typeSyntax)); + + if (refType == SemanticModelExtensions.RefConversion.PreAndPostAssignment) { + var convertedLocalIdentifier = CommonConversions.TypeConversionAnalyzer.AddExplicitConversion(node, local.IdentifierName, forceSourceType: expressionTypeInfo.ConvertedType, forceTargetType: expressionTypeInfo.Type); + var writeBack = new AdditionalAssignment(refLValue, convertedLocalIdentifier); + if (_writeBacksPerCall.Count > 0) _writeBacksPerCall.Peek().Add(writeBack); + else _typeContext.PerScopeState.Hoist(writeBack); + } + + return local.IdentifierName; + } +} diff --git a/CodeConverter/CSharp/ByRefArguments/README.md b/CodeConverter/CSharp/ByRefArguments/README.md new file mode 100644 index 000000000..e5567face --- /dev/null +++ b/CodeConverter/CSharp/ByRefArguments/README.md @@ -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. diff --git a/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs b/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs new file mode 100644 index 000000000..982457c1a --- /dev/null +++ b/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs @@ -0,0 +1,277 @@ +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Operations; +using static ICSharpCode.CodeConverter.CSharp.SemanticModelExtensions; + +namespace ICSharpCode.CodeConverter.CSharp.ByRefArguments; + +/// +/// Decides whether a call's ByRef temporaries can be declared before, and written back after, the converted statement, +/// and otherwise moves the call into a local function that writes back straight after it, as VB does. +/// +internal class WriteBackPlacement +{ + private readonly SemanticModel _semanticModel; + private readonly HashSet _generatedNames; + private readonly ITypeContext _typeContext; + + public WriteBackPlacement(SemanticModel semanticModel, HashSet generatedNames, ITypeContext typeContext, CommonConversions commonConversions) + { + _semanticModel = semanticModel; + _generatedNames = generatedNames; + _typeContext = typeContext; + CommonConversions = commonConversions; + } + + private CommonConversions CommonConversions { get; } + + /// + /// The VB compiler actually just hoists the conditions within the same method, but that leads to the original logic looking very different. + /// This should be equivalent but keep closer to the look of the original source code. + /// See https://github.com/icsharpcode/CodeConverter/issues/310 and https://github.com/icsharpcode/CodeConverter/issues/324 + /// + public async Task HoistAndCallLocalFunctionAsync(VBasic.VisualBasicSyntaxNode invocation, IMethodSymbol invocationSymbol, ExpressionSyntax csExpression) + { + // Each local function is its own scope, so only names visible at the call can clash, e.g. a parameter used in the argument + var retVariableName = NameGenerator.CS.GetUniqueVariableNameInScope(_semanticModel, new HashSet(), invocation, "ret"); + var localFuncName = $"local{invocationSymbol.Name}"; + + var callAndStoreResult = CommonConversions.CreateLocalVariableDeclarationAndAssignment(retVariableName, csExpression); + + var statements = await _typeContext.PerScopeState.CreateLocalsAsync(invocation, new[] { callAndStoreResult }, _generatedNames, _semanticModel); + + var block = SyntaxFactory.Block( + statements.Concat(SyntaxFactory.ReturnStatement(ValidSyntaxFactory.IdentifierName(retVariableName)).Yield()) + ); + var returnType = CommonConversions.GetTypeSyntax(invocationSymbol.ReturnType); + + // Parent ByRef parameters cannot be captured, including references in receivers and nested argument expressions. + var enclosingSymbol = _semanticModel.GetEnclosingSymbol(invocation.SpanStart); + var refParametersOfParent = (_semanticModel.GetOperation(invocation)?.DescendantsAndSelf() + .OfType().Select(p => p.Parameter) ?? Enumerable.Empty()) + .Where(p => p.RefKind != RefKind.None && SymbolEqualityComparer.Default.Equals(p.ContainingSymbol, enclosingSymbol)) + .Distinct(SymbolEqualityComparer.Default).ToList(); + var (args, @params) = CreateArgumentsAndParametersLists(refParametersOfParent); + + var localFunc = _typeContext.PerScopeState.Hoist(new HoistedFunction(localFuncName, returnType, block, SyntaxFactory.ParameterList(@params))); + return SyntaxFactory.InvocationExpression(localFunc.TempIdentifier, SyntaxFactory.ArgumentList(args)); + + (SeparatedSyntaxList, SeparatedSyntaxList) CreateArgumentsAndParametersLists(List parameterSymbols) + { + var arguments = new List(); + var parameters = new List(); + foreach (var p in parameterSymbols) { + var arg = (ArgumentSyntax)CommonConversions.CsSyntaxGenerator.Argument(p.RefKind, SyntaxFactory.IdentifierName(p.Name)); + arguments.Add(arg); + var par = (ParameterSyntax)CommonConversions.CsSyntaxGenerator.ParameterDeclaration(p); + parameters.Add(par.WithDefault(null)); + } + return (SyntaxFactory.SeparatedList(arguments), SyntaxFactory.SeparatedList(parameters)); + } + } + + public bool RequiresLocalFunction(VBSyntax.InvocationExpressionSyntax invocation, IMethodSymbol invocationSymbol) + { + if (IsLoopCondition(invocation)) { + // A loop condition needs fresh argument temporaries and copy-back on every evaluation. + return invocationSymbol.ReducedFrom?.Parameters.FirstOrDefault() is { RefKind: not RefKind.None } && + invocation.Expression is VBSyntax.MemberAccessExpressionSyntax member && + _semanticModel.GetRefConversionForExpression(member.Expression) != RefConversion.Inline || + invocation.ArgumentList?.Arguments.Any(a => + CommonConversions.GetRefConversionType(a, invocation.ArgumentList, invocationSymbol.Parameters, out _, out _) != RefConversion.Inline) == true || + _semanticModel.GetOperation(invocation) is IInvocationOperation operation && operation.Arguments.Any(a => + a.ArgumentKind == ArgumentKind.DefaultValue && a.Parameter.RefKind != RefKind.None); + } + + if (invocation.ArgumentList == null) return false; + if (IsInStructAndUsesThis(invocation)) return false; + var definitelyExecutedAfterPrevious = DefinitelyExecutedAfterPreviousStatement(invocation); + var assignmentChangesWhatIsWrittenBack = AssignmentChangesWhatIsWrittenBack(invocation, invocationSymbol); + var nextStatementDefinitelyExecuted = NextStatementDefinitelyExecutedAfter(invocation) && !assignmentChangesWhatIsWrittenBack; + if (definitelyExecutedAfterPrevious && nextStatementDefinitelyExecuted) return false; + if (assignmentChangesWhatIsWrittenBack && GetWrittenBackReceiver(invocation, invocationSymbol) is not null) return true; + var possibleInline = definitelyExecutedAfterPrevious ? RefConversion.PreAssigment : RefConversion.Inline; + return invocation.ArgumentList.Arguments.Any(a => RequiresLocalFunction(possibleInline, invocation, invocationSymbol, a)); + + bool RequiresLocalFunction(RefConversion possibleInline, VBSyntax.InvocationExpressionSyntax invocation, IMethodSymbol invocationSymbol, VBSyntax.ArgumentSyntax a) + { + var refConversion = CommonConversions.GetRefConversionType(a, invocation.ArgumentList, invocationSymbol.Parameters, out string _, out _); + if (RefConversion.Inline == refConversion || possibleInline == refConversion) return false; + if (!(a is VBSyntax.SimpleArgumentSyntax sas)) return false; + var argExpression = sas.Expression.SkipIntoParens(); + if (argExpression is VBSyntax.InstanceExpressionSyntax) return false; + return !_semanticModel.GetConstantValue(argExpression).HasValue; + } + } + + /// + /// VB writes back straight after the call, before the enclosing assignment stores its result. + /// A write-back emitted after the assignment statement would overwrite the assigned target (h.P = F(h.P)), + /// or write to a different place if the assignment changes something the write-back target reads (x = F(h.Items(x)), h = F(h.P)). + /// A simple target is handled by the statement instead (see ), so only a compound assignment + /// or a target with a receiver or index to evaluate first needs the local function. + /// + private bool AssignmentChangesWhatIsWrittenBack(VBSyntax.InvocationExpressionSyntax invocation, IMethodSymbol invocationSymbol) + { + if (invocation.Ancestors().FirstOrDefault(n => n is VBSyntax.StatementSyntax or VBSyntax.LambdaExpressionSyntax) is not VBSyntax.AssignmentStatementSyntax assignment || + !assignment.Right.Span.Contains(invocation.Span) || IsSimpleTarget(assignment)) { + return false; + } + + return WritesBackSomethingReading(invocation, invocationSymbol, GetAssignedSymbol(assignment)); + } + + /// + /// For P = F(P) or x = F(h.Items(x)), where the target has nothing to evaluate before the call, + /// var ret = F(...); write-backs; P = ret; keeps VB's order without a local function (which couldn't use this in a struct). + /// + public bool IsSimpleTargetReadByWriteBack(VBSyntax.AssignmentStatementSyntax assignment) + { + if (!IsSimpleTarget(assignment)) return false; + var assignedSymbol = GetAssignedSymbol(assignment); + return assignment.Right.DescendantNodesAndSelf(n => n is not VBSyntax.LambdaExpressionSyntax).OfType() + .Any(i => i.ArgumentList != null && _semanticModel.GetSymbolInfo(i).Symbol is IMethodSymbol method && WritesBackSomethingReading(i, method, assignedSymbol)); + } + + /// + /// The receiver of an extension method whose first parameter is ByRef, e.g. h.P in h.P.Ext(), is written back like an argument. + /// + private VBSyntax.ExpressionSyntax GetWrittenBackReceiver(VBSyntax.InvocationExpressionSyntax invocation, IMethodSymbol invocationSymbol) => + invocationSymbol.ReducedFrom?.Parameters.FirstOrDefault() is { RefKind: not RefKind.None } && + invocation.Expression is VBSyntax.MemberAccessExpressionSyntax { Expression: { } receiver } && + _semanticModel.GetRefConversionForExpression(receiver) == RefConversion.PreAndPostAssignment + ? receiver + : null; + + private static bool IsSimpleTarget(VBSyntax.AssignmentStatementSyntax assignment) => + assignment.IsKind(VBasic.SyntaxKind.SimpleAssignmentStatement) && + assignment.Left.SkipIntoParens() is VBSyntax.IdentifierNameSyntax or VBSyntax.MemberAccessExpressionSyntax { Expression: VBSyntax.MeExpressionSyntax or VBSyntax.MyClassExpressionSyntax }; + + private ISymbol GetAssignedSymbol(VBSyntax.AssignmentStatementSyntax assignment) => + _semanticModel.GetSymbolInfo(assignment.Left).Symbol ?? + (assignment.Left is VBSyntax.InvocationExpressionSyntax { Expression: var indexed } ? _semanticModel.GetSymbolInfo(indexed).Symbol : null); + + private bool WritesBackSomethingReading(VBSyntax.InvocationExpressionSyntax invocation, IMethodSymbol invocationSymbol, ISymbol assignedSymbol) + { + var writtenBackExpressions = invocation.ArgumentList.Arguments.OfType() + .Where(a => CommonConversions.GetRefConversionType(a, invocation.ArgumentList, invocationSymbol.Parameters, out _, out _) == RefConversion.PreAndPostAssignment) + .Select(a => a.Expression) + .Concat(GetWrittenBackReceiver(invocation, invocationSymbol) is { } receiver ? new[] { receiver } : Array.Empty()); + return writtenBackExpressions.Any(e => assignedSymbol is null || + e.DescendantNodesAndSelf().OfType().Any(n => SymbolEqualityComparer.Default.Equals(_semanticModel.GetSymbolInfo(n).Symbol, assignedSymbol))); + } + + public static bool IsLoopCondition(SyntaxNode node) + { + var containingStatement = node.Ancestors().FirstOrDefault(n => n is VBSyntax.StatementSyntax or VBSyntax.LambdaExpressionSyntax); + return containingStatement is VBSyntax.WhileStatementSyntax or VBSyntax.DoStatementSyntax or VBSyntax.LoopStatementSyntax; + } + + /// + /// Conservative version of _semanticModel.AnalyzeControlFlow(invocation).ExitPoints to account for exceptions + /// + /// + /// A local function in a struct can't use this (CS1673), so there the write-back stays after the statement: compiling but late, a known gap. + /// + private bool IsInStructAndUsesThis(VBSyntax.InvocationExpressionSyntax invocation) => + _semanticModel.GetEnclosingSymbol(invocation.SpanStart) is { IsStatic: false, ContainingType.TypeKind: TypeKind.Struct } && + _semanticModel.GetOperation(invocation)?.DescendantsAndSelf().OfType().Any() != false; + + private bool DefinitelyExecutedAfterPreviousStatement(VBSyntax.InvocationExpressionSyntax invocation) + { + SyntaxNode parent = invocation; + while (true) { + parent = parent.Parent; + switch (parent) { + case VBSyntax.ParenthesizedExpressionSyntax _: + continue; + case VBSyntax.BinaryExpressionSyntax binaryExpression: + if (binaryExpression.Left == invocation) continue; + else return false; + case VBSyntax.ArgumentSyntax argumentSyntax: + // Being the leftmost invocation of an unqualified method call ensures no other code is executed. Could add other cases here, such as a method call on a local variable name, or "this.". A method call on a property is not acceptable. + if (argumentSyntax.Parent.Parent is VBSyntax.InvocationExpressionSyntax parentInvocation && parentInvocation.ArgumentList.Arguments.First() == argumentSyntax && FirstArgDefinitelyEvaluated(parentInvocation)) continue; + else return false; + case VBSyntax.VariableDeclaratorSyntax declarator when IsInLocalDeclarationWithMultipleDeclarators(declarator, out var declarators): + if (declarators.First() == declarator) continue; + else return false; + case VBSyntax.ElseIfStatementSyntax _: + case VBSyntax.ExpressionSyntax _: + return false; + case VBSyntax.StatementSyntax _: + return true; + } + } + } + + private bool FirstArgDefinitelyEvaluated(VBSyntax.InvocationExpressionSyntax parentInvocation) => + parentInvocation.Expression.SkipIntoParens() switch { + VBSyntax.IdentifierNameSyntax _ => true, + VBSyntax.MemberAccessExpressionSyntax maes => maes.Expression is { } exp && !MayThrow(exp), + _ => true + }; + + /// + /// Safe overapproximation of whether an expression may throw. + /// + private bool MayThrow(VBSyntax.ExpressionSyntax expression) + { + expression = expression.SkipIntoParens(); + if (expression is VBSyntax.InstanceExpressionSyntax) return false; + var symbol = _semanticModel.GetSymbolInfo(expression).Symbol; + return !symbol.IsKind(SymbolKind.Local) && !symbol.IsKind(SymbolKind.Field); + } + + /// + /// Conservative version of _semanticModel.AnalyzeControlFlow(invocation).ExitPoints to account for exceptions. + /// A block's header statement is followed by its body, so a write-back placed after the converted block would run too late + /// (or, for a later Case clause, run when the clause was never evaluated). + /// + private static bool NextStatementDefinitelyExecutedAfter(VBSyntax.InvocationExpressionSyntax invocation) + { + SyntaxNode parent = invocation; + while (true) { + parent = parent.Parent; + switch (parent) { + case VBSyntax.ParenthesizedExpressionSyntax _: + continue; + case VBSyntax.BinaryExpressionSyntax binaryExpression: + if (binaryExpression.Right == invocation) continue; + else return false; + case VBSyntax.VariableDeclaratorSyntax declarator when IsInLocalDeclarationWithMultipleDeclarators(declarator, out var declarators): + if (declarators.Last() == declarator) continue; + else return false; + case VBSyntax.IfStatementSyntax _: + case VBSyntax.ElseIfStatementSyntax _: + case VBSyntax.SingleLineIfStatementSyntax _: + case VBSyntax.SelectStatementSyntax _: + case VBSyntax.CaseStatementSyntax _: + case VBSyntax.ForStatementSyntax _: + case VBSyntax.ForEachStatementSyntax _: + case VBSyntax.UsingStatementSyntax _: + case VBSyntax.SyncLockStatementSyntax _: + case VBSyntax.WithStatementSyntax _: + case VBSyntax.CatchStatementSyntax _: + return false; + case VBSyntax.ExpressionSyntax _: + case VBSyntax.StatementSyntax _: + return true; + } + } + } + + + /// + /// VB evaluates each declarator of Dim a = F(p.X), b = F(p.X) in turn, writing back before the next one starts, + /// but temporaries and write-backs are hoisted around the whole converted declaration. + /// A Static local's declarators become fields, where a local function couldn't be called, so those keep the old placement. + /// + private static bool IsInLocalDeclarationWithMultipleDeclarators(VBSyntax.VariableDeclaratorSyntax declarator, out SeparatedSyntaxList declarators) + { + declarators = declarator.Parent is VBSyntax.LocalDeclarationStatementSyntax localDeclaration && + !localDeclaration.Modifiers.Any(m => m.IsKind(VBasic.SyntaxKind.StaticKeyword)) + ? localDeclaration.Declarators + : default; + return declarators.Count > 1; + } +} diff --git a/CodeConverter/CSharp/CommonConversions.cs b/CodeConverter/CSharp/CommonConversions.cs index 3f37f1985..dd19cdb98 100644 --- a/CodeConverter/CSharp/CommonConversions.cs +++ b/CodeConverter/CSharp/CommonConversions.cs @@ -61,6 +61,22 @@ public record VariablesDeclaration(CSSyntax.VariableDeclarationSyntax Decl, ITyp public async Task<(IReadOnlyCollection Variables, IReadOnlyCollection Methods)> SplitVariableDeclarationsAsync( VariableDeclaratorSyntax declarator, HashSet symbolsToSkip = null, bool preferExplicitType = false) + { + if (!IsField(declarator)) return await SplitVariableDeclarationsInCurrentScopeAsync(declarator, symbolsToSkip, preferExplicitType); + + // A field initializer has no statement to hoist into, so it gets its own scope, which ConvertEqualsValueClauseSyntaxAsync moves into a method + _typeContext.PerScopeState.PushScope(); + try { + return await SplitVariableDeclarationsInCurrentScopeAsync(declarator, symbolsToSkip, preferExplicitType); + } finally { + _typeContext.PerScopeState.PopScope(); + } + } + + private static bool IsField(VariableDeclaratorSyntax declarator) => declarator.Parent.IsKind(SyntaxKind.FieldDeclaration); + + private async Task<(IReadOnlyCollection Variables, IReadOnlyCollection Methods)> SplitVariableDeclarationsInCurrentScopeAsync( + VariableDeclaratorSyntax declarator, HashSet symbolsToSkip, bool preferExplicitType) { var vbInitValue = GetInitializerToConvert(declarator); var initializerOrMethodDecl = await vbInitValue.AcceptAsync(TriviaConvertingExpressionVisitor); @@ -129,7 +145,7 @@ public bool ShouldPreferExplicitType(VBSyntax.ExpressionSyntax exp, { var csTypeSyntax = GetTypeSyntax(declaredSymbolType); - bool isField = vbDeclarator.Parent.IsKind(SyntaxKind.FieldDeclaration); + bool isField = IsField(vbDeclarator); bool declaredConst = declaredSymbol is IFieldSymbol fieldSymbol && fieldSymbol.IsConst || declaredSymbol is ILocalSymbol localSymbol && localSymbol.IsConst; @@ -144,15 +160,17 @@ public bool ShouldPreferExplicitType(VBSyntax.ExpressionSyntax exp, if (isField && !declaredSymbol.IsStatic && !SemanticModel.IsDefinitelyStatic(vbName, vbInitValue)) { if (!_typeContext.Initializers.HasInstanceConstructorsOutsideThisPart) { var lhs = SyntaxFactory.IdentifierName(ConvertIdentifier(vbName.Identifier, sourceTriviaMapKind: SourceTriviaMapKind.None)); - _typeContext.Initializers.AdditionalInstanceInitializers.Add(new Assignment(lhs, CSSyntaxKind.SimpleAssignmentExpression, adjustedInitializerExpr.WithoutSourceMapping())); + var initializer = await WithHoistedNodesInMethodAsync(vbName, adjustedInitializerExpr, csTypeSyntax, isStatic: false); + _typeContext.Initializers.AdditionalInstanceInitializers.Add(new Assignment(lhs, CSSyntaxKind.SimpleAssignmentExpression, initializer.WithoutSourceMapping())); equalsValueClauseSyntax = null; } else { - var returnBlock = SyntaxFactory.Block(SyntaxFactory.ReturnStatement(adjustedInitializerExpr)); - _typeContext.PerScopeState.Hoist(new HoistedFunction(GetInitialValueFunctionName(vbName), csTypeSyntax, returnBlock, SyntaxFactory.ParameterList())); + var returnBlock = await _typeContext.PerScopeState.CreateReturnBlockAsync(vbName, adjustedInitializerExpr, csTypeSyntax, SemanticModel); + _typeContext.PerScopeState.HoistToParent(new HoistedFunction(GetInitialValueFunctionName(vbName), csTypeSyntax, returnBlock, SyntaxFactory.ParameterList(), isStatic: false)); equalsValueClauseSyntax = null; } } else { - equalsValueClauseSyntax = SyntaxFactory.EqualsValueClause(convertedInitializer); + var initializer = isField ? await WithHoistedNodesInMethodAsync(vbName, convertedInitializer, csTypeSyntax, isStatic: true) : convertedInitializer; + equalsValueClauseSyntax = SyntaxFactory.EqualsValueClause(initializer); } } else if (isField || declaredSymbol != null && SemanticModel.IsDefinitelyAssignedBeforeRead(declaredSymbol, vbName)) @@ -168,6 +186,30 @@ public bool ShouldPreferExplicitType(VBSyntax.ExpressionSyntax exp, return equalsValueClauseSyntax; } + /// + /// Temporaries for ByRef arguments (and their write-backs) need statements, which a field initializer can't contain. + /// A method keeps them together with the initializer whether it stays on the field or moves to the constructor. + /// It must be static to be called from a field initializer, and an instance method to read instance members from the constructor. + /// + private async Task WithHoistedNodesInMethodAsync(VBSyntax.ModifiedIdentifierSyntax vbName, ExpressionSyntax initializer, TypeSyntax type, bool isStatic) + { + if (!_typeContext.PerScopeState.HasHoistedNodes) return initializer; + + var body = await _typeContext.PerScopeState.CreateReturnBlockAsync(vbName, initializer, type, SemanticModel); + var baseMethodName = GetInitializerMethodName(initializer, ConvertIdentifier(vbName.Identifier).ValueText); + var methodName = NameGenerator.CS.GetUniqueVariableNameInScope(SemanticModel, new HashSet(), vbName, baseMethodName); + _typeContext.PerScopeState.HoistToParent(new HoistedFunction(methodName, type, body, SyntaxFactory.ParameterList(), isStatic)); + return SyntaxFactory.InvocationExpression(ValidSyntaxFactory.IdentifierName(methodName)); + } + + private static string GetInitializerMethodName(ExpressionSyntax initializer, string fieldName) + { + // Names are qualified by the time they're converted, e.g. Me.Foo(...) + return initializer is CSSyntax.InvocationExpressionSyntax { Expression: CSSyntax.MemberAccessExpressionSyntax { Name: var invokedName } } + ? $"{invokedName.Identifier.ValueText}_{fieldName}" + : "init" + fieldName.UppercaseFirstLetter(); + } + /// /// In CS we need to lift non-static initializers to the constructor. But for partial classes these can be in different files. /// Rather than re-architect to allow communication between files, we create an initializer function, and call it from the other part, and just hope the name doesn't clash. diff --git a/CodeConverter/CSharp/DeclarationNodeVisitor.cs b/CodeConverter/CSharp/DeclarationNodeVisitor.cs index 74a905a13..7a35d2ef9 100644 --- a/CodeConverter/CSharp/DeclarationNodeVisitor.cs +++ b/CodeConverter/CSharp/DeclarationNodeVisitor.cs @@ -548,20 +548,12 @@ private IEnumerable CreateMemberDeclarations(IReadOnlyC } } + foreach (var method in CreateExtraMethodMembers()) yield return method; if (isWithEvents) { var fieldDecls = CreateWithEventsMembers(thisFieldModifiers, attributes, variablesDecl.Decl); foreach (var f in fieldDecls) yield return f; } else { - foreach (var method in CreateExtraMethodMembers()) yield return method; - - if (AdditionalLocals.GetDeclarations().Any()) { - foreach (var additionalDecl in CreateAdditionalLocalMembers(thisFieldModifiers, attributes, variablesDecl.Decl)) { - yield return additionalDecl; - } - } else { - yield return CS.SyntaxFactory.FieldDeclaration(CS.SyntaxFactory.List(attributes), thisFieldModifiers, variablesDecl.Decl); - } - + yield return CS.SyntaxFactory.FieldDeclaration(CS.SyntaxFactory.List(attributes), thisFieldModifiers, variablesDecl.Decl); } } } @@ -586,67 +578,11 @@ private IEnumerable CreateWithEventsMembers(SyntaxToken return fieldDecls; } - private IEnumerable CreateAdditionalLocalMembers(SyntaxTokenList convertedModifiers, List attributes, VariableDeclarationSyntax decl) - { - if (decl.Variables.Count > 1) { - // Currently no way to tell which _additionalLocals would apply to which initializer - throw new NotImplementedException( - "Fields with multiple declarations and initializers with ByRef parameters not currently supported"); - } - - var v = decl.Variables.First(); - var invocations = v.Initializer.Value.DescendantNodesAndSelf().OfType().ToArray(); - if (invocations.Length > 1) { - throw new NotImplementedException( - "Field initializers with nested method calls not currently supported"); - } - - string newMethodName; - if (invocations.OnlyOrDefault() is { Expression: {} e} && e.ChildNodes().OfType().LastOrDefault() is {} sns) { - newMethodName = $"{sns?.Identifier.ValueText}_{v.Identifier.ValueText}"; - } else { - newMethodName = "init" + v.Identifier.ValueText.UppercaseFirstLetter(); - } - - var declarationInfo = AdditionalLocals.GetDeclarations(); - - var localVars = declarationInfo - .Select(al => CommonConversions.CreateLocalVariableDeclarationAndAssignment(al.Prefix, al.Initializer)) - .ToArray(); - - // This should probably use a unique name like in MethodBodyVisitor - a collision is far less likely here - var newNames = declarationInfo.ToDictionary(l => l.Id, l => l.Prefix); - var newInitializer = PerScopeState.ReplaceNames(v.Initializer.Value, newNames); - - var body = CS.SyntaxFactory.Block(localVars.Concat(CS.SyntaxFactory.ReturnStatement(newInitializer).Yield())); - // Method calls in initializers must be static in C# - Supporting this is #281 - var methodDecl = ValidSyntaxFactory.CreateParameterlessMethod(newMethodName, decl.Type, body); - yield return methodDecl; - - var newVar = - v.WithInitializer(CS.SyntaxFactory.EqualsValueClause( - CS.SyntaxFactory.InvocationExpression(ValidSyntaxFactory.IdentifierName(newMethodName)))); - var newVarDecl = - CS.SyntaxFactory.VariableDeclaration(decl.Type, CS.SyntaxFactory.SingletonSeparatedList(newVar)); - - yield return CS.SyntaxFactory.FieldDeclaration(CS.SyntaxFactory.List(attributes), convertedModifiers, newVarDecl); - } - private IReadOnlyCollection CreateExtraMethodMembers() { - var methodsInfos = AdditionalLocals.GetParameterlessFunctions(); - - // In theory this should use a unique name like in MethodBodyVisitor - // Unfortunately we can't change the name for these since the file containing the constructor of a partial class tries to call the method with exactly this name. - // See GetInitialValueFunctionName - var newMethodNames = methodsInfos.ToDictionary(l => l.Id, l => l.Prefix); - for (int i = 0; i < _typeContext.Initializers.AdditionalInstanceInitializers.Count; i++) { - var (a, b, initializer, _) = _typeContext.Initializers.AdditionalInstanceInitializers[i]; - _typeContext.Initializers.AdditionalInstanceInitializers[i] = new Assignment(a, b, PerScopeState.ReplaceNames(initializer, newMethodNames)); - } - - return methodsInfos - .Select(al => al.AsInstanceMethod(newMethodNames[al.Id])) + // Callers reference these by their final name, so it's the prefix rather than a placeholder + return AdditionalLocals.TakeParameterlessFunctions() + .Select(al => al.AsInstanceMethod(al.Prefix)) .ToArray(); } diff --git a/CodeConverter/CSharp/HoistedFunction.cs b/CodeConverter/CSharp/HoistedFunction.cs index cca1c0c83..6b02f3b7d 100644 --- a/CodeConverter/CSharp/HoistedFunction.cs +++ b/CodeConverter/CSharp/HoistedFunction.cs @@ -8,20 +8,23 @@ internal class HoistedFunction : IHoistedNode private readonly TypeSyntax _returnType; private readonly BlockSyntax _block; private readonly ParameterListSyntax _parameters; + private readonly bool _isStatic; public string Id { get; } public string Prefix { get; } - public HoistedFunction(string localFuncName, TypeSyntax returnType, BlockSyntax block, ParameterListSyntax parameters) + /// Only used when hoisted to a member: it must be an instance method to be called from an instance context such as a constructor + public HoistedFunction(string localFuncName, TypeSyntax returnType, BlockSyntax block, ParameterListSyntax parameters, bool isStatic = true) { Id = $"hs{Guid.NewGuid().ToString("N")}"; Prefix = localFuncName; _returnType = returnType; _block = block; _parameters = parameters; + _isStatic = isStatic; } public IdentifierNameSyntax TempIdentifier => ValidSyntaxFactory.IdentifierName(Id).WithAdditionalAnnotations(PerScopeState.AdditionalLocalAnnotation); public LocalFunctionStatementSyntax AsLocalFunction(string functionName) => SyntaxFactory.LocalFunctionStatement(_returnType, SyntaxFactory.Identifier(functionName)).WithParameterList(_parameters).WithBody(_block); - public MethodDeclarationSyntax AsInstanceMethod(string functionName) => ValidSyntaxFactory.CreateMethod(functionName, _returnType, _parameters, _block); + public MethodDeclarationSyntax AsInstanceMethod(string functionName) => ValidSyntaxFactory.CreateMethod(functionName, _returnType, _parameters, _block, _isStatic); } \ No newline at end of file diff --git a/CodeConverter/CSharp/MethodBodyExecutableStatementVisitor.cs b/CodeConverter/CSharp/MethodBodyExecutableStatementVisitor.cs index 6e9720622..2f29cd63b 100644 --- a/CodeConverter/CSharp/MethodBodyExecutableStatementVisitor.cs +++ b/CodeConverter/CSharp/MethodBodyExecutableStatementVisitor.cs @@ -6,6 +6,7 @@ using static Microsoft.CodeAnalysis.VisualBasic.VisualBasicExtensions; using SyntaxFactory = Microsoft.CodeAnalysis.CSharp.SyntaxFactory; using Microsoft.CodeAnalysis.Text; +using ICSharpCode.CodeConverter.CSharp.ByRefArguments; using ICSharpCode.CodeConverter.Util.FromRoslyn; using ICSharpCode.CodeConverter.VB; using ComparisonKind = ICSharpCode.CodeConverter.CSharp.VisualBasicEqualityComparison.ComparisonKind; @@ -28,6 +29,7 @@ internal class MethodBodyExecutableStatementVisitor : VBasic.VisualBasicSyntaxVi private readonly HashSet _generatedNames = new(); private readonly HashSet _localsToInlineInLoop; private readonly PerScopeState _perScopeState; + private readonly WriteBackPlacement _writeBackPlacement; public bool IsIterator { get; set; } public IdentifierNameSyntax ReturnVariable { get; set; } @@ -64,6 +66,7 @@ private MethodBodyExecutableStatementVisitor(VisualBasicSyntaxNode methodNode, S _extraUsingDirectives = extraUsingDirectives; _handledEventsAnalysis = typeContext.HandledEventsAnalysis; _perScopeState = typeContext.PerScopeState; + _writeBackPlacement = new WriteBackPlacement(semanticModel, _generatedNames, typeContext, commonConversions); var byRefParameterVisitor = new PerScopeStateVisitorDecorator(this, _perScopeState, semanticModel, _generatedNames); CommentConvertingVisitor = new CommentConvertingMethodBodyVisitor(byRefParameterVisitor); _localsToInlineInLoop = localsToInlineInLoop; @@ -288,9 +291,12 @@ _methodNode is VBSyntax.MethodBlockSyntax mb && return SingleStatement(lhs); } - var assignment = SyntaxFactory.AssignmentExpression(kind, lhs, rhs); var postAssignment = GetPostAssignmentStatements(node); - return postAssignment.Insert(0, SyntaxFactory.ExpressionStatement(assignment)); + StatementSyntax AssignTo(ExpressionSyntax value) => SyntaxFactory.ExpressionStatement(SyntaxFactory.AssignmentExpression(kind, lhs, value)); + if (kind == SyntaxKind.SimpleAssignmentExpression && _writeBackPlacement.IsSimpleTargetReadByWriteBack(node)) { + return SyntaxFactory.List(_perScopeState.WithWriteBacksBefore(rhs, "ret", () => GetResultTypeSyntax(node.Right), AssignTo).Concat(postAssignment)); + } + return postAssignment.Insert(0, AssignTo(rhs)); } private async Task> ConvertMidAssignmentAsync(VBSyntax.AssignmentStatementSyntax node, VBSyntax.MidExpressionSyntax mes) @@ -492,7 +498,8 @@ private ExpressionStatementSyntax CreateNewArrayAssignment(VBSyntax.ExpressionSy public override async Task> VisitThrowStatement(VBSyntax.ThrowStatementSyntax node) { - return SingleStatement(SyntaxFactory.ThrowStatement(await node.Expression.AcceptAsync(_expressionVisitor))); + var csExpression = await node.Expression.AcceptAsync(_expressionVisitor); + return WithWriteBacksBeforeJump(node.Expression, csExpression, "ex", SyntaxFactory.ThrowStatement); } public override async Task> VisitReturnStatement(VBSyntax.ReturnStatementSyntax node) @@ -502,7 +509,27 @@ public override async Task> VisitReturnStatement(VBS var csExpression = await node.Expression.AcceptAsync(_expressionVisitor); csExpression = CommonConversions.TypeConversionAnalyzer.AddExplicitConversion(node.Expression, csExpression); - return SingleStatement(SyntaxFactory.ReturnStatement(csExpression)); + return WithWriteBacksBeforeJump(node.Expression, csExpression, "ret", SyntaxFactory.ReturnStatement); + } + + /// + /// Write-backs are normally emitted after the converted statement, which after a jump would be unreachable (or, for yield, delayed until the consumer resumes). + /// + private SyntaxList WithWriteBacksBeforeJump(VBSyntax.ExpressionSyntax vbExpression, ExpressionSyntax csExpression, string resultPrefix, + Func createJump) + { + if (csExpression is null) return SingleStatement(createJump(null)); + return SyntaxFactory.List(_perScopeState.WithWriteBacksBefore(csExpression, resultPrefix, () => GetResultTypeSyntax(vbExpression), createJump)); + } + + /// + /// var is only safe when the expression's own type is the one the jump needs: e.g. Nothing or a lambda has no natural type in C#. + /// + private TypeSyntax GetResultTypeSyntax(VBSyntax.ExpressionSyntax vbExpression) + { + var typeInfo = _semanticModel.GetTypeInfo(vbExpression); + var isNaturalType = typeInfo.Type is { } type && SymbolEqualityComparer.Default.Equals(type, typeInfo.ConvertedType); + return CommonConversions.GetTypeSyntax(typeInfo.ConvertedType, useImplicitType: isNaturalType); } public override async Task> VisitContinueStatement(VBSyntax.ContinueStatementSyntax node) @@ -513,7 +540,8 @@ public override async Task> VisitContinueStatement(V public override async Task> VisitYieldStatement(VBSyntax.YieldStatementSyntax node) { - return SingleStatement(SyntaxFactory.YieldStatement(SyntaxKind.YieldReturnStatement, await node.Expression.AcceptAsync(_expressionVisitor))); + var csExpression = await node.Expression.AcceptAsync(_expressionVisitor); + return WithWriteBacksBeforeJump(node.Expression, csExpression, "ret", e => SyntaxFactory.YieldStatement(SyntaxKind.YieldReturnStatement, e)); } public override async Task> VisitExitStatement(VBSyntax.ExitStatementSyntax node) diff --git a/CodeConverter/CSharp/NameExpressionNodeVisitor.cs b/CodeConverter/CSharp/NameExpressionNodeVisitor.cs index eb6de7f58..d9f3ad3e8 100644 --- a/CodeConverter/CSharp/NameExpressionNodeVisitor.cs +++ b/CodeConverter/CSharp/NameExpressionNodeVisitor.cs @@ -1,5 +1,6 @@ using System.Data; using System.Globalization; +using ICSharpCode.CodeConverter.CSharp.ByRefArguments; using ICSharpCode.CodeConverter.CSharp.Queries; using ICSharpCode.CodeConverter.CSharp.Replacements; using ICSharpCode.CodeConverter.Util.FromRoslyn; @@ -23,6 +24,7 @@ internal class NameExpressionNodeVisitor private readonly Dictionary _conditionalAccessReceivers; private readonly ArgumentConverter _argumentConverter; private readonly RangeVariableReplacements _rangeVariableReplacements; + private readonly WriteBackPlacement _writeBackPlacement; public CommonConversions CommonConversions { get; } public CommentConvertingVisitorWrapper TriviaConvertingExpressionVisitor { get; } @@ -45,6 +47,7 @@ public NameExpressionNodeVisitor(SemanticModel semanticModel, HashSet ge _argumentConverter = argumentConverter; CommonConversions = commonConversions; TriviaConvertingExpressionVisitor = triviaConvertingExpressionVisitor; + _writeBackPlacement = new WriteBackPlacement(semanticModel, generatedNames, typeContext, commonConversions); } public async Task ConvertMemberAccessExpressionAsync(VBasic.Syntax.MemberAccessExpressionSyntax node) @@ -213,7 +216,7 @@ public async Task ConvertInvocationExpressionAsync( { var invocationSymbol = _semanticModel.GetSymbolInfo(node).ExtractBestMatch(); var methodInvocationSymbol = invocationSymbol as IMethodSymbol; - var withinLocalFunction = methodInvocationSymbol != null && RequiresLocalFunction(node, methodInvocationSymbol); + var withinLocalFunction = methodInvocationSymbol != null && _writeBackPlacement.RequiresLocalFunction(node, methodInvocationSymbol); if (withinLocalFunction) { _typeContext.PerScopeState.PushScope(); } @@ -229,7 +232,7 @@ public async Task ConvertInvocationExpressionAsync( var convertedInvocation = await ConvertOrReplaceInvocationAsync(node, invocationSymbol); if (withinLocalFunction) { - return await HoistAndCallLocalFunctionAsync(node, methodInvocationSymbol, (ExpressionSyntax)convertedInvocation); + return await _writeBackPlacement.HoistAndCallLocalFunctionAsync(node, methodInvocationSymbol, (ExpressionSyntax)convertedInvocation); } return convertedInvocation; } finally { @@ -375,7 +378,7 @@ private async Task ConvertInvocationAsync(VBSyntax.InvocationE var thisArgExpression = await maes.Expression.AcceptAsync(TriviaConvertingExpressionVisitor); if (requiresHoist) { - thisArgExpression = _argumentConverter.HoistByRefDeclaration(maes.Expression, thisArgExpression, refConversion, thisParam.Name, refKind); + thisArgExpression = _argumentConverter.ByRefArgumentHoister.HoistByRefDeclaration(maes.Expression, thisArgExpression, refConversion, thisParam.Name, refKind); } if (requiresStaticInvocation) { @@ -483,158 +486,6 @@ private async Task TryConvertParameterizedPropertyAs } - /// - /// The VB compiler actually just hoists the conditions within the same method, but that leads to the original logic looking very different. - /// This should be equivalent but keep closer to the look of the original source code. - /// See https://github.com/icsharpcode/CodeConverter/issues/310 and https://github.com/icsharpcode/CodeConverter/issues/324 - /// - private async Task HoistAndCallLocalFunctionAsync(VBasic.VisualBasicSyntaxNode invocation, IMethodSymbol invocationSymbol, ExpressionSyntax csExpression) - { - const string retVariableName = "ret"; - var localFuncName = $"local{invocationSymbol.Name}"; - - var callAndStoreResult = CommonConversions.CreateLocalVariableDeclarationAndAssignment(retVariableName, csExpression); - - var statements = await _typeContext.PerScopeState.CreateLocalsAsync(invocation, new[] { callAndStoreResult }, _generatedNames, _semanticModel); - - var block = SyntaxFactory.Block( - statements.Concat(SyntaxFactory.ReturnStatement(ValidSyntaxFactory.IdentifierName(retVariableName)).Yield()) - ); - var returnType = CommonConversions.GetTypeSyntax(invocationSymbol.ReturnType); - - // Parent ByRef parameters cannot be captured, including references in receivers and nested argument expressions. - var enclosingSymbol = _semanticModel.GetEnclosingSymbol(invocation.SpanStart); - var refParametersOfParent = (_semanticModel.GetOperation(invocation)?.DescendantsAndSelf() - .OfType().Select(p => p.Parameter) ?? Enumerable.Empty()) - .Where(p => p.RefKind != RefKind.None && SymbolEqualityComparer.Default.Equals(p.ContainingSymbol, enclosingSymbol)) - .Distinct(SymbolEqualityComparer.Default).ToList(); - var (args, @params) = CreateArgumentsAndParametersLists(refParametersOfParent); - - var localFunc = _typeContext.PerScopeState.Hoist(new HoistedFunction(localFuncName, returnType, block, SyntaxFactory.ParameterList(@params))); - return SyntaxFactory.InvocationExpression(localFunc.TempIdentifier, SyntaxFactory.ArgumentList(args)); - - (SeparatedSyntaxList, SeparatedSyntaxList) CreateArgumentsAndParametersLists(List parameterSymbols) - { - var arguments = new List(); - var parameters = new List(); - foreach (var p in parameterSymbols) { - var arg = (ArgumentSyntax)CommonConversions.CsSyntaxGenerator.Argument(p.RefKind, SyntaxFactory.IdentifierName(p.Name)); - arguments.Add(arg); - var par = (ParameterSyntax)CommonConversions.CsSyntaxGenerator.ParameterDeclaration(p); - parameters.Add(par.WithDefault(null)); - } - return (SyntaxFactory.SeparatedList(arguments), SyntaxFactory.SeparatedList(parameters)); - } - } - - private bool RequiresLocalFunction(VBSyntax.InvocationExpressionSyntax invocation, IMethodSymbol invocationSymbol) - { - if (IsLoopCondition(invocation)) { - // A loop condition needs fresh argument temporaries and copy-back on every evaluation. - return invocationSymbol.ReducedFrom?.Parameters.FirstOrDefault() is { RefKind: not RefKind.None } && - invocation.Expression is VBSyntax.MemberAccessExpressionSyntax member && - _semanticModel.GetRefConversionForExpression(member.Expression) != RefConversion.Inline || - invocation.ArgumentList?.Arguments.Any(a => - CommonConversions.GetRefConversionType(a, invocation.ArgumentList, invocationSymbol.Parameters, out _, out _) != RefConversion.Inline) == true || - _semanticModel.GetOperation(invocation) is IInvocationOperation operation && operation.Arguments.Any(a => - a.ArgumentKind == ArgumentKind.DefaultValue && a.Parameter.RefKind != RefKind.None); - } - - if (invocation.ArgumentList == null) return false; - var definitelyExecutedAfterPrevious = DefinitelyExecutedAfterPreviousStatement(invocation); - var nextStatementDefinitelyExecuted = NextStatementDefinitelyExecutedAfter(invocation); - if (definitelyExecutedAfterPrevious && nextStatementDefinitelyExecuted) return false; - var possibleInline = definitelyExecutedAfterPrevious ? RefConversion.PreAssigment : RefConversion.Inline; - return invocation.ArgumentList.Arguments.Any(a => RequiresLocalFunction(possibleInline, invocation, invocationSymbol, a)); - - bool RequiresLocalFunction(RefConversion possibleInline, VBSyntax.InvocationExpressionSyntax invocation, IMethodSymbol invocationSymbol, VBSyntax.ArgumentSyntax a) - { - var refConversion = CommonConversions.GetRefConversionType(a, invocation.ArgumentList, invocationSymbol.Parameters, out string _, out _); - if (RefConversion.Inline == refConversion || possibleInline == refConversion) return false; - if (!(a is VBSyntax.SimpleArgumentSyntax sas)) return false; - var argExpression = sas.Expression.SkipIntoParens(); - if (argExpression is VBSyntax.InstanceExpressionSyntax) return false; - return !_semanticModel.GetConstantValue(argExpression).HasValue; - } - } - - private static bool IsLoopCondition(SyntaxNode node) - { - var containingStatement = node.Ancestors().FirstOrDefault(n => n is VBSyntax.StatementSyntax or VBSyntax.LambdaExpressionSyntax); - return containingStatement is VBSyntax.WhileStatementSyntax or VBSyntax.DoStatementSyntax or VBSyntax.LoopStatementSyntax; - } - - /// - /// Conservative version of _semanticModel.AnalyzeControlFlow(invocation).ExitPoints to account for exceptions - /// - private bool DefinitelyExecutedAfterPreviousStatement(VBSyntax.InvocationExpressionSyntax invocation) - { - SyntaxNode parent = invocation; - while (true) { - parent = parent.Parent; - switch (parent) { - case VBSyntax.ParenthesizedExpressionSyntax _: - continue; - case VBSyntax.BinaryExpressionSyntax binaryExpression: - if (binaryExpression.Left == invocation) continue; - else return false; - case VBSyntax.ArgumentSyntax argumentSyntax: - // Being the leftmost invocation of an unqualified method call ensures no other code is executed. Could add other cases here, such as a method call on a local variable name, or "this.". A method call on a property is not acceptable. - if (argumentSyntax.Parent.Parent is VBSyntax.InvocationExpressionSyntax parentInvocation && parentInvocation.ArgumentList.Arguments.First() == argumentSyntax && FirstArgDefinitelyEvaluated(parentInvocation)) continue; - else return false; - case VBSyntax.ElseIfStatementSyntax _: - case VBSyntax.ExpressionSyntax _: - return false; - case VBSyntax.StatementSyntax _: - return true; - } - } - } - - private bool FirstArgDefinitelyEvaluated(VBSyntax.InvocationExpressionSyntax parentInvocation) => - parentInvocation.Expression.SkipIntoParens() switch { - VBSyntax.IdentifierNameSyntax _ => true, - VBSyntax.MemberAccessExpressionSyntax maes => maes.Expression is { } exp && !MayThrow(exp), - _ => true - }; - - /// - /// Safe overapproximation of whether an expression may throw. - /// - private bool MayThrow(VBSyntax.ExpressionSyntax expression) - { - expression = expression.SkipIntoParens(); - if (expression is VBSyntax.InstanceExpressionSyntax) return false; - var symbol = _semanticModel.GetSymbolInfo(expression).Symbol; - return !symbol.IsKind(SymbolKind.Local) && !symbol.IsKind(SymbolKind.Field); - } - - /// - /// Conservative version of _semanticModel.AnalyzeControlFlow(invocation).ExitPoints to account for exceptions - /// - private static bool NextStatementDefinitelyExecutedAfter(VBSyntax.InvocationExpressionSyntax invocation) - { - SyntaxNode parent = invocation; - while (true) { - parent = parent.Parent; - switch (parent) { - case VBSyntax.ParenthesizedExpressionSyntax _: - continue; - case VBSyntax.BinaryExpressionSyntax binaryExpression: - if (binaryExpression.Right == invocation) continue; - else return false; - case VBSyntax.IfStatementSyntax _: - case VBSyntax.ElseIfStatementSyntax _: - case VBSyntax.SingleLineIfStatementSyntax _: - return false; - case VBSyntax.ExpressionSyntax _: - case VBSyntax.StatementSyntax _: - return true; - } - } - } - - /// /// The pre-expansion phase should handle this for compiling nodes. /// This is mainly targeted at dealing with missing semantic info. @@ -728,12 +579,12 @@ private async Task AddEmptyArgumentListIfImplicitAsync(SyntaxN { if (_semanticModel.SyntaxTree != node.SyntaxTree) return id; var operation = _semanticModel.GetOperation(node); - if (IsLoopCondition(node) && operation is IInvocationOperation implicitInvocation && + if (WriteBackPlacement.IsLoopCondition(node) && operation is IInvocationOperation implicitInvocation && implicitInvocation.TargetMethod.Parameters.Any(p => p.RefKind != RefKind.None)) { _typeContext.PerScopeState.PushScope(); try { var call = SyntaxFactory.InvocationExpression(id, _argumentConverter.CreateArgList(implicitInvocation.TargetMethod)); - return await HoistAndCallLocalFunctionAsync((VBasic.VisualBasicSyntaxNode)node, implicitInvocation.TargetMethod, call); + return await _writeBackPlacement.HoistAndCallLocalFunctionAsync((VBasic.VisualBasicSyntaxNode)node, implicitInvocation.TargetMethod, call); } finally { _typeContext.PerScopeState.PopExpressionScope(); } diff --git a/CodeConverter/CSharp/PerScopeState.cs b/CodeConverter/CSharp/PerScopeState.cs index a49fff977..d0273911e 100644 --- a/CodeConverter/CSharp/PerScopeState.cs +++ b/CodeConverter/CSharp/PerScopeState.cs @@ -68,6 +68,27 @@ public T HoistToTopLevel(T additionalField) where T : IHoistedNode return additionalField; } + public bool HasHoistedNodes => _hoistedNodesPerScope.Peek().HoistedNodes.Any(); + + /// + /// For an expression that has no statement of its own to hoist into, e.g. a field initializer. + /// Declares the temporaries hoisted for it and writes back ByRef arguments before returning, as a statement would. + /// Leaves the current scope as it was, since each variable sharing an initializer evaluates it separately. + /// + public async Task CreateReturnBlockAsync(VBasic.VisualBasicSyntaxNode vbNode, ExpressionSyntax expression, TypeSyntax resultType, SemanticModel semanticModel) + { + var currentScope = _hoistedNodesPerScope.Peek(); + _hoistedNodesPerScope.Push(currentScope with { HoistedNodes = currentScope.HoistedNodes.ToList() }); + try { + var generatedNames = new HashSet(); + var statements = WithWriteBacksBefore(expression, "ret", () => resultType, SyntaxFactory.ReturnStatement); + var withLocals = await CreateLocalsAsync(vbNode, statements, generatedNames, semanticModel); + return SyntaxFactory.Block(CreateStatements(vbNode, withLocals, generatedNames, semanticModel)); + } finally { + PopScope(); + } + } + public IReadOnlyCollection GetDeclarations() { return _hoistedNodesPerScope.Peek().OfType().ToArray(); @@ -78,6 +99,28 @@ public IReadOnlyCollection GetDefaultInit return _hoistedNodesPerScope.Peek().OfType().ToArray(); } + /// + /// VB copies a ByRef argument back to its property straight after the call, so before a statement that uses the result jumps away. + /// When there are write-backs, evaluate the expression into a local, write back, then use that local. Without any, the single statement is kept. + /// + public IReadOnlyCollection WithWriteBacksBefore(ExpressionSyntax expression, string resultPrefix, Func getResultType, + Func createStatementUsingResult) + { + var writeBacks = TakeWriteBacks(); + if (!writeBacks.Any()) return new[] { createStatementUsingResult(expression) }; + + var result = Hoist(new AdditionalDeclaration(resultPrefix, expression, getResultType())); + return writeBacks.Append(createStatementUsingResult(result.IdentifierName)).ToArray(); + } + + private IReadOnlyCollection TakeWriteBacks() + { + var hoistedNodes = _hoistedNodesPerScope.Peek().HoistedNodes; + var writeBacks = hoistedNodes.OfType().ToArray(); + hoistedNodes.RemoveAll(n => n is AdditionalAssignment); + return writeBacks.Select(AdditionalAssignment.CreateAssignment).ToArray(); + } + private StatementSyntax[] GetPostStatements() { var scopeState = _hoistedNodesPerScope.Peek(); @@ -91,6 +134,16 @@ public IReadOnlyCollection GetParameterlessFunctions() return _hoistedNodesPerScope.Peek().OfType().ToArray(); } + /// + /// For a scope whose functions are emitted as they're found, e.g. one per variable of a field declaration, so each is emitted once. + /// + public IReadOnlyCollection TakeParameterlessFunctions() + { + var functions = GetParameterlessFunctions(); + _hoistedNodesPerScope.Peek().HoistedNodes.RemoveAll(n => n is HoistedFunction); + return functions; + } + public IReadOnlyCollection GetFields() { return _hoistedNodesPerScope.Peek().OfType().ToArray(); diff --git a/CodeConverter/CSharp/README.md b/CodeConverter/CSharp/README.md new file mode 100644 index 000000000..5873bc336 --- /dev/null +++ b/CodeConverter/CSharp/README.md @@ -0,0 +1,4 @@ +# VB → C# conversion + +* ByRef arguments that need a temporary, and where their write-backs go: [ByRefArguments/README.md](ByRefArguments/README.md) +* Query expressions: [Queries/README.md](Queries/README.md) diff --git a/CodeConverter/CSharp/ValidSyntaxFactory.cs b/CodeConverter/CSharp/ValidSyntaxFactory.cs index 38bd3bf26..563b15de7 100644 --- a/CodeConverter/CSharp/ValidSyntaxFactory.cs +++ b/CodeConverter/CSharp/ValidSyntaxFactory.cs @@ -79,9 +79,9 @@ public static MethodDeclarationSyntax CreateParameterlessMethod(string newMethod return CreateMethod(newMethodName, type, parameterList, body); } - public static MethodDeclarationSyntax CreateMethod(string newMethodName, TypeSyntax type, ParameterListSyntax parameterList, BlockSyntax body) + public static MethodDeclarationSyntax CreateMethod(string newMethodName, TypeSyntax type, ParameterListSyntax parameterList, BlockSyntax body, bool isStatic = true) { - var modifiers = SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.StaticKeyword)); + var modifiers = isStatic ? SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.StaticKeyword)) : SyntaxFactory.TokenList(); var typeConstraints = SyntaxFactory.List(); var methodAttrs = SyntaxFactory.List(); diff --git a/Tests/CSharp/ExpressionTests/ByRefTests.cs b/Tests/CSharp/ExpressionTests/ByRefTests.cs index 74b47b178..d1437fa1c 100644 --- a/Tests/CSharp/ExpressionTests/ByRefTests.cs +++ b/Tests/CSharp/ExpressionTests/ByRefTests.cs @@ -995,4 +995,566 @@ public void Bar() }"); } + [Fact] + public async Task WritesBackBeforeJumpingIssue896Async() + { + await TestConversionVisualBasicToCSharpAsync(@"Imports System.Collections.Generic +Public Class C + Public Property P As Integer + + Function Inc(ByRef v As Integer) As Integer + v += 1 + Return v + End Function + + Function CreateException(ByRef v As Integer) As Exception + Return New Exception() + End Function + + Function ReturnsWrittenBack() As Long + Return Inc(P) + End Function + + Function ReturnsWithoutWriteBack() As Integer + Return Inc(New Integer) + End Function + + Iterator Function YieldsWrittenBack() As IEnumerable(Of Integer) + Yield Inc(P) + End Function + + Sub ThrowsWrittenBack() + Throw CreateException(P) + End Sub +End Class", @"using System; +using System.Collections.Generic; + +public partial class C +{ + public int P { get; set; } + + public int Inc(ref int v) + { + v += 1; + return v; + } + + public Exception CreateException(ref int v) + { + return new Exception(); + } + + public long ReturnsWrittenBack() + { + int argv = P; + long ret = Inc(ref argv); + P = argv; + return ret; + } + + public int ReturnsWithoutWriteBack() + { + int argv = new int(); + return Inc(ref argv); + } + + public IEnumerable YieldsWrittenBack() + { + int argv = P; + var ret = Inc(ref argv); + P = argv; + yield return ret; + } + + public void ThrowsWrittenBack() + { + int argv = P; + var ex = CreateException(ref argv); + P = argv; + throw ex; + } +}"); + } + + [Fact] + public async Task WritesBackBeforeBlockBodyAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Public Class C + Public Property P As Integer + + Function Inc(ByRef v As Integer) As Integer + v += 1 + Return v + End Function + + Function Arr(ByRef v As Integer) As Integer() + Return New Integer() {v} + End Function + + Function D(ByRef v As Integer) As IDisposable + Return Nothing + End Function + + Function IsOne(ByRef v As Integer) As Boolean + Return v = 1 + End Function + + Sub BlockHeaders() + Select Case Inc(P) + Case 1 + Console.WriteLine(1) + End Select + For i = 0 To Inc(P) + Console.WriteLine(i) + Next + For Each item In Arr(P) + Console.WriteLine(item) + Next + Using dd = D(P) + Console.WriteLine(3) + End Using + SyncLock Arr(P) + Console.WriteLine(4) + End SyncLock + With Arr(P) + Console.WriteLine(.Length) + End With + Try + Catch ex As Exception When IsOne(P) + End Try + End Sub + + Sub BlockHeaderWithoutWriteBack() + Select Case Inc(New Integer) + Case 1 + Console.WriteLine(1) + End Select + End Sub +End Class", @"using System; + +public partial class C +{ + public int P { get; set; } + + public int Inc(ref int v) + { + v += 1; + return v; + } + + public int[] Arr(ref int v) + { + return new int[] { v }; + } + + public IDisposable D(ref int v) + { + return null; + } + + public bool IsOne(ref int v) + { + return v == 1; + } + + public void BlockHeaders() + { + int localInc() { int argv = P; var ret = Inc(ref argv); P = argv; return ret; } + + switch (localInc()) + { + case 1: + Console.WriteLine(1); + break; + } + int localInc1() { int argv1 = P; var ret = Inc(ref argv1); P = argv1; return ret; } + + for (int i = 0, loopTo = localInc1(); i <= loopTo; i++) + Console.WriteLine(i); + int[] localArr() { int argv2 = P; var ret = Arr(ref argv2); P = argv2; return ret; } + + foreach (var item in localArr()) + Console.WriteLine(item); + IDisposable localD() { int argv3 = P; var ret = D(ref argv3); P = argv3; return ret; } + + using (var dd = localD()) + { + Console.WriteLine(3); + } + int[] localArr1() { int argv4 = P; var ret = Arr(ref argv4); P = argv4; return ret; } + + lock (localArr1()) + Console.WriteLine(4); + int[] localArr2() { int argv5 = P; var ret = Arr(ref argv5); P = argv5; return ret; } + + { + var withBlock = localArr2(); + Console.WriteLine(withBlock.Length); + } + bool localIsOne() { int argv6 = P; var ret = IsOne(ref argv6); P = argv6; return ret; } + + try + { + } + catch (Exception ex) when (localIsOne()) + { + } + } + + public void BlockHeaderWithoutWriteBack() + { + int argv = new int(); + switch (Inc(ref argv)) + { + case 1: + Console.WriteLine(1); + break; + } + } +}"); + } + + [Fact] + public async Task OmittedOptionalRefInInstanceFieldInitializerIssue1081Async() + { + await TestConversionVisualBasicToCSharpAsync(@"Public Class FieldInitializationTest + Private First As New Inner() + Private Second As New Outer(First) +End Class + +Public Class Inner +End Class + +Public Class Outer + Sub New(inner As Inner, Optional ByRef x As String = """") + End Sub +End Class", @"using System.Runtime.InteropServices; + +public partial class FieldInitializationTest +{ + private Inner First = new Inner(); + + public FieldInitializationTest() + { + Second = initSecond(); + } + Outer initSecond() + { + string argx = """"; + return new Outer(First, x: ref argx); + } + + private Outer Second; +} + +public partial class Inner +{ +} + +public partial class Outer +{ + public Outer(Inner inner, [Optional, DefaultParameterValue("""")] ref string x) + { + } +}"); + } + + [Fact] + public async Task FieldInitializersWriteBackAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Public Class C + Public Property P As Integer + Private Shared Property SP As Integer + Private _a As Integer = Inc(P) + Private Shared _c As Integer = Inc(SP) + + Shared Function Inc(ByRef v As Integer) As Integer + v += 1 + Return v + End Function +End Class", @" +public partial class C +{ + public int P { get; set; } + private static int SP { get; set; } + + public C() + { + _a = Inc__a(); + } + int Inc__a() + { + int argv = P; + int ret = Inc(ref argv); + P = argv; + return ret; + } + + private int _a; + static int Inc__c() + { + int argv = SP; + int ret = Inc(ref argv); + SP = argv; + return ret; + } + + private static int _c = Inc__c(); + + public static int Inc(ref int v) + { + v += 1; + return v; + } +}"); + } + + [Fact] + public async Task FieldInitializerMethodNamesAvoidExistingMembersAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Public Class C + Public Property P As Integer + Private w As Integer = Inc(P) + 1 + Private v As Integer = Inc(P) + Private Inc_v As Integer + + Function initW() As Integer + Return 0 + End Function + + Shared Function Inc(ByRef x As Integer) As Integer + x += 1 + Return x + End Function +End Class", @" +public partial class C +{ + public int P { get; set; } + + public C() + { + w = initW1(); + v = Inc_v1(); + } + int initW1() + { + int localInc() { int argx = P; var ret = Inc(ref argx); P = argx; return ret; } + + return localInc() + 1; + } + + private int w; + int Inc_v1() + { + int argx = P; + int ret = Inc(ref argx); + P = argx; + return ret; + } + + private int v; + private int Inc_v; + + public int initW() + { + return 0; + } + + public static int Inc(ref int x) + { + x += 1; + return x; + } +}"); + } + + [Fact] + public async Task WritesBackBeforeAssignmentCompletesWhenItChangesTheWriteBackTargetAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Public Class C + Public Property P As String + Public Property Q As String + + Function F(ByRef v As String) As String + Return v + End Function + + Function G(ByRef v As String) As C + Return New C + End Function + + Sub Assignments(h As C) + P = F(P) + h.Q = F(h.Q) + h = G(h.P) + Q = F(P) + End Sub +End Class", @" +public partial class C +{ + public string P { get; set; } + public string Q { get; set; } + + public string F(ref string v) + { + return v; + } + + public C G(ref string v) + { + return new C(); + } + + public void Assignments(C h) + { + string argv = P; + var ret = F(ref argv); + P = argv; + P = ret; + string localF() { string argv = h.Q; var ret = F(ref argv); h.Q = argv; return ret; } + + h.Q = localF(); + string argv1 = h.P; + var ret1 = G(ref argv1); + h.P = argv1; + h = ret1; + string argv2 = P; + Q = F(ref argv2); + P = argv2; + } +}"); + } + + [Fact] + public async Task StructureKeepsStatementPlacementWhereALocalFunctionWouldNeedThisAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Public Structure S + Public Property P As Integer + + Shared Function Inc(ByRef v As Integer) As Integer + v += 1 + Return v + End Function + + Sub M() + Select Case Inc(P) + Case 1 + Console.WriteLine(1) + End Select + Dim a = Inc(P), b = Inc(P) + P += Inc(P) + End Sub +End Structure", @"using System; + +public partial struct S +{ + public int P { get; set; } + + public static int Inc(ref int v) + { + v += 1; + return v; + } + + public void M() + { + int argv = P; + switch (Inc(ref argv)) + { + case 1: + Console.WriteLine(1); + break; + } + P = argv; + int argv1 = P; + int argv2 = P; + int a = Inc(ref argv1); + int b = Inc(ref argv2); + P = argv1; + P = argv2; + int argv3 = P; + P += Inc(ref argv3); + P = argv3; + } +}", incompatibleWithAutomatedCommentTesting: true); // The write-back after the block moves line comments out of order + } + + [Fact] + public async Task StructureKeepsStatementPlacementForOperandsThatWouldNeedThisAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Public Structure S + Public Property P As Integer + + Shared Function Inc(ByRef v As Integer) As Integer + v += 1 + Return v + End Function + + Sub M() + Me.P = Inc(Me.P) + 1 + Dim x = 1 + Inc(P) + P = Inc(Inc(P)) + End Sub +End Structure", @" +public partial struct S +{ + public int P { get; set; } + + public static int Inc(ref int v) + { + v += 1; + return v; + } + + public void M() + { + int argv = P; + var ret = Inc(ref argv) + 1; + P = argv; + P = ret; + int argv1 = P; + int x = 1 + Inc(ref argv1); + P = argv1; + int argv2 = P; + int argv3 = Inc(ref argv2); + var ret1 = Inc(ref argv3); + P = argv2; + P = ret1; + } +}"); + } + + [Fact] + public async Task LateBoundAssignmentTargetTakesTheLocalFunctionAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Option Strict Off + +Public Class C + Public Property P As Integer + + Shared Function Inc(ByRef v As Integer) As Integer + v += 1 + Return v + End Function + + Sub M(o As Object) + o.X = Inc(P) + End Sub +End Class", @" +public partial class C +{ + public int P { get; set; } + + public static int Inc(ref int v) + { + v += 1; + return v; + } + + public void M(object o) + { + int localInc() { int argv = P; var ret = Inc(ref argv); P = argv; return ret; } ((dynamic)o).X = localInc(); + } +}", incompatibleWithAutomatedCommentTesting: true); // The late-bound assignment is emitted on the local function's line + } } \ No newline at end of file diff --git a/Tests/CSharp/ExpressionTests/ExpressionTests.cs b/Tests/CSharp/ExpressionTests/ExpressionTests.cs index ef68b4387..d2bc5c561 100644 --- a/Tests/CSharp/ExpressionTests/ExpressionTests.cs +++ b/Tests/CSharp/ExpressionTests/ExpressionTests.cs @@ -1379,8 +1379,8 @@ public partial class SomeClass public string SomeProperty; static SomeClass initInstance() { - var init = new SomeClass(); - return (init.SomeProperty = init.SomeProperty + nameof(init.SomeProperty), init).init; // Second line gets moved + SomeClass @init = new SomeClass(); + return (@init.SomeProperty = @init.SomeProperty + nameof(@init.SomeProperty), @init).@init; // Second line gets moved } // Third line gets moved public static SomeClass Instance = initInstance(); // First line gets moved diff --git a/Tests/CSharp/MemberTests/ConstructorTests.cs b/Tests/CSharp/MemberTests/ConstructorTests.cs index 3de4d01e9..7bb6789c3 100644 --- a/Tests/CSharp/MemberTests/ConstructorTests.cs +++ b/Tests/CSharp/MemberTests/ConstructorTests.cs @@ -122,7 +122,7 @@ public void S([Optional, DefaultParameterValue(-1)] ref int x) int i = 0; bool localF1(ref int x) { object argo = i; var ret = F1(x, ref argo); i = Conversions.ToInteger(argo); return ret; } bool localF2(ref int x) { object argo1 = i; var ret = F2(ref x, ref argo1); i = Conversions.ToInteger(argo1); return ret; } - bool localF3(ref int x) { object argx = x; object argo2 = i; var ret = F3(ref argx, ref argo2); x = Conversions.ToInteger(argx); i = Conversions.ToInteger(argo2); return ret; } + bool localF3(ref int x) { object argx = x; object argo2 = i; var ret = F3(ref argx, ref argo2); i = Conversions.ToInteger(argo2); x = Conversions.ToInteger(argx); return ret; } if (localF1(ref x)) { diff --git a/Tests/TestData/MultiFileCharacterization/VBToCSResults/ConvertVbLibraryOnly/VbLibrary/PartialClassPart.cs b/Tests/TestData/MultiFileCharacterization/VBToCSResults/ConvertVbLibraryOnly/VbLibrary/PartialClassPart.cs index f6a13e3a3..424a6ff69 100644 --- a/Tests/TestData/MultiFileCharacterization/VBToCSResults/ConvertVbLibraryOnly/VbLibrary/PartialClassPart.cs +++ b/Tests/TestData/MultiFileCharacterization/VBToCSResults/ConvertVbLibraryOnly/VbLibrary/PartialClassPart.cs @@ -6,7 +6,7 @@ namespace VbLibrary /// internal partial class AClass { - static int[] initialAnArrayWithNonStaticInitializerReferencingOtherPart() => new int[anInt + 1]; + int[] initialAnArrayWithNonStaticInitializerReferencingOtherPart() => new int[anInt + 1]; private int[] anArrayWithNonStaticInitializerReferencingOtherPart; } diff --git a/Tests/TestData/MultiFileCharacterization/VBToCSResults/ConvertWholeSolution/Prefix.VbLibrary/PartialClassPart.cs b/Tests/TestData/MultiFileCharacterization/VBToCSResults/ConvertWholeSolution/Prefix.VbLibrary/PartialClassPart.cs index 3f9874dde..d3e12b88a 100644 --- a/Tests/TestData/MultiFileCharacterization/VBToCSResults/ConvertWholeSolution/Prefix.VbLibrary/PartialClassPart.cs +++ b/Tests/TestData/MultiFileCharacterization/VBToCSResults/ConvertWholeSolution/Prefix.VbLibrary/PartialClassPart.cs @@ -6,7 +6,7 @@ namespace Prefix.VbLibrary /// internal partial class AClass { - static int[] initialAnArrayWithNonStaticInitializerReferencingOtherPart() => new int[anInt + 1]; + int[] initialAnArrayWithNonStaticInitializerReferencingOtherPart() => new int[anInt + 1]; private int[] anArrayWithNonStaticInitializerReferencingOtherPart; } diff --git a/Tests/TestData/MultiFileCharacterization/VBToCSResults/ConvertWholeSolution/VbLibrary/PartialClassPart.cs b/Tests/TestData/MultiFileCharacterization/VBToCSResults/ConvertWholeSolution/VbLibrary/PartialClassPart.cs index f6a13e3a3..424a6ff69 100644 --- a/Tests/TestData/MultiFileCharacterization/VBToCSResults/ConvertWholeSolution/VbLibrary/PartialClassPart.cs +++ b/Tests/TestData/MultiFileCharacterization/VBToCSResults/ConvertWholeSolution/VbLibrary/PartialClassPart.cs @@ -6,7 +6,7 @@ namespace VbLibrary /// internal partial class AClass { - static int[] initialAnArrayWithNonStaticInitializerReferencingOtherPart() => new int[anInt + 1]; + int[] initialAnArrayWithNonStaticInitializerReferencingOtherPart() => new int[anInt + 1]; private int[] anArrayWithNonStaticInitializerReferencingOtherPart; } diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb new file mode 100644 index 000000000..f4a5112f5 --- /dev/null +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb @@ -0,0 +1,631 @@ +Imports System +Imports System.Collections.Generic +Imports System.Runtime.CompilerServices +Imports System.Runtime.InteropServices +Imports Xunit + +Public Class ByRefWriteBackPlacementTests + + Public Sub ReturnWritesBackBeforeReturningIssue896() + Dim testClass As New OutParamTestClass + Assert.Equal(2, testClass.Number) + Dim result = CallSubWithOutParam(testClass) + Assert.True(result) + Assert.Equal(1, testClass.Number) + End Sub + + Private Shared Function CallSubWithOutParam(testClass As OutParamTestClass) As Boolean + Return SubWithOutParam(testClass.Number) + End Function + + Private Shared Function SubWithOutParam( ByRef out_a As Integer) As Boolean + out_a = 1 + Return True + End Function + + Private Class OutParamTestClass + Friend Property Number As Integer = 2 + End Class + + + Public Sub ReturnWithConversionWritesBackOnce() + Dim probe As New Probe + Assert.Equal(1L, ReturnAsLong(probe)) + Assert.Equal("get,set", probe.LogText) + End Sub + + Private Shared Function ReturnAsLong(probe As Probe) As Long + Return Increment(probe.Value) + End Function + + + Public Sub ReturnFromPropertyGetterWritesBack() + Dim probe As New Probe + Assert.Equal(1, probe.IncrementedValue) + Assert.Equal(1, probe.Stored) + End Sub + + + Public Sub ReturnInMultiLineLambdaWritesBack() + Dim probe As New Probe + Dim f As Func(Of Integer) = Function() + Return Increment(probe.Value) + End Function + Assert.Equal(1, f()) + Assert.Equal(1, probe.Stored) + End Sub + + + Public Sub ThrowWritesBackBeforeThrowing() + Dim probe As New Probe + Dim ex = Assert.Throws(Of InvalidOperationException)(Sub() ThrowCreated(probe)) + Assert.Equal("1", ex.Message) + Assert.Equal(1, probe.Stored) + Assert.Equal("get,set", probe.LogText) + End Sub + + Private Shared Sub ThrowCreated(probe As Probe) + Throw CreateException(probe.Value) + End Sub + + Private Shared Function CreateException(ByRef value As Integer) As Exception + value += 1 + Return New InvalidOperationException(value.ToString()) + End Function + + + Public Sub YieldWritesBackBeforeTheConsumerResumes() + Dim probe As New Probe + For Each value In YieldIncremented(probe) + Assert.Equal(value, probe.Stored) + Next + Assert.Equal(2, probe.Stored) + End Sub + + Private Shared Iterator Function YieldIncremented(probe As Probe) As IEnumerable(Of Integer) + Yield Increment(probe.Value) + Yield Increment(probe.Value) + End Function + + + Public Sub ReturnWritesBackWhenResultNameIsTaken() + Dim probe As New Probe + Assert.Equal(42, ReturnWithLocalNamedRet(probe)) + Assert.Equal(42, probe.Stored) + End Sub + + Private Shared Function ReturnWithLocalNamedRet(probe As Probe) As Integer + Dim ret = 41 + probe.Stored = ret + Return Increment(probe.Value) + End Function + + + Public Sub ReturnToWiderTypeWritesBack() + Dim probe As New Probe + Assert.Equal(CObj(1), ReturnAsObject(probe)) + Assert.Equal(1, probe.Stored) + End Sub + + Private Shared Function ReturnAsObject(probe As Probe) As Object + Return Increment(probe.Value) + End Function + + + Public Sub SelectCaseBodySeesWrittenBackValue() + Dim probe As New Probe + Select Case Increment(probe.Value) + Case 1 + Assert.Equal(1, probe.Stored) + Case Else + Assert.Fail("Unexpected case") + End Select + Assert.Equal("get,set", probe.LogText) + End Sub + + + Public Sub CaseClauseWritesBackBeforeItsBody() + Dim probe As New Probe + Dim x = 1 + Select Case x + Case Increment(probe.Value) + Assert.Equal(1, probe.Stored) + Case Else + Assert.Fail("Unexpected case") + End Select + Assert.Equal("get,set", probe.LogText) + End Sub + + + Public Sub ForBoundWritesBackBeforeTheBody() + Dim probe As New Probe + Dim iterations = 0 + For i = 0 To Increment(probe.Value) + iterations += 1 + Assert.Equal(1, probe.Stored) + Next + Assert.Equal(2, iterations) + Assert.Equal("get,set", probe.LogText) + End Sub + + + Public Sub ForEachCollectionWritesBackBeforeTheBody() + Dim probe As New Probe + For Each item In New Integer() {Increment(probe.Value)} + Assert.Equal(1, probe.Stored) + Next + For Each item In Repeat(probe.Value) + Assert.Equal(2, probe.Stored) + Next + Assert.Equal(2, probe.Stored) + End Sub + + Private Shared Function Repeat(ByRef value As Integer) As Integer() + value += 1 + Return New Integer() {value} + End Function + + + Public Sub UsingResourceWritesBackBeforeTheBody() + Dim probe As New Probe + Using d = CreateDisposable(probe.Value) + Assert.Equal(1, probe.Stored) + End Using + Assert.Equal("get,set", probe.LogText) + End Sub + + Private Shared Function CreateDisposable(ByRef value As Integer) As IDisposable + value += 1 + Return New IO.MemoryStream() + End Function + + + Public Sub SyncLockWritesBackBeforeTheBody() + Dim probe As New Probe + SyncLock CreateLock(probe.Value) + Assert.Equal(1, probe.Stored) + End SyncLock + End Sub + + Private Shared Function CreateLock(ByRef value As Integer) As Object + value += 1 + Return New Object() + End Function + + + Public Sub WithWritesBackBeforeTheBody() + Dim probe As New Probe + With CreateLock(probe.Value) + Assert.Equal(1, probe.Stored) + End With + End Sub + + + Public Sub ForStartWritesBackBeforeTheBody() + Dim probe As New Probe + For i = Increment(probe.Value) To 1 + Assert.Equal(1, probe.Stored) + Next + Assert.Equal("get,set", probe.LogText) + End Sub + + + Public Sub CatchFilterWritesBackBeforeTheHandler() + Dim probe As New Probe + Try + Throw New InvalidOperationException() + Catch ex As InvalidOperationException When IncrementIsOne(probe.Value) + Assert.Equal(1, probe.Stored) + End Try + Assert.Equal("get,set", probe.LogText) + End Sub + + Private Shared Function IncrementIsOne(ByRef value As Integer) As Boolean + Return Increment(value) = 1 + End Function + + + Public Sub LaterCaseClauseIsOnlyEvaluatedWhenReached() + Dim probe As New Probe + Select Case 1 + Case 1 + Assert.Equal(0, probe.Stored) + Case Increment(probe.Value) + Assert.Fail("Unexpected case") + End Select + Assert.Equal("", probe.LogText) + End Sub + + + Public Sub NestedBlockHeadersWriteBackBeforeTheirBodies() + Dim probe As New Probe + For Each item In Repeat(probe.Value) + Select Case Increment(probe.Value) + Case 2 + Assert.Equal(2, probe.Stored) + End Select + Next + Assert.Equal(2, probe.Stored) + End Sub + + + Public Sub UnchangedStatementShapesStillWriteBack() + Dim probe As New Probe + Increment(probe.Value) + Dim local = Increment(probe.Value) + local = Increment(probe.Value) + Assert.Equal(3, local) + Assert.Equal(3, probe.Stored) + End Sub + + + Public Sub InstanceFieldInitializerWithOmittedOptionalByRefIssue1081() + Dim initialized As New FieldInitializers + Assert.Same(initialized.First, initialized.Second.ReceivedInner) + Assert.Equal("", initialized.Second.ReceivedX) + End Sub + + + Public Sub InstanceFieldInitializersWriteBackInDeclarationOrder() + Dim initialized As New FieldInitializers + Assert.Equal(1, initialized.A) + Assert.Equal(22, initialized.C) + Assert.Equal(2, initialized.Counter) + End Sub + + + Public Sub EachVariableOfAFieldDeclarationGetsItsOwnTemporary() + Dim initialized As New FieldInitializers + Assert.NotSame(initialized.D, initialized.E) + Assert.Same(initialized.First, initialized.D.ReceivedInner) + Assert.Same(initialized.First, initialized.E.ReceivedInner) + End Sub + + + Public Sub SharedFieldInitializerWritesBack() + Assert.Equal(1, SharedFieldInitializer.B) + Assert.Equal(1, SharedFieldInitializer.SharedCounter) + End Sub + + Private Class FieldInitializers + Public Property Counter As Integer + Public ReadOnly First As New Inner() + Public ReadOnly Second As New Outer(First) + Public ReadOnly A As Integer = Increment(Counter) + Public ReadOnly C As Integer = Increment(Counter) + Counter * 10 + Public ReadOnly D, E As New Outer(First) + End Class + + Private Class SharedFieldInitializer + Public Shared Property SharedCounter As Integer + Public Shared ReadOnly B As Integer = Increment(SharedCounter) + End Class + + Private Class Inner + End Class + + Private Class Outer + Public ReadOnly ReceivedInner As Inner + Public ReadOnly ReceivedX As String + + Sub New(inner As Inner, Optional ByRef x As String = "") + ReceivedInner = inner + ReceivedX = x + x = "changed" + End Sub + End Class + + + Public Sub PartialClassFieldInitializerWritesBack() + Dim initialized As New PartialFieldInitializers() + Assert.Equal(1, initialized.A) + Assert.Equal(1, initialized.Counter) + End Sub + + Partial Private Class PartialFieldInitializers + Public Property Counter As Integer + Public ReadOnly A As Integer = Increment(Counter) + End Class + + Partial Private Class PartialFieldInitializers + Public Sub New() + End Sub + End Class + + + Public Sub SeveralDeclaratorsInOneFieldDeclarationEachWriteBack() + Dim initialized As New SeveralDeclarators + Assert.Equal(1, initialized.A) + Assert.Equal(2, initialized.B) + Assert.Equal(4, initialized.Arr.Length) + Assert.Equal(3, initialized.Counter) + End Sub + + Private Class SeveralDeclarators + Public Property Counter As Integer + Public ReadOnly A As Integer = Increment(Counter), B As Integer = Increment(Counter) + Public Arr(Increment(Counter)), Other As Integer + End Class + + + Public Sub WithEventsFieldInitializerWritesBack() + Dim initialized As New WithEventsFieldInitializer + Assert.Equal(1, initialized.Counter) + Assert.Equal(1, initialized.Source.Received) + End Sub + + Private Class WithEventsFieldInitializer + Public Property Counter As Integer + Public WithEvents Source As New EventSource(Counter) + End Class + + Private Class EventSource + Public Event Changed() + Public ReadOnly Received As Integer + + Sub New(ByRef value As Integer) + value += 1 + Received = value + End Sub + End Class + + + Public Sub CallWritesBackItsArgumentsInReverseOrder() + Dim probe As New Probe + Two(probe.Value, probe.Value) + Assert.Equal(1, probe.Stored) + Assert.Equal("get,get,set,set", probe.LogText) + End Sub + + + Public Sub NestedCallWritesBackBeforeTheOuterCallsReversedWriteBacks() + Dim probe As New Probe + Three(SetToNine(probe.Value), probe.Value, probe.Value) + Assert.Equal(1, probe.Stored) + End Sub + + + Public Sub ReturnWritesBackInReverseOrderBeforeReturning() + Dim probe As New Probe + Assert.Equal(3, ReturnTwo(probe)) + Assert.Equal(1, probe.Stored) + End Sub + + Private Shared Function ReturnTwo(probe As Probe) As Integer + Return TwoAndSum(probe.Value, probe.Value) + End Function + + + Public Sub BlockHeaderWritesBackInReverseOrderBeforeTheBody() + Dim probe As New Probe + Select Case TwoAndSum(probe.Value, probe.Value) + Case 3 + Assert.Equal(1, probe.Stored) + Case Else + Assert.Fail("Unexpected case") + End Select + End Sub + + Private Shared Sub Two(ByRef a As Integer, ByRef b As Integer) + a = 1 + b = 2 + End Sub + + Private Shared Function TwoAndSum(ByRef a As Integer, ByRef b As Integer) As Integer + Two(a, b) + Return a + b + End Function + + Private Shared Sub Three(x As Integer, ByRef a As Integer, ByRef b As Integer) + Two(a, b) + End Sub + + Private Shared Function SetToNine(ByRef value As Integer) As Integer + value = 9 + Return value + End Function + + + Public Sub EachDeclaratorOfALocalDeclarationWritesBackBeforeTheNext() + Dim probe As New Probe + Dim a = Increment(probe.Value), b = Increment(probe.Value), c = probe.Stored + Assert.Equal(1, a) + Assert.Equal(2, b) + Assert.Equal(2, c) + Assert.Equal(2, probe.Stored) + Assert.Equal("get,set,get,set", probe.LogText) + End Sub + + + Public Sub AssignmentToTheWrittenBackPropertyKeepsTheCallResult() + Dim h As New Holder + h.Plain = SetValueReturnOther(h.Plain) + Assert.Equal("result", h.Plain) + End Sub + + + Public Sub AssignmentToAnIndexOfTheWriteBackWritesBackAtTheOldIndex() + Dim h As New Holder + Dim x = 0 + x = SetValueReturnOne(h.Items(x)) + Assert.Equal(1, x) + Assert.Equal("changed", h.Items(0)) + Assert.Equal("b", h.Items(1)) + x += SetValueReturnOne(h.Items(x)) + Assert.Equal(2, x) + Assert.Equal("changed", h.Items(1)) + End Sub + + + Public Sub AssignmentToTheWriteBackReceiverWritesBackToTheOldReceiver() + Dim h As New Holder + Dim original = h + h = SetValueReturnHolder(h.Plain) + Assert.NotSame(original, h) + Assert.Equal("changed", original.Plain) + Assert.Equal("", h.Plain) + Dim second = h + h = SetValueReturnHolder(h.Items(1)) + Assert.Equal("changed", second.Items(1)) + Assert.Equal("b", h.Items(1)) + End Sub + + + Public Sub CompoundAssignmentReadsItsTargetBeforeTheCall() + Dim probe As New Probe + probe.Value += Increment(probe.Value) + Assert.Equal(1, probe.Stored) + Assert.Equal("get,get,set,set", probe.LogText) + End Sub + + + Public Sub AssignmentToTheWrittenBackExtensionReceiverKeepsTheCallResult() + Dim h As New Holder + h.Plain = h.Plain.SetToChangedReturnResult() + Assert.Equal("result", h.Plain) + h.Plain = "" + h.AssignOwnPlain() + Assert.Equal("result", h.Plain) + End Sub + + Public Class Holder + Public Property Plain As String = "" + Public Property Items As New List(Of String) From {"a", "b"} + + Public Sub AssignOwnPlain() + Plain = Plain.SetToChangedReturnResult() + End Sub + End Class + + Private Shared Function SetValueReturnOther(ByRef value As String) As String + value = "changed" + Return "result" + End Function + + Private Shared Function SetValueReturnOne(ByRef value As String) As Integer + value = "changed" + Return 1 + End Function + + Private Shared Function SetValueReturnHolder(ByRef value As String) As Holder + value = "changed" + Return New Holder + End Function + + + Public Sub LocalFunctionResultAvoidsANameInScope() + Dim probe As New Probe + Assert.Equal(2, AddOne(probe)) + Assert.Equal(1, probe.Stored) + End Sub + + Private Shared Function AddOne(ret As Probe) As Integer + Return Increment(ret.Value) + 1 + End Function + + + Public Sub StructureAssignmentWritesBackBeforeAssigning() + Dim s As New Counter + s.Go() + Assert.Equal(5, s.P) + End Sub + + Private Structure Counter + Public Property P As Integer + + Public Sub Go() + P = SetToTwoReturnFive(P) + End Sub + End Structure + + Private Shared Function SetToTwoReturnFive(ByRef value As Integer) As Integer + value = 2 + Return 5 + End Function + + + Public Sub ParenthesizedCallAssignedToTheWrittenBackPropertyKeepsTheCallResult() + Dim h As New Holder + h.Plain = (SetValueReturnOther(h.Plain)) + Assert.Equal("result", h.Plain) + End Sub + + + Public Sub LastDeclaratorWritesBackAfterTheDeclaration() + Dim probe As New Probe + Dim a = Increment(probe.Value), b = Increment(probe.Value) + Assert.Equal(1, a) + Assert.Equal(2, b) + Assert.Equal(2, probe.Stored) + End Sub + + + Public Sub MidAssignmentToTheWrittenBackProperty() + Dim h As New Holder With {.Plain = "abcdef"} + Mid(h.Plain, 1) = SetValueReturnZZ(h.Plain) + Assert.Equal("ZZcdef", h.Plain) + End Sub + + Private Shared Function SetValueReturnZZ(ByRef value As String) As String + value = "changed" + Return "ZZ" + End Function + + + Public Sub ExtensionReceiverInLoopConditionWritesBackEachTime() + Dim h As New Holder + Dim count = 0 + Do While h.Plain.GrowIsShort() + count += 1 + Loop + Assert.Equal(2, count) + Assert.Equal("xxx", h.Plain) + End Sub + + Private Shared Function Increment(ByRef value As Integer) As Integer + value += 1 + Return value + End Function + + Private Class Probe + Public Stored As Integer + Public ReadOnly Log As New List(Of String) + + Public ReadOnly Property LogText As String + Get + Return String.Join(",", Log) + End Get + End Property + + Public Property Value As Integer + Get + Log.Add("get") + Return Stored + End Get + Set(value As Integer) + Log.Add("set") + Stored = value + End Set + End Property + + Public ReadOnly Property IncrementedValue As Integer + Get + Return Increment(Value) + End Get + End Property + End Class +End Class + +Public Module ByRefWriteBackPlacementExtensions + + Public Function SetToChangedReturnResult(ByRef value As String) As String + value = "changed" + Return "result" + End Function + + + Public Function GrowIsShort(ByRef value As String) As Boolean + value &= "x" + Return value.Length < 3 + End Function +End Module