diff --git a/CodeConverter/CSharp/AdditionalAssignment.cs b/CodeConverter/CSharp/AdditionalAssignment.cs index 95ff7e39f..4f874b012 100644 --- a/CodeConverter/CSharp/AdditionalAssignment.cs +++ b/CodeConverter/CSharp/AdditionalAssignment.cs @@ -5,18 +5,21 @@ namespace ICSharpCode.CodeConverter.CSharp; internal class AdditionalAssignment : IHoistedNode { + private readonly ExpressionSyntax _assignment; + public AdditionalAssignment(ExpressionSyntax lhs, ExpressionSyntax rhs) + : this(SyntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, + lhs ?? throw new ArgumentNullException(nameof(lhs)), rhs ?? throw new ArgumentNullException(nameof(rhs)))) { - RightHandSide = rhs ?? throw new ArgumentNullException(nameof(rhs)); - LeftHandSide = lhs ?? throw new ArgumentNullException(nameof(lhs)); } - public ExpressionSyntax LeftHandSide { get; set; } - public ExpressionSyntax RightHandSide { get; } + private AdditionalAssignment(ExpressionSyntax assignment) => _assignment = assignment; - public static StatementSyntax CreateAssignment(AdditionalAssignment additionalAssignment) - { - var assign = SyntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, additionalAssignment.LeftHandSide, additionalAssignment.RightHandSide); - return SyntaxFactory.ExpressionStatement(assign); - } -} \ No newline at end of file + /// + /// A parameterized property becomes a pair of methods in C#, so there's nothing to assign to: call its setter instead. + /// + public static AdditionalAssignment ViaSetter(InvocationExpressionSyntax setterCall) => new(setterCall); + + public static StatementSyntax CreateAssignment(AdditionalAssignment additionalAssignment) => + SyntaxFactory.ExpressionStatement(additionalAssignment._assignment); +} diff --git a/CodeConverter/CSharp/ArgumentConverter.cs b/CodeConverter/CSharp/ArgumentConverter.cs index adf31ce65..601de8a00 100644 --- a/CodeConverter/CSharp/ArgumentConverter.cs +++ b/CodeConverter/CSharp/ArgumentConverter.cs @@ -12,14 +12,15 @@ internal class ArgumentConverter private CommentConvertingVisitorWrapper TriviaConvertingExpressionVisitor { get; } public ByRefArgumentHoister ByRefArgumentHoister { get; } - public ArgumentConverter(VisualBasicEqualityComparison visualBasicEqualityComparison, ITypeContext typeContext, SemanticModel semanticModel, CommonConversions commonConversions) + public ArgumentConverter(VisualBasicEqualityComparison visualBasicEqualityComparison, ITypeContext typeContext, SemanticModel semanticModel, CommonConversions commonConversions, + IFieldMutationOracle fieldMutations) { CommonConversions = commonConversions; _visualBasicEqualityComparison = visualBasicEqualityComparison; _typeContext = typeContext; _semanticModel = semanticModel; TriviaConvertingExpressionVisitor = commonConversions.TriviaConvertingExpressionVisitor; - ByRefArgumentHoister = new ByRefArgumentHoister(typeContext, semanticModel, commonConversions); + ByRefArgumentHoister = new ByRefArgumentHoister(typeContext, semanticModel, commonConversions, fieldMutations); } public async Task ConvertSimpleArgumentAsync(VBSyntax.SimpleArgumentSyntax node) diff --git a/CodeConverter/CSharp/ByRefArguments/ByRefArgumentHoister.cs b/CodeConverter/CSharp/ByRefArguments/ByRefArgumentHoister.cs index abd89565e..68e95d444 100644 --- a/CodeConverter/CSharp/ByRefArguments/ByRefArgumentHoister.cs +++ b/CodeConverter/CSharp/ByRefArguments/ByRefArgumentHoister.cs @@ -1,4 +1,6 @@ -namespace ICSharpCode.CodeConverter.CSharp.ByRefArguments; +using Microsoft.CodeAnalysis.Operations; + +namespace ICSharpCode.CodeConverter.CSharp.ByRefArguments; /// /// C# can only pass a variable by reference, so a ByRef argument that isn't one gets a temporary, and VB's copy-back becomes a write-back statement. @@ -7,6 +9,7 @@ internal class ByRefArgumentHoister { private readonly ITypeContext _typeContext; private readonly SemanticModel _semanticModel; + private readonly IFieldMutationOracle _fieldMutations; private CommonConversions CommonConversions { get; } /// @@ -14,10 +17,11 @@ internal class ByRefArgumentHoister /// private readonly Stack> _writeBacksPerCall = new(); - public ByRefArgumentHoister(ITypeContext typeContext, SemanticModel semanticModel, CommonConversions commonConversions) + public ByRefArgumentHoister(ITypeContext typeContext, SemanticModel semanticModel, CommonConversions commonConversions, IFieldMutationOracle fieldMutations) { _typeContext = typeContext; _semanticModel = semanticModel; + _fieldMutations = fieldMutations; CommonConversions = commonConversions; } @@ -46,10 +50,8 @@ public CSSyntax.ExpressionSyntax HoistByRefDeclaration(VBSyntax.ExpressionSyntax bool useVar = expressionTypeInfo.Type?.Equals(expressionTypeInfo.ConvertedType, SymbolEqualityComparer.IncludeNullability) == true && !CommonConversions.ShouldPreferExplicitType(node, expressionTypeInfo.ConvertedType, out var _); var typeSyntax = CommonConversions.GetTypeSyntax(expressionTypeInfo.ConvertedType, useVar); - if (refLValue is CSSyntax.ElementAccessExpressionSyntax eae) { - //Hoist out the container so we can assign back to the same one after (like VB does) - var tmpContainer = _typeContext.PerScopeState.Hoist(new AdditionalDeclaration("tmp", eae.Expression, ValidSyntaxFactory.VarType)); - refLValue = eae.WithExpression(tmpContainer.IdentifierName); + if (refType == SemanticModelExtensions.RefConversion.PreAndPostAssignment) { + refLValue = ByRefTargetTemporaries.Hoist(_semanticModel, _typeContext, _fieldMutations, node, refLValue); } var withCast = CommonConversions.TypeConversionAnalyzer.AddExplicitConversion(node, refLValue, defaultToCast: refKind != RefKind.None); @@ -58,11 +60,27 @@ public CSSyntax.ExpressionSyntax HoistByRefDeclaration(VBSyntax.ExpressionSyntax if (refType == SemanticModelExtensions.RefConversion.PreAndPostAssignment) { var convertedLocalIdentifier = CommonConversions.TypeConversionAnalyzer.AddExplicitConversion(node, local.IdentifierName, forceSourceType: expressionTypeInfo.ConvertedType, forceTargetType: expressionTypeInfo.Type); - var writeBack = new AdditionalAssignment(refLValue, convertedLocalIdentifier); + var writeBack = CreateWriteBack(node, refLValue, convertedLocalIdentifier); if (_writeBacksPerCall.Count > 0) _writeBacksPerCall.Peek().Add(writeBack); else _typeContext.PerScopeState.Hoist(writeBack); } return local.IdentifierName; } + + private AdditionalAssignment CreateWriteBack(VBSyntax.ExpressionSyntax vbTarget, CSSyntax.ExpressionSyntax csTarget, CSSyntax.ExpressionSyntax value) + { + if (_semanticModel.GetOperation(vbTarget) is IPropertyReferenceOperation { Arguments.Length: > 0 } pro && !VBasic.VisualBasicExtensions.IsDefault(pro.Property) && + csTarget is CSSyntax.InvocationExpressionSyntax getterCall) { + return AdditionalAssignment.ViaSetter(CreateSetterCall(getterCall, pro.Property, value)); + } + return new AdditionalAssignment(csTarget, value); + } + + private static CSSyntax.InvocationExpressionSyntax CreateSetterCall(CSSyntax.InvocationExpressionSyntax getterCall, IPropertySymbol property, CSSyntax.ExpressionSyntax value) + { + var getterName = getterCall.Expression.DescendantTokens().Last(t => t.IsKind(CS.SyntaxKind.IdentifierToken)); + var setter = getterCall.Expression.ReplaceToken(getterName, CS.SyntaxFactory.Identifier(property.SetMethod.Name).WithTriviaFrom(getterName)); + return CS.SyntaxFactory.InvocationExpression(setter, CommonConversions.AddSetterValueArgument(getterCall.ArgumentList, property, value)); + } } diff --git a/CodeConverter/CSharp/ByRefArguments/ByRefTargetTemporaries.cs b/CodeConverter/CSharp/ByRefArguments/ByRefTargetTemporaries.cs new file mode 100644 index 000000000..5b9bafc3b --- /dev/null +++ b/CodeConverter/CSharp/ByRefArguments/ByRefTargetTemporaries.cs @@ -0,0 +1,188 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.Operations; + +namespace ICSharpCode.CodeConverter.CSharp.ByRefArguments; + +/// +/// A ByRef argument that VB copies back is used twice: read before the call, and written after it. +/// VB evaluates the target's receiver and index arguments once, and the write reuses their values +/// (Roslyn's UseTwiceRewriter.vb, called from RewriteByRefArgumentWithCopyBack in LocalRewriter_Call.vb). +/// The C# read and write-back are separate expressions, so a part that could have a different value the second time is hoisted into a temporary. +/// +/// +/// VB copies every part except constants and Me. A (non-Static) local or ByVal parameter gives the same value again unless it's written while the +/// enclosing expression runs, so it's only copied when that expression, or a lambda the call could run, writes it. +/// A field is also copied when the call could change it (). +/// An intrinsic operator on such parts gives the same value again too. +/// +internal class ByRefTargetTemporaries +{ + private readonly SemanticModel _semanticModel; + private readonly ITypeContext _typeContext; + private readonly IFieldMutationOracle _fieldMutations; + private readonly VBSyntax.ExpressionSyntax _vbTarget; + private readonly Lazy> _writtenSymbols; + + private ByRefTargetTemporaries(SemanticModel semanticModel, ITypeContext typeContext, IFieldMutationOracle fieldMutations, VBSyntax.ExpressionSyntax vbTarget) + { + _semanticModel = semanticModel; + _typeContext = typeContext; + _fieldMutations = fieldMutations; + _vbTarget = vbTarget; + _writtenSymbols = new Lazy>(GetSymbolsWrittenInEnclosingExpression); + } + + /// The C# target with each part VB evaluates once replaced by a hoisted temporary, where its value could otherwise differ. + public static CSSyntax.ExpressionSyntax Hoist(SemanticModel semanticModel, ITypeContext typeContext, IFieldMutationOracle fieldMutations, + VBSyntax.ExpressionSyntax vbTarget, CSSyntax.ExpressionSyntax csTarget) => + new ByRefTargetTemporaries(semanticModel, typeContext, fieldMutations, vbTarget).Hoist(csTarget); + + private CSSyntax.ExpressionSyntax Hoist(CSSyntax.ExpressionSyntax csTarget) + { + return (_semanticModel.GetOperation(_vbTarget), csTarget) switch { + (IPropertyReferenceOperation pro, CSSyntax.InvocationExpressionSyntax getterCall) => + getterCall.WithExpression(HoistReceiver(getterCall.Expression, pro)) + .WithArgumentList(getterCall.ArgumentList.WithArguments(HoistArguments(getterCall.ArgumentList.Arguments, pro))), + (IPropertyReferenceOperation pro, CSSyntax.ElementAccessExpressionSyntax indexer) => + indexer.WithExpression(HoistInstance(pro.Instance, indexer.Expression)) + .WithArgumentList(indexer.ArgumentList.WithArguments(HoistArguments(indexer.ArgumentList.Arguments, pro))), + (IArrayElementReferenceOperation element, CSSyntax.ElementAccessExpressionSyntax elementAccess) => + elementAccess.WithExpression(HoistInstance(element.ArrayReference, elementAccess.Expression)) + .WithArgumentList(elementAccess.ArgumentList.WithArguments(HoistIndices(elementAccess.ArgumentList.Arguments, element.Indices))), + (IPropertyReferenceOperation pro, CSSyntax.MemberAccessExpressionSyntax) => HoistReceiver(csTarget, pro), + // E.g. late bound: without an operation to tell what's reusable, copy the container as VB does + (_, CSSyntax.ElementAccessExpressionSyntax elementAccess) => elementAccess.WithExpression(HoistValue(elementAccess.Expression)), + _ => csTarget + }; + } + + private CSSyntax.ExpressionSyntax HoistReceiver(CSSyntax.ExpressionSyntax memberExpression, IPropertyReferenceOperation pro) + { + if (memberExpression is not CSSyntax.MemberAccessExpressionSyntax maes || pro.Property.IsStatic) { + return memberExpression; + } + return maes.WithExpression(HoistInstance(pro.Instance, maes.Expression)); + } + + /// + /// A reference can be copied, but writing a structure's property through a copy would lose the write. + /// So, like VB, a structure variable stays in place and only the parts that locate it are copied. + /// + private CSSyntax.ExpressionSyntax HoistInstance(IOperation instance, CSSyntax.ExpressionSyntax csInstance) + { + if (IsReusable(instance)) return csInstance; + if (instance.Type?.IsReferenceType == true) return HoistValue(csInstance); + return (instance, csInstance) switch { + (ILocalReferenceOperation or IParameterReferenceOperation, _) => csInstance, + (IFieldReferenceOperation { Instance: { } fieldInstance }, CSSyntax.MemberAccessExpressionSyntax maes) => + maes.WithExpression(HoistInstance(fieldInstance, maes.Expression)), + (IFieldReferenceOperation, _) => csInstance, + (IArrayElementReferenceOperation element, CSSyntax.ElementAccessExpressionSyntax elementAccess) => + elementAccess.WithExpression(HoistInstance(element.ArrayReference, elementAccess.Expression)) + .WithArgumentList(elementAccess.ArgumentList.WithArguments(HoistIndices(elementAccess.ArgumentList.Arguments, element.Indices))), + _ => HoistValue(csInstance) + }; + } + + private SeparatedSyntaxList HoistArguments(SeparatedSyntaxList csArgs, IPropertyReferenceOperation pro) + { + var parameters = pro.Property.Parameters; + return CS.SyntaxFactory.SeparatedList(csArgs.Select((csArg, i) => { + var parameter = csArg.NameColon is { } nameColon + ? parameters.FirstOrDefault(p => string.Equals(p.Name, nameColon.Name.Identifier.ValueText, StringComparison.OrdinalIgnoreCase)) + : parameters.ElementAtOrDefault(i); + var vbArg = pro.Arguments.FirstOrDefault(a => SymbolEqualityComparer.Default.Equals(a.Parameter, parameter)); + return IsReusable(vbArg) ? csArg : csArg.WithExpression(HoistValue(csArg.Expression)); + })); + } + + private SeparatedSyntaxList HoistIndices(SeparatedSyntaxList csArgs, ImmutableArray indices) + { + return CS.SyntaxFactory.SeparatedList(csArgs.Select((csArg, i) => + IsReusable(indices.ElementAtOrDefault(i)) ? csArg : csArg.WithExpression(HoistValue(csArg.Expression)))); + } + + /// A ParamArray's elements don't map one to one onto C# arguments, so they're each copied. + private bool IsReusable(IArgumentOperation vbArg) => vbArg switch { + // The converter fills in an omitted argument with a constant or a temporary of its own + { ArgumentKind: ArgumentKind.DefaultValue } => true, + { ArgumentKind: ArgumentKind.Explicit } => IsReusable(vbArg.Value), + _ => false + }; + + private bool IsReusable(IOperation vbValue) => vbValue switch { + null => true, + { ConstantValue.HasValue: true } => true, + IInstanceReferenceOperation => true, + IParenthesizedOperation p => IsReusable(p.Operand), + IConversionOperation { OperatorMethod: null } c when IsRepeatable(c) => IsReusable(c.Operand), + IUnaryOperation { OperatorMethod: null } u when IsCultureFree(u.Type) && IsCultureFree(u.Operand.Type) => IsReusable(u.Operand), + IBinaryOperation { OperatorMethod: null } b when IsCultureFree(b.Type) && IsCultureFree(b.LeftOperand.Type) && IsCultureFree(b.RightOperand.Type) => + IsReusable(b.LeftOperand) && IsReusable(b.RightOperand), + // A Static local lives as long as its method's object (or type), so another call of the method can change it + ILocalReferenceOperation l => !l.Local.IsStatic && !_writtenSymbols.Value.Contains(l.Local), + // A ByRef parameter aliases a variable of the caller's, which the call could reach some other way + IParameterReferenceOperation p => p.Parameter.RefKind == RefKind.None && !_writtenSymbols.Value.Contains(p.Parameter), + IFieldReferenceOperation f => !_writtenSymbols.Value.Contains(f.Field) && !_fieldMutations.MayChangeDuringCall(f.Field, GetCall()) && IsReusable(f.Instance), + _ => false + }; + + /// The call (or object creation, or event raise) that the ByRef target is an argument of. + private IOperation GetCall() => _semanticModel.GetOperation(_vbTarget)?.Parent is IArgumentOperation { Parent: var call } ? call : null; + + /// + /// An intrinsic operator or conversion between these types gives the same result (or exception) from the same operands. + /// One involving String or Date can read the current culture, which the call could change, and one on Object is late bound, which can run user code. + /// + private static bool IsCultureFree(ITypeSymbol type) + { + if (type is INamedTypeSymbol { OriginalDefinition.SpecialType: SpecialType.System_Nullable_T } nullable) type = nullable.TypeArguments[0]; + return type is { TypeKind: TypeKind.Enum } or { SpecialType: SpecialType.System_Boolean or SpecialType.System_Char or SpecialType.System_SByte + or SpecialType.System_Byte or SpecialType.System_Int16 or SpecialType.System_UInt16 or SpecialType.System_Int32 or SpecialType.System_UInt32 + or SpecialType.System_Int64 or SpecialType.System_UInt64 or SpecialType.System_Single or SpecialType.System_Double or SpecialType.System_Decimal }; + } + + /// + /// Besides conversions between culture-free types, a widening reference or boxing conversion only changes the static type. + /// + private static bool IsRepeatable(IConversionOperation conversion) => + conversion.Conversion.IsIdentity || + conversion.Conversion.IsImplicit && (conversion.Conversion.IsReference || conversion.Operand.Type is { IsValueType: true } && conversion.Type is { IsReferenceType: true }) || + IsCultureFree(conversion.Operand.Type) && IsCultureFree(conversion.Type); + + private CSSyntax.ExpressionSyntax HoistValue(CSSyntax.ExpressionSyntax value) => + _typeContext.PerScopeState.Hoist(new AdditionalDeclaration("tmp", value, ValidSyntaxFactory.VarType)).IdentifierName; + + /// + /// The temporaries and write-back are placed around the enclosing expression, so that's what could change a local variable in between. + /// So could any lambda in the same method (or, outside a method, in the same outermost lambda), since the call could run it. + /// + private HashSet GetSymbolsWrittenInEnclosingExpression() + { + SyntaxNode enclosing = _vbTarget; + while (enclosing.Parent is VBSyntax.ExpressionSyntax or VBSyntax.ArgumentSyntax or VBSyntax.ArgumentListSyntax) { + enclosing = enclosing.Parent; + } + // A local can only be written in the scope that declares it, which is inside the outermost method or lambda + var scopeOfLocals = _vbTarget.Ancestors().LastOrDefault(a => a is VBSyntax.MethodBlockBaseSyntax or VBSyntax.LambdaExpressionSyntax); + var lambdasInMember = scopeOfLocals?.DescendantNodes().OfType() + ?? Enumerable.Empty(); + + var written = lambdasInMember.Prepend(enclosing) + .SelectMany(GetVariablesWrittenIn); + return new HashSet(written, SymbolEqualityComparer.Default); + } + + private IEnumerable GetVariablesWrittenIn(SyntaxNode node) => + _semanticModel.GetOperation(node)?.DescendantsAndSelf() + .Select(o => (Operation: o, Variable: GetReferencedVariable(o))) + .Where(r => r.Variable != null && VariableWrites.IsWrite(r.Operation)) + .Select(r => r.Variable) ?? Enumerable.Empty(); + + private static ISymbol GetReferencedVariable(IOperation operation) => operation switch { + ILocalReferenceOperation l => l.Local, + IParameterReferenceOperation p => p.Parameter, + IFieldReferenceOperation f => f.Field, + _ => null + }; +} diff --git a/CodeConverter/CSharp/ByRefArguments/FieldWriteAnalysis.cs b/CodeConverter/CSharp/ByRefArguments/FieldWriteAnalysis.cs new file mode 100644 index 000000000..4787ee5c0 --- /dev/null +++ b/CodeConverter/CSharp/ByRefArguments/FieldWriteAnalysis.cs @@ -0,0 +1,114 @@ +using System.Runtime.CompilerServices; +using Microsoft.CodeAnalysis.Operations; +using static Microsoft.CodeAnalysis.VisualBasic.VisualBasicExtensions; + +namespace ICSharpCode.CodeConverter.CSharp.ByRefArguments; + +/// +/// Sound without knowing what a call reaches: a field can only change during a call if something can write it after construction. +/// A field keeps its value while any call runs when it's Const or ReadOnly, or when only this compilation can write it +/// and nothing in it does, outside construction of the object (or type) that holds it. +/// +/// +/// Construction is excluded because it has finished before a caller can read the field: a constructor's writes to its own instance's fields, +/// a shared constructor's writes to shared fields, and field initializers (which run as part of those). A lambda in a constructor can run later, so it isn't excluded. +/// Computed once per project, on first use. Each document is converted with a compilation of its own (after expanding its root), +/// so fields are matched by documentation ID rather than by symbol. +/// +internal class FieldWriteAnalysis : IFieldMutationOracle +{ + private readonly Compilation _compilation; + private readonly Lazy> _fieldsWrittenAfterConstruction; + private readonly Lazy _hasFriendAssemblies; + + public FieldWriteAnalysis(Compilation compilation) + { + _compilation = compilation; + _fieldsWrittenAfterConstruction = new Lazy>(FindFieldsWrittenAfterConstruction); + _hasFriendAssemblies = new Lazy(() => compilation.Assembly.GetAttributes() + .Any(a => a.AttributeClass?.Name == nameof(InternalsVisibleToAttribute))); + } + + /// Ignores : a call graph could narrow the answer to the fields the call can transitively write. + public bool MayChangeDuringCall(IFieldSymbol field, IOperation call) + { + field = field.OriginalDefinition; + if (field.IsConst) return false; + // Assigning a whole structure (`s = New S(9)`) overwrites every instance field, ReadOnly or not + if (!field.IsStatic && field.ContainingType.IsValueType) return true; + if (field.IsReadOnly) return false; + // An auto-property's backing field (or a WithEvents variable's) is written through the property, which this doesn't follow + if (field.AssociatedSymbol is IPropertySymbol) return true; + if (CanBeWrittenOutsideCompilation(field) || CanBeMutatedThroughMembers(field)) return true; + return _fieldsWrittenAfterConstruction.Value.Contains(field.GetDocumentationCommentId()); + } + + private bool CanBeWrittenOutsideCompilation(IFieldSymbol field) + { + if (field.ContainingAssembly?.Name != _compilation.AssemblyName) return true; + for (ISymbol symbol = field; symbol is not null and not INamespaceSymbol; symbol = symbol.ContainingSymbol) { + switch (symbol.DeclaredAccessibility) { + case Accessibility.Private: + return false; + case Accessibility.Internal or Accessibility.ProtectedAndInternal: + return _hasFriendAssemblies.Value; + } + } + return true; + } + + /// + /// A structure field can be changed by calling a method on it or assigning one of its members, not just by assigning the field. + /// + private static bool CanBeMutatedThroughMembers(IFieldSymbol field) => + field.Type.IsValueType && field.Type.SpecialType == SpecialType.None && field.Type.TypeKind != TypeKind.Enum; + + private HashSet FindFieldsWrittenAfterConstruction() + { + var written = new HashSet(StringComparer.Ordinal); + foreach (var tree in _compilation.SyntaxTrees) { + var semanticModel = _compilation.GetSemanticModel(tree, true); + foreach (var name in tree.GetRoot().DescendantNodes().OfType()) { + if (semanticModel.GetSymbolInfo(name).Symbol is not IFieldSymbol { IsConst: false, IsReadOnly: false } field) continue; + var reference = name.Parent is VBSyntax.MemberAccessExpressionSyntax maes && maes.Name == name ? (SyntaxNode)maes : name; + if (semanticModel.GetOperation(reference) is { } operation && VariableWrites.IsWrite(operation) && + !IsDuringConstruction(semanticModel, reference, field)) { + written.Add(field.OriginalDefinition.GetDocumentationCommentId()); + } + } + } + return written; + } + + private static bool IsDuringConstruction(SemanticModel semanticModel, SyntaxNode reference, IFieldSymbol field) + { + if (!field.IsStatic && reference is VBSyntax.MemberAccessExpressionSyntax { Expression: not (VBSyntax.MeExpressionSyntax or VBSyntax.MyClassExpressionSyntax) }) { + return false; + } + foreach (var ancestor in reference.Ancestors()) { + switch (ancestor) { + case VBSyntax.LambdaExpressionSyntax: + return false; + case VBSyntax.ConstructorBlockSyntax ctor: + return IsConstructing(semanticModel.GetDeclaredSymbol(ctor.SubNewStatement), field); + case VBSyntax.FieldDeclarationSyntax or VBSyntax.PropertyStatementSyntax: + var containingType = semanticModel.GetDeclaredSymbol(ancestor.FirstAncestorOrSelf()?.BlockStatement); + return SymbolEqualityComparer.Default.Equals(containingType, field.ContainingType) && IsSharedDeclaration(ancestor) == field.IsStatic; + case VBSyntax.MethodBlockBaseSyntax or VBSyntax.TypeBlockSyntax: + return false; + } + } + return false; + } + + private static bool IsConstructing(IMethodSymbol constructor, IFieldSymbol field) => + SymbolEqualityComparer.Default.Equals(constructor?.ContainingType, field.ContainingType) && constructor.IsStatic == field.IsStatic; + + /// A field declaration or property statement. + private static bool IsSharedDeclaration(SyntaxNode declaration) + { + var modifiers = declaration is VBSyntax.FieldDeclarationSyntax f ? f.Modifiers : ((VBSyntax.PropertyStatementSyntax)declaration).Modifiers; + return modifiers.Any(m => m.IsKind(VBasic.SyntaxKind.SharedKeyword)) || + declaration.FirstAncestorOrSelf() is VBSyntax.ModuleBlockSyntax; + } +} diff --git a/CodeConverter/CSharp/ByRefArguments/IFieldMutationOracle.cs b/CodeConverter/CSharp/ByRefArguments/IFieldMutationOracle.cs new file mode 100644 index 000000000..84a9a9fdd --- /dev/null +++ b/CodeConverter/CSharp/ByRefArguments/IFieldMutationOracle.cs @@ -0,0 +1,11 @@ +namespace ICSharpCode.CodeConverter.CSharp.ByRefArguments; + +/// +/// Answers whether a field can hold a different value after a call than before it, so the converter knows whether reading it again is safe. +/// +internal interface IFieldMutationOracle +{ + /// The call whose ByRef argument reads the field. Lets an implementation narrow the answer to what that call can reach. + /// False only when the field certainly keeps its value while the call runs. + bool MayChangeDuringCall(IFieldSymbol field, IOperation call); +} diff --git a/CodeConverter/CSharp/ByRefArguments/README.md b/CodeConverter/CSharp/ByRefArguments/README.md index e5567face..9671b8b34 100644 --- a/CodeConverter/CSharp/ByRefArguments/README.md +++ b/CodeConverter/CSharp/ByRefArguments/README.md @@ -27,19 +27,51 @@ Sources: [passing arguments by value and by reference](https://learn.microsoft.c Within each of these, one call's write-backs are hoisted after its whole argument list, last argument first, so a nested call's come before them: `ByRefArgumentHoister.WithWriteBacksInVbOrderAsync`. +In a `Structure`, a local function can't use `this` (CS1673). When the call uses an instance member, the local function takes `ref S self` and is called with `ref this`, and its body uses `self` for `this` (the converted body always qualifies instance members, which are only simplified later). `ref this` is legal wherever VB can use `Me` in a structure; VB has no read-only members (where it's CS1605), no `Me` in a structure's lambdas (BC36638) and no `MyBase` in a structure (BC30044, so an unqualified base call can't be hoisted): `WriteBackPlacement.HoistAndCallLocalFunctionAsync`. + +A local function can't use a ref local either (CS8175), such as the `ref var withBlock` of a `With` over a structure field. References to a ref local are marked with its type, and the local function takes each one it uses from outside its body as a `ref` parameter of the same name: `RefLocalReferences`. The enclosing method's ByRef parameters are passed the same way (CS1628), including one reused directly as a `With` receiver (`With b : Inc(.X)` becomes `Inc(ref b.X)`). The candidates are the parameters the VB operations reference, so a type named like a parameter isn't one, and the converted body then drops those it no longer mentions (a header evaluated into `withBlock`): `WriteBackPlacement.RefParametersUsedIn`. + The classes in this folder hold the ByRef-specific decisions. The placement mechanics stay with the code they extend: the hoisted node types and `PerScopeState` (the hoisting for every feature), `MethodBodyExecutableStatementVisitor` (jumps) and `CommonConversions` (field initializers, whose method wraps any hoisted statement, not only ByRef ones). +### What the write-back writes to + +Source: Roslyn's [`UseTwiceRewriter.vb`](https://github.com/dotnet/roslyn/blob/main/src/Compilers/VisualBasic/Portable/Lowering/UseTwiceRewriter.vb), which `RewriteByRefArgumentWithCopyBack` uses to read the target and then write it with the setter. Behaviour is covered by `Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedProperty*.vb`. + +* VB evaluates the target's receiver and index arguments once, and the write-back reuses their values. It copies each into a temporary except literals, constants and `Me`. +* The converter hoists a `tmp` only where the second evaluation could give a different value: `ByRefTargetTemporaries`. + * A write is anything in `VariableWrites`: an assignment, compound assignment, ByRef or late-bound argument, `For`/`For Each` control variable, `ReDim`, `Erase` or `Mid` statement. + * A local or `ByVal` parameter is reused unless the enclosing expression, or any lambda in the same method (outside a method, the outermost enclosing lambda), writes it: the call could run that lambda. Only those can. A `ByRef` parameter aliases a variable the call might reach, and a `Static` local outlives the call like a field, so both are copied. + * An intrinsic unary or binary operator, or a conversion, on reusable operands is reused when it gives the same result, or throws the same exception, again: between numeric, `Boolean`, `Char` and enum types (or their nullables), or an identity, widening reference or boxing conversion. Anything involving `String` or `Date` can read the current culture, which the call can change (`d & ""` gives `1.5` or `1,5`), one on `Object` is late bound, and a user-defined one runs user code, so those are copied. + * A field is reused only if, in addition, the call can't change it (`IFieldMutationOracle.MayChangeDuringCall`). `FieldWriteAnalysis` answers that once per project (created by `VBToCSProjectContentsConverter`, matching fields by documentation ID since each document gets its own compilation), soundly without knowing what the call reaches: a field can't change if it's `Const` or `ReadOnly`, or if only this compilation can write it (it, or a type containing it, is `Private`, or `Friend` with no `InternalsVisibleTo`) and nothing in it writes it outside construction. Construction (a constructor writing its own instance's field, a shared constructor writing a shared field, or a field or property initializer) has finished before anything can read the field, but a lambda in it may run later, so that isn't excluded. A structure field (other than a primitive or enum) is always treated as changeable, since calling a method on it can change it. So is an auto-property's backing field (`_Idx`), which is written through the property, and any instance field of a structure, even `ReadOnly`: assigning the whole structure (`s = New S(9)`) overwrites it. + * A call graph of method references could narrow this to the fields the call can transitively write. To stay sound it would treat overridable and interface calls as reaching every implementation, delegate invocations and late-bound calls as reaching anything a delegate or late-bound call could, and calls outside the compilation as reaching any field they can see. +* A parameterized property (not the default one) becomes `get_X`/`set_X` methods, so its write-back calls the setter with the same index arguments: `ByRefArgumentHoister.CreateWriteBack`, `AdditionalAssignment.ViaSetter`. It takes its place in the call's reversed write-back order like any other. +* A `ReadOnly` property isn't written back (`GetRefConversionForExpression`), so it's evaluated once and needs no temporaries. + +| VB target | C# | +|---|---| +| `Qr(i, 2)`, `Qr(i + 1, -i)`, `other.Qr(_index, 2)` (`_index` a `Private` field written only in constructors) | `get_Qr(i, 2)` … `set_Qr(i, 2, arg)` | +| `other.Qr(_writtenElsewhere, 2)`, `other.Qr(PublicIndex, 2)` | `var tmp = _writtenElsewhere;` … `other.set_Qr(tmp, 2, arg)` | +| `other.Qr(NextIndex(), 2)` | `var tmp = NextIndex();` … `other.get_Qr(tmp, 2)` … `other.set_Qr(tmp, 2, arg)` | +| `GetC().Qr(1, 2)`, `GetC().Plain` | `var tmp = GetC();` … `tmp.set_Qr(1, 2, arg)`, `tmp.Plain = arg` | +| `other(NextIndex())`, `Me(i, 5)` (default property, indexer or array) | `var tmp = NextIndex();` … `other[tmp] = arg`, `this[i, 5] = arg`: the container follows the receiver rules | +| `Two(other.Qr(i, 2), i)` | `var tmp = i;` … `other.set_Qr(tmp, 2, arg)` | +| `cells(NextIndex()).Text`, `GetHolder().Cell.Text` (`Cell` is a structure) | `var tmp = NextIndex();` … `cells[tmp].Text = arg`, `var tmp = GetHolder();` … `tmp.Cell.Text = arg`: a structure variable is written in place (`ByRefTargetTemporaries.HoistInstance`) | + 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. +* A parameterized property with a `ParamArray` converts to a setter with `params` before the value (`set_PA(params int[] idx, string value)`, CS0231), so it can't be written back. +* An array element whose array isn't a variable, passed to a ByRef parameter of a wider type (`BumpLong(GetArr()(Next1()))` with an `Integer` array and a `ByRef Long` parameter), isn't written back: `IsRefArrayAcces` only treats it as an array element when the array is passed inline. VB writes it back. +* The receiver of an extension method that takes it ByRef has an empty `NoneOperation` in Roslyn's VB operation tree, so it gets none of the above: a parameterized property there stays `this.Qr(2)` (CS1061), and a receiver like `GetC().Plain` is evaluated twice. A fix would rebuild the target from symbols and syntax. +* A late-bound parameterized property (`SetValue(o.Qr(1))` with `o As Object`) converts to `((dynamic)o).Qr(1)`, which throws `RuntimeBinderException`, and isn't written back. VB reads and writes it through `NewLateBinding.LateGet`/`LateSet` (or `LateIndexGet`/`LateIndexSet`). * 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 member of a structure returned by a property (`Inc(InnerProp.P)`) writes back with `InnerProp.P = argv`, which C# rejects because `InnerProp` returns a copy (CS1612). +* `Select Case Inc(P)` with `Case Inc(P)` gives `case var @case when ...` (CS0825). * A `ReadOnly` auto-property is assignable in its type's constructor and initializers, so VB writes it back there, but `GetRefConversionForExpression` treats every read-only property as not writable. A fix also needs the C# write-back target to be assignable from the field initializer method. diff --git a/CodeConverter/CSharp/ByRefArguments/RefLocalReferences.cs b/CodeConverter/CSharp/ByRefArguments/RefLocalReferences.cs new file mode 100644 index 000000000..9a3de0962 --- /dev/null +++ b/CodeConverter/CSharp/ByRefArguments/RefLocalReferences.cs @@ -0,0 +1,41 @@ +using System.Runtime.CompilerServices; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace ICSharpCode.CodeConverter.CSharp.ByRefArguments; + +/// +/// A local function can't use a ref local from its enclosing method (CS8175), e.g. the ref var withBlock of a With block over a structure field. +/// Each reference to a ref local is marked with the local's type, so that a local function can find the ones in its body and take them as ref parameters. +/// +internal static class RefLocalReferences +{ + private const string AnnotationKind = "CodeConverter.RefLocalReference"; + + /// An annotation's data can only be a string, but the annotation itself is kept on every copy of the node, so it can key the type. + private static readonly ConditionalWeakTable RefLocalTypes = new(); + + public static IdentifierNameSyntax Mark(IdentifierNameSyntax reference, TypeSyntax refLocalType) + { + var annotation = new SyntaxAnnotation(AnnotationKind); + RefLocalTypes.Add(annotation, refLocalType); + return reference.WithAdditionalAnnotations(annotation); + } + + /// One marked reference per ref local that uses from outside it, and the local's type. + /// A ref local declared inside, e.g. by a With block in a lambda argument, is in scope already. + /// Generated names are unique within a method, so a name declared inside can't also refer to one outside. + public static IEnumerable<(IdentifierNameSyntax Reference, TypeSyntax Type)> FindIn(SyntaxNode node) + { + var declaredInside = new HashSet(node.DescendantNodes().OfType().Select(v => v.Identifier.ValueText)); + return node.GetAnnotatedNodes(AnnotationKind).OfType() + .Where(n => !declaredInside.Contains(n.Identifier.ValueText)) + .GroupBy(n => n.Identifier.ValueText) + .Select(g => g.First()) + .Select(n => (n, GetRefLocalType(n))); + } + + private static TypeSyntax GetRefLocalType(IdentifierNameSyntax reference) => + RefLocalTypes.TryGetValue(reference.GetAnnotations(AnnotationKind).First(), out var type) + ? type + : throw new InvalidOperationException($"Ref local reference {reference} was annotated without {nameof(Mark)}"); +} diff --git a/CodeConverter/CSharp/ByRefArguments/VariableWrites.cs b/CodeConverter/CSharp/ByRefArguments/VariableWrites.cs new file mode 100644 index 000000000..64194192d --- /dev/null +++ b/CodeConverter/CSharp/ByRefArguments/VariableWrites.cs @@ -0,0 +1,31 @@ +using Microsoft.CodeAnalysis.Operations; + +namespace ICSharpCode.CodeConverter.CSharp.ByRefArguments; + +/// +/// Every VB construct that stores to a variable (local, parameter or field), so analyses that ask "can this change?" agree on what a write is. +/// +internal static class VariableWrites +{ + /// A local, parameter or field reference. + public static bool IsWrite(IOperation reference) => IsWrittenBySyntax(reference.Syntax) || reference.Parent switch { + IAssignmentOperation a => a.Target == reference, + // Without a known parameter (in code that doesn't compile), assume it could be ByRef + IArgumentOperation a => a.Parameter is null || a.Parameter.RefKind != RefKind.None, + IForToLoopOperation l => l.LoopControlVariable == reference, + IForEachLoopOperation l => l.LoopControlVariable == reference, + IReDimClauseOperation => true, + // Late-bound arguments are copied back when the method found at runtime takes them ByRef + IDynamicInvocationOperation or IDynamicIndexerAccessOperation or IDynamicObjectCreationOperation => true, + _ => false + }; + + /// + /// Statements whose operation tree doesn't show the variable as written. + /// + private static bool IsWrittenBySyntax(SyntaxNode reference) => reference.Parent switch { + VBSyntax.EraseStatementSyntax => true, + VBSyntax.SimpleArgumentSyntax { Parent.Parent: VBSyntax.MidExpressionSyntax mid } arg => mid.ArgumentList.Arguments.First() == arg, + _ => false + }; +} diff --git a/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs b/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs index 982457c1a..f97ca8995 100644 --- a/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs +++ b/CodeConverter/CSharp/ByRefArguments/WriteBackPlacement.cs @@ -33,7 +33,8 @@ public WriteBackPlacement(SemanticModel semanticModel, HashSet generated public async Task HoistAndCallLocalFunctionAsync(VBasic.VisualBasicSyntaxNode invocation, IMethodSymbol invocationSymbol, ExpressionSyntax csExpression) { // Each local function is its own scope, so only names visible at the call can clash, e.g. a parameter used in the argument - var retVariableName = NameGenerator.CS.GetUniqueVariableNameInScope(_semanticModel, new HashSet(), invocation, "ret"); + var namesInLocalFunction = new HashSet(); + var retVariableName = NameGenerator.CS.GetUniqueVariableNameInScope(_semanticModel, namesInLocalFunction, invocation, "ret"); var localFuncName = $"local{invocationSymbol.Name}"; var callAndStoreResult = CommonConversions.CreateLocalVariableDeclarationAndAssignment(retVariableName, csExpression); @@ -45,31 +46,81 @@ public async Task HoistAndCallLocalFunctionAsync(VBa ); 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 arguments = new List(); + var parameters = new List(); + if (IsInStructAndUsesThis(enclosingSymbol, block)) { + var selfName = NameGenerator.CS.GetUniqueVariableNameInScope(_semanticModel, namesInLocalFunction, invocation, "self"); + block = block.ReplaceNodes(block.DescendantNodes().OfType(), (_, _) => ValidSyntaxFactory.IdentifierName(selfName)); + arguments.Add(SyntaxFactory.Argument(SyntaxFactory.ThisExpression()).WithRefKindKeyword(SyntaxFactory.Token(SyntaxKind.RefKeyword))); + parameters.Add(RefParameter(selfName, CommonConversions.GetTypeSyntax(enclosingSymbol.ContainingType))); + } + + AddArgumentsAndParameters(RefParametersUsedIn(invocation, block, enclosingSymbol)); + + foreach (var (reference, type) in RefLocalReferences.FindIn(block)) { + arguments.Add(SyntaxFactory.Argument(reference).WithRefKindKeyword(SyntaxFactory.Token(SyntaxKind.RefKeyword))); + parameters.Add(RefParameter(reference.Identifier.ValueText, type)); + } + + var localFunc = _typeContext.PerScopeState.Hoist(new HoistedFunction(localFuncName, returnType, block, SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(parameters)))); + return SyntaxFactory.InvocationExpression(localFunc.TempIdentifier, SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(arguments))); - var localFunc = _typeContext.PerScopeState.Hoist(new HoistedFunction(localFuncName, returnType, block, SyntaxFactory.ParameterList(@params))); - return SyntaxFactory.InvocationExpression(localFunc.TempIdentifier, SyntaxFactory.ArgumentList(args)); + static ParameterSyntax RefParameter(string name, TypeSyntax type) => + SyntaxFactory.Parameter(SyntaxFactory.Identifier(name)) + .WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.RefKeyword))) + .WithType(type); - (SeparatedSyntaxList, SeparatedSyntaxList) CreateArgumentsAndParametersLists(List parameterSymbols) + void AddArgumentsAndParameters(List parameterSymbols) { - var arguments = new List(); - var parameters = new List(); foreach (var p in parameterSymbols) { - var arg = (ArgumentSyntax)CommonConversions.CsSyntaxGenerator.Argument(p.RefKind, SyntaxFactory.IdentifierName(p.Name)); + var arg = (ArgumentSyntax)CommonConversions.CsSyntaxGenerator.Argument(p.RefKind, ValidSyntaxFactory.IdentifierName(p.Name)); arguments.Add(arg); var par = (ParameterSyntax)CommonConversions.CsSyntaxGenerator.ParameterDeclaration(p); - parameters.Add(par.WithDefault(null)); + parameters.Add(par.WithIdentifier(CommonConversions.CsEscapedIdentifier(p.Name)).WithDefault(null)); } - return (SyntaxFactory.SeparatedList(arguments), SyntaxFactory.SeparatedList(parameters)); } } + /// + /// A local function can't use the enclosing method's ByRef parameters (CS1628), so it takes each one its converted body uses as a ref parameter. + /// The candidates are the parameters the VB call references, so a type or namespace with the same name as a parameter (H.S beside h As H) isn't one. + /// A With block's implicit receiver counts as its With expression, because the converter may reuse that expression directly + /// (With b : Inc(.X) becomes Inc(ref b.X)). + /// A candidate is then dropped if the converted body doesn't mention it, i.e. the With header was evaluated into withBlock (With arr(i)). + /// The converter writes a parameter reference with the declared casing, escaped like any identifier (@params, whose token text keeps the @), so the names compare ordinally after the same escaping. + /// + private List RefParametersUsedIn(VBasic.VisualBasicSyntaxNode invocation, BlockSyntax block, ISymbol enclosingSymbol) + { + if (_semanticModel.GetOperation(invocation) is not { } operation) return new List(); + var candidates = DescendantsResolvingWithReceivers(operation) + .OfType().Select(p => p.Parameter) + .Where(p => p.RefKind != RefKind.None && SymbolEqualityComparer.Default.Equals(p.ContainingSymbol, enclosingSymbol)) + .Distinct(SymbolEqualityComparer.Default).ToList(); + if (candidates.Count == 0) return candidates; + var namesUsed = new HashSet(block.DescendantNodes().OfType().Where(IsNotAMemberName).Select(n => n.Identifier.ValueText), StringComparer.Ordinal); + return candidates.Where(p => namesUsed.Contains(CommonConversions.CsEscapedIdentifier(p.Name).ValueText)).ToList(); + + static bool IsNotAMemberName(IdentifierNameSyntax name) => + name.Parent switch { + MemberAccessExpressionSyntax member => member.Expression == name, + MemberBindingExpressionSyntax or NameColonSyntax or NameEqualsSyntax => false, + AssignmentExpressionSyntax { Parent: InitializerExpressionSyntax initializer } assignment when initializer.IsKind(CS.SyntaxKind.ObjectInitializerExpression) => assignment.Left != name, + _ => true + }; + } + + /// + /// The operations within , where a With block's implicit receiver is replaced by the operations of the With expression. + /// + private IEnumerable DescendantsResolvingWithReceivers(IOperation operation) => + operation.DescendantsAndSelf().SelectMany(o => + o is IInstanceReferenceOperation { ReferenceKind: InstanceReferenceKind.ImplicitReceiver } && + o.Syntax is VBSyntax.ExpressionSyntax { Parent: VBSyntax.WithStatementSyntax } withExpression && + _semanticModel.GetOperation(withExpression) is { } withOperation + ? DescendantsResolvingWithReceivers(withOperation) + : new[] { o }); + public bool RequiresLocalFunction(VBSyntax.InvocationExpressionSyntax invocation, IMethodSymbol invocationSymbol) { if (IsLoopCondition(invocation)) { @@ -84,7 +135,6 @@ invocation.Expression is VBSyntax.MemberAccessExpressionSyntax member && } if (invocation.ArgumentList == null) return false; - if (IsInStructAndUsesThis(invocation)) return false; var definitelyExecutedAfterPrevious = DefinitelyExecutedAfterPreviousStatement(invocation); var assignmentChangesWhatIsWrittenBack = AssignmentChangesWhatIsWrittenBack(invocation, invocationSymbol); var nextStatementDefinitelyExecuted = NextStatementDefinitelyExecutedAfter(invocation) && !assignmentChangesWhatIsWrittenBack; @@ -99,7 +149,8 @@ bool RequiresLocalFunction(RefConversion possibleInline, VBSyntax.InvocationExpr if (RefConversion.Inline == refConversion || possibleInline == refConversion) return false; if (!(a is VBSyntax.SimpleArgumentSyntax sas)) return false; var argExpression = sas.Expression.SkipIntoParens(); - if (argExpression is VBSyntax.InstanceExpressionSyntax) return false; + // A copy of a class's Me is the same reference whenever it's taken, but a structure's Me is copied by value, so it must be taken at the call + if (argExpression is VBSyntax.InstanceExpressionSyntax) return _semanticModel.GetTypeInfo(argExpression).Type?.IsValueType == true; return !_semanticModel.GetConstantValue(argExpression).HasValue; } } @@ -168,14 +219,16 @@ public static bool IsLoopCondition(SyntaxNode node) } /// - /// Conservative version of _semanticModel.AnalyzeControlFlow(invocation).ExitPoints to account for exceptions - /// - /// - /// A local function in a struct can't use this (CS1673), so there the write-back stays after the statement: compiling but late, a known gap. + /// A local function in a struct can't use this (CS1673), but it can take it as a ref parameter: local(ref this). + /// That's legal wherever VB can use Me in a structure: methods, property and event accessors, constructors (C# 11 structs are auto-default), + /// iterators and async methods (which work on a copy in both languages). VB has no read-only members, where ref this would be CS1605, + /// and doesn't allow Me in a lambda in a structure (BC36638), so the call is never inside one. + /// The converted body qualifies every instance member with this (the simplifier removes it later), so it uses this exactly when it contains one. + /// Deciding from the VB operation instead would have to resolve a With block's implicit receiver, which is this only for With Me. /// - private bool IsInStructAndUsesThis(VBSyntax.InvocationExpressionSyntax invocation) => - _semanticModel.GetEnclosingSymbol(invocation.SpanStart) is { IsStatic: false, ContainingType.TypeKind: TypeKind.Struct } && - _semanticModel.GetOperation(invocation)?.DescendantsAndSelf().OfType().Any() != false; + private static bool IsInStructAndUsesThis(ISymbol enclosingSymbol, BlockSyntax block) => + enclosingSymbol is { IsStatic: false, ContainingType.TypeKind: TypeKind.Struct } && + block.DescendantNodes().OfType().Any(); private bool DefinitelyExecutedAfterPreviousStatement(VBSyntax.InvocationExpressionSyntax invocation) { diff --git a/CodeConverter/CSharp/CommonConversions.cs b/CodeConverter/CSharp/CommonConversions.cs index b5135bb26..b77496088 100644 --- a/CodeConverter/CSharp/CommonConversions.cs +++ b/CodeConverter/CSharp/CommonConversions.cs @@ -649,6 +649,22 @@ public static CSSyntax.VariableDeclaratorSyntax CreateVariableDeclarator(string return (null, null); } + /// + /// A parameterized property's setter takes the value after the index parameters. + /// When an index argument is named, or an optional one is left out, the value must be named too, since a positional argument can't follow them. + /// + public static CSSyntax.ArgumentListSyntax AddSetterValueArgument(CSSyntax.ArgumentListSyntax indexArgs, IPropertySymbol property, ExpressionSyntax value) + { + var valueArg = SyntaxFactory.Argument(value); + var mustNameValue = indexArgs.Arguments.Count != property.GetParameters().Length || + indexArgs.Arguments.Any(t => t.NameColon != null); + if (mustNameValue) { + valueArg = valueArg.WithNameColon(SyntaxFactory.NameColon("value")); + } + + return indexArgs.WithArguments(indexArgs.Arguments.Add(valueArg)); + } + private async Task GetParameterizedSetterArgAsync(IOperation operation) { var vbNode = (VBSyntax.ExpressionSyntax) operation.Parent.Syntax.ChildNodes().ElementAt(1); diff --git a/CodeConverter/CSharp/DeclarationNodeVisitor.cs b/CodeConverter/CSharp/DeclarationNodeVisitor.cs index dabff26a0..bc6fadb22 100644 --- a/CodeConverter/CSharp/DeclarationNodeVisitor.cs +++ b/CodeConverter/CSharp/DeclarationNodeVisitor.cs @@ -1,4 +1,5 @@ -using System.Collections.Immutable; +using ICSharpCode.CodeConverter.CSharp.ByRefArguments; +using System.Collections.Immutable; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.CSharp; @@ -43,7 +44,8 @@ internal class DeclarationNodeVisitor : VBasic.VisualBasicSyntaxVisitor _typeContext.PerScopeState; public DeclarationNodeVisitor(Document document, Compilation compilation, SemanticModel semanticModel, - CSharpCompilation csCompilation, SyntaxGenerator csSyntaxGenerator, ILookup typeToInheritors, ErrUsage errUsage) + CSharpCompilation csCompilation, SyntaxGenerator csSyntaxGenerator, ILookup typeToInheritors, + IFieldMutationOracle fieldMutations, ErrUsage errUsage) { _vbCompilation = compilation; _csSyntaxGenerator = csSyntaxGenerator; @@ -56,7 +58,7 @@ public DeclarationNodeVisitor(Document document, Compilation compilation, Semant var nullableExpressionsConverter = new VisualBasicNullableExpressionsConverter(_semanticModel); var typeConversionAnalyzer = new TypeConversionAnalyzer(semanticModel, csCompilation, _extraUsingDirectives, _csSyntaxGenerator, expressionEvaluator, nullableExpressionsConverter); CommonConversions = new CommonConversions(document, semanticModel, typeConversionAnalyzer, csSyntaxGenerator, compilation, csCompilation, _typeContext, _visualBasicEqualityComparison, errUsage); - var expressionNodeVisitor = new ExpressionNodeVisitor(semanticModel, _visualBasicEqualityComparison, _typeContext, CommonConversions, _extraUsingDirectives, _xmlImportContext, nullableExpressionsConverter); + var expressionNodeVisitor = new ExpressionNodeVisitor(semanticModel, _visualBasicEqualityComparison, _typeContext, CommonConversions, _extraUsingDirectives, _xmlImportContext, nullableExpressionsConverter, fieldMutations); _accessorDeclarationNodeConverter = new AccessorDeclarationNodeConverter(semanticModel, CommonConversions, TriviaConvertingDeclarationVisitor, _additionalDeclarations, expressionNodeVisitor.ConvertMethodBodyStatementsAsync); _triviaConvertingExpressionVisitor = CommonConversions.TriviaConvertingExpressionVisitor; _convertMethodBodyStatementsAsync = expressionNodeVisitor.ConvertMethodBodyStatementsAsync; diff --git a/CodeConverter/CSharp/ExpressionNodeVisitor.cs b/CodeConverter/CSharp/ExpressionNodeVisitor.cs index 837cc47b7..6297bea8f 100644 --- a/CodeConverter/CSharp/ExpressionNodeVisitor.cs +++ b/CodeConverter/CSharp/ExpressionNodeVisitor.cs @@ -1,3 +1,4 @@ +using ICSharpCode.CodeConverter.CSharp.ByRefArguments; using ICSharpCode.CodeConverter.CSharp.Queries; using ICSharpCode.CodeConverter.Util.FromRoslyn; using Microsoft.CodeAnalysis.CSharp; @@ -36,7 +37,8 @@ internal partial class ExpressionNodeVisitor : VBasic.VisualBasicSyntaxVisitor extraUsingDirectives, XmlImportContext xmlImportContext, VisualBasicNullableExpressionsConverter visualBasicNullableTypesConverter) + HashSet extraUsingDirectives, XmlImportContext xmlImportContext, VisualBasicNullableExpressionsConverter visualBasicNullableTypesConverter, + IFieldMutationOracle fieldMutations) { _semanticModel = semanticModel; CommonConversions = commonConversions; @@ -48,7 +50,7 @@ public ExpressionNodeVisitor(SemanticModel semanticModel, _typeContext = typeContext; _extraUsingDirectives = extraUsingDirectives; _valueTupleCreationConverter = new ValueTupleCreationConverter(semanticModel, commonConversions); - _argumentConverter = new ArgumentConverter(visualBasicEqualityComparison, typeContext, semanticModel, commonConversions); + _argumentConverter = new ArgumentConverter(visualBasicEqualityComparison, typeContext, semanticModel, commonConversions, fieldMutations); _xmlExpressionConverter = new XmlExpressionConverter(xmlImportContext, extraUsingDirectives, commonConversions, semanticModel, _withBlockLhs, _generatedNames, _conditionalAccessReceivers); _nameExpressionNodeVisitor = new NameExpressionNodeVisitor(semanticModel, _generatedNames, typeContext, extraUsingDirectives, _tempNameForAnonymousScope, _withBlockLhs, commonConversions, _argumentConverter, TriviaConvertingExpressionVisitor, _conditionalAccessReceivers, rangeVariableReplacements); _operatorConverter = VbOperatorConversion.Create(TriviaConvertingExpressionVisitor, semanticModel, visualBasicEqualityComparison, commonConversions.TypeConversionAnalyzer); diff --git a/CodeConverter/CSharp/MethodBodyExecutableStatementVisitor.cs b/CodeConverter/CSharp/MethodBodyExecutableStatementVisitor.cs index 38d5de646..9fbdc9e58 100644 --- a/CodeConverter/CSharp/MethodBodyExecutableStatementVisitor.cs +++ b/CodeConverter/CSharp/MethodBodyExecutableStatementVisitor.cs @@ -1055,12 +1055,14 @@ private static CasePatternSwitchLabelSyntax VarWhen(SyntaxToken varName, Express reusableExprWithoutSideEffects = expr.WithoutSourceMapping(); } else { TypeSyntax forceType = null; - if (_semanticModel.GetOperation(vbExpr.SkipIntoParens()).IsAssignableExpression()) { + // VB's With uses a structure variable in place, but only copies a reference, so it keeps the original object even if the variable is reassigned + if (_semanticModel.GetTypeInfo(vbExpr).Type?.IsReferenceType != true && _semanticModel.GetOperation(vbExpr.SkipIntoParens()).IsAssignableExpression()) { forceType = SyntaxFactory.RefType(ValidSyntaxFactory.VarType); expr = SyntaxFactory.RefExpression(expr); } var (stmt, id) = CreateLocalVariableWithUniqueName(vbExpr, variableNameBase, expr, forceType); + if (forceType != null) id = RefLocalReferences.Mark(id, CommonConversions.GetTypeSyntax(_semanticModel.GetTypeInfo(vbExpr).Type)); stmts = stmts.Add(stmt); reusableExprWithoutSideEffects = exprWithoutSideEffects = id; } diff --git a/CodeConverter/CSharp/NameExpressionNodeVisitor.cs b/CodeConverter/CSharp/NameExpressionNodeVisitor.cs index d9f3ad3e8..7331794f4 100644 --- a/CodeConverter/CSharp/NameExpressionNodeVisitor.cs +++ b/CodeConverter/CSharp/NameExpressionNodeVisitor.cs @@ -467,16 +467,7 @@ private async Task TryConvertParameterizedPropertyAs var args = await _argumentConverter.ConvertArgumentListOrEmptyAsync(node, optionalArgumentList); if (extraArg != null) { - var extraArgSyntax = SyntaxFactory.Argument(extraArg); - var propertySymbol = ((IPropertyReferenceOperation)operation).Property; - var forceNamedExtraArg = args.Arguments.Count != propertySymbol.GetParameters().Length || - args.Arguments.Any(t => t.NameColon != null); - - if (forceNamedExtraArg) { - extraArgSyntax = extraArgSyntax.WithNameColon(SyntaxFactory.NameColon("value")); - } - - args = args.WithArguments(args.Arguments.Add(extraArgSyntax)); + args = CommonConversions.AddSetterValueArgument(args, ((IPropertyReferenceOperation)operation).Property, extraArg); } return SyntaxFactory.InvocationExpression((ExpressionSyntax)expr, args); diff --git a/CodeConverter/CSharp/VBToCSProjectContentsConverter.cs b/CodeConverter/CSharp/VBToCSProjectContentsConverter.cs index a3148373e..a1d727197 100644 --- a/CodeConverter/CSharp/VBToCSProjectContentsConverter.cs +++ b/CodeConverter/CSharp/VBToCSProjectContentsConverter.cs @@ -1,4 +1,5 @@ -using System.Runtime.CompilerServices; +using ICSharpCode.CodeConverter.CSharp.ByRefArguments; +using System.Runtime.CompilerServices; using System.Xml.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.VisualBasic; @@ -22,6 +23,7 @@ internal class VBToCSProjectContentsConverter : IProjectContentsConverter private readonly IProgress _progress; private readonly CancellationToken _cancellationToken; private ILookup _typeToInheritors; + private IFieldMutationOracle _fieldMutations; private ErrUsage _errUsage; public VBToCSProjectContentsConverter(ConversionOptions conversionOptions, @@ -49,6 +51,7 @@ public async Task InitializeSourceAsync(Project project) _csharpViewOfVbSymbols = (CSharpCompilation)await _csharpReferenceProject.GetCompilationAsync(_cancellationToken); _designerToResxRelativePath = project.ReadVbEmbeddedResources().ToDictionary(r => r.LastGenOutput, r => r.RelativePath); SourceProject = await WithProjectLevelWinformsAdjustmentsAsync(project); + _fieldMutations = new FieldWriteAnalysis(await SourceProject.GetCompilationAsync(_cancellationToken)); _errUsage = new ErrUsage(SourceProject); var compilation = await project.GetCompilationAsync(_cancellationToken); @@ -79,7 +82,7 @@ private async Task WithProjectLevelWinformsAdjustmentsAsync(Project pro public async Task SingleFirstPassAsync(Document document) { - return await VisualBasicConverter.ConvertCompilationTreeAsync(document, _csharpViewOfVbSymbols, _csharpReferenceProject, OptionalOperations, _typeToInheritors, _errUsage, _cancellationToken); + return await VisualBasicConverter.ConvertCompilationTreeAsync(document, _csharpViewOfVbSymbols, _csharpReferenceProject, OptionalOperations, _typeToInheritors, _fieldMutations, _errUsage, _cancellationToken); } public async Task<(Project project, List> firstPassDocIds)> GetConvertedProjectAsync(WipFileConversion[] firstPassResults) diff --git a/CodeConverter/CSharp/VisualBasicConverter.cs b/CodeConverter/CSharp/VisualBasicConverter.cs index cd93592f1..3845e339c 100644 --- a/CodeConverter/CSharp/VisualBasicConverter.cs +++ b/CodeConverter/CSharp/VisualBasicConverter.cs @@ -1,4 +1,5 @@ -using Microsoft.CodeAnalysis.CSharp; +using ICSharpCode.CodeConverter.CSharp.ByRefArguments; +using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Editing; using ICSharpCode.CodeConverter.CSharp.OnError; @@ -8,7 +9,8 @@ internal static class VisualBasicConverter { public static async Task ConvertCompilationTreeAsync(Document document, CSharpCompilation csharpViewOfVbSymbols, Project csharpReferenceProject, - OptionalOperations optionalOperations, ILookup typeToInheritors, ErrUsage errUsage, CancellationToken cancellationToken) + OptionalOperations optionalOperations, ILookup typeToInheritors, IFieldMutationOracle fieldMutations, ErrUsage errUsage, + CancellationToken cancellationToken) { document = await document.WithExpandedRootAsync(cancellationToken); var root = await document.GetSyntaxRootAsync(cancellationToken) as VBSyntax.CompilationUnitSyntax ?? @@ -21,7 +23,7 @@ public static async Task ConvertCompilationTreeAsync(Document docume var csSyntaxGenerator = SyntaxGenerator.GetGenerator(csharpReferenceProject); var semanticModel = compilation.GetSemanticModel(tree, true); var visualBasicSyntaxVisitor = new - DeclarationNodeVisitor(document, compilation, semanticModel, csharpViewOfVbSymbols, csSyntaxGenerator, typeToInheritors, errUsage); + DeclarationNodeVisitor(document, compilation, semanticModel, csharpViewOfVbSymbols, csSyntaxGenerator, typeToInheritors, fieldMutations, errUsage); var converted = await root.AcceptAsync(visualBasicSyntaxVisitor.TriviaConvertingDeclarationVisitor); return optionalOperations.MapSourceTriviaToTargetHandled(root, converted, document); diff --git a/Tests/CSharp/ExpressionTests/ByRefTests.cs b/Tests/CSharp/ExpressionTests/ByRefTests.cs index d1437fa1c..f6cd5ce67 100644 --- a/Tests/CSharp/ExpressionTests/ByRefTests.cs +++ b/Tests/CSharp/ExpressionTests/ByRefTests.cs @@ -896,10 +896,9 @@ public static void Main() LogAndReset(ref argarg); wide = argarg; object[] wideArray = new object[] { 3, 4, 4 }; - var tmp = wideArray; - int argarg1 = Conversions.ToInteger(tmp[1]); + int argarg1 = Conversions.ToInteger(wideArray[1]); LogAndReset(ref argarg1); - tmp[1] = argarg1; + wideArray[1] = argarg1; short narrow = 3; int argarg2 = narrow; LogAndReset(ref argarg2); @@ -1426,7 +1425,7 @@ public void Assignments(C h) } [Fact] - public async Task StructureKeepsStatementPlacementWhereALocalFunctionWouldNeedThisAsync() + public async Task StructureBlockHeaderDeclaratorAndCompoundAssignmentPassThisToTheLocalFunctionAsync() { await TestConversionVisualBasicToCSharpAsync(@"Public Structure S Public Property P As Integer @@ -1458,29 +1457,29 @@ public static int Inc(ref int v) public void M() { - int argv = P; - switch (Inc(ref argv)) + int localInc(ref S self) { int argv = self.P; var ret = Inc(ref argv); self.P = argv; return ret; } + + switch (localInc(ref this)) { case 1: Console.WriteLine(1); break; } - P = argv; - int argv1 = P; - int argv2 = P; - int a = Inc(ref argv1); - int b = Inc(ref argv2); - P = argv1; - P = argv2; - int argv3 = P; - P += Inc(ref argv3); - P = argv3; + int localInc1(ref S self) { int argv1 = self.P; var ret = Inc(ref argv1); self.P = argv1; return ret; } + + int localInc2(ref S self) { int argv2 = self.P; var ret = Inc(ref argv2); self.P = argv2; return ret; } + + int a = localInc1(ref this); + int b = localInc2(ref this); + int localInc3(ref S self) { int argv3 = self.P; var ret = Inc(ref argv3); self.P = argv3; return ret; } + + P += localInc3(ref this); } -}", incompatibleWithAutomatedCommentTesting: true); // The write-back after the block moves line comments out of order +}"); } [Fact] - public async Task StructureKeepsStatementPlacementForOperandsThatWouldNeedThisAsync() + public async Task StructureOperandsPassThisToTheLocalFunctionAsync() { await TestConversionVisualBasicToCSharpAsync(@"Public Structure S Public Property P As Integer @@ -1508,18 +1507,16 @@ public static int Inc(ref int v) public void M() { - int argv = P; - var ret = Inc(ref argv) + 1; - P = argv; - P = ret; - int argv1 = P; - int x = 1 + Inc(ref argv1); - P = argv1; - int argv2 = P; - int argv3 = Inc(ref argv2); - var ret1 = Inc(ref argv3); - P = argv2; - P = ret1; + int localInc(ref S self) { int argv = self.P; var ret = Inc(ref argv); self.P = argv; return ret; } + + P = localInc(ref this) + 1; + int localInc1(ref S self) { int argv1 = self.P; var ret = Inc(ref argv1); self.P = argv1; return ret; } + + int x = 1 + localInc1(ref this); + int localInc2(ref S self) { int argv2 = self.P; var ret = Inc(ref argv2); self.P = argv2; return ret; } + + int argv = localInc2(ref this); + P = Inc(ref argv); } }"); } @@ -1557,4 +1554,1724 @@ public void M(object o) } }", incompatibleWithAutomatedCommentTesting: true); // The late-bound assignment is emitted on the local function's line } + [Fact] + public async Task StructureConditionsPassThisToTheLocalFunctionAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Public Structure S + Public Shared Counter As Integer + Public Property P As Integer + Private F As Integer + + Shared Function Inc(ByRef v As Integer) As Integer + v += 1 + Return v + End Function + + Function InstanceInc(ByRef v As Integer) As Integer + v += F + Return v + End Function + + Sub New(start As Integer) + F = start + If Inc(P) > F Then P = 0 + End Sub + + ReadOnly Property Incremented As Integer + Get + If Inc(P) > 0 Then Return P + Return 0 + End Get + End Property + + Sub M(b As Boolean, self As Integer) + If b AndAlso Inc(P) > self Then + P = 0 + ElseIf InstanceInc(Me.P) > Inc(Inc(P)) Then + P = 1 + End If + While Inc(P) < 10 + End While + Do + Loop Until InstanceInc(P) > 20 + If Inc(Counter) > 0 Then Counter = 0 + End Sub +End Structure", @" +public partial struct S +{ + public static int Counter; + public int P { get; set; } + private int F; + + public static int Inc(ref int v) + { + v += 1; + return v; + } + + public int InstanceInc(ref int v) + { + v += F; + return v; + } + + public S(int start) + { + F = start; + int localInc(ref S self) { int argv = self.P; var ret = Inc(ref argv); self.P = argv; return ret; } + + if (localInc(ref this) > F) + P = 0; + } + + public int Incremented + { + get + { + int localInc(ref S self) { int argv1 = self.P; var ret = Inc(ref argv1); self.P = argv1; return ret; } + + if (localInc(ref this) > 0) + return P; + return 0; + } + } + + public void M(bool b, int self) + { + int localInc(ref S self1) { int argv2 = self1.P; var ret = Inc(ref argv2); self1.P = argv2; return ret; } + int localInstanceInc(ref S self1) { int argv3 = self1.P; var ret = self1.InstanceInc(ref argv3); self1.P = argv3; return ret; } + + int localInc1(ref S self1) { int argv4 = self1.P; var ret = Inc(ref argv4); self1.P = argv4; return ret; } + + int localInc2(ref S self1) { int argv5 = localInc1(ref self1); var ret = Inc(ref argv5); return ret; } + + if (b && localInc(ref this) > self) + { + P = 0; + } + else if (localInstanceInc(ref this) > localInc2(ref this)) + { + P = 1; + } + int localInc3(ref S self1) { int argv6 = self1.P; var ret = Inc(ref argv6); self1.P = argv6; return ret; } + + while (localInc3(ref this) < 10) + { + } + int localInstanceInc1(ref S self1) { int argv7 = self1.P; var ret = self1.InstanceInc(ref argv7); self1.P = argv7; return ret; } + + do + { + } + while (localInstanceInc1(ref this) <= 20); + if (Inc(ref Counter) > 0) + Counter = 0; + } +}"); + } + [Fact] + public async Task StructureWithBlockOnALocalDoesNotPassThisAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Public Class Box + Public Property X As Integer +End Class + +Public Structure S + Shared Function Inc(ByRef v As Integer) As Integer + v += 1 + Return v + End Function + + Sub M() + Dim b As New Box + With b + If Inc(.X) > 0 Then .X = 0 + End With + End Sub +End Structure", @" +public partial class Box +{ + public int X { get; set; } +} + +public partial struct S +{ + public static int Inc(ref int v) + { + v += 1; + return v; + } + + public void M() + { + var b = new Box(); + int localInc() { int argv = b.X; var ret = Inc(ref argv); b.X = argv; return ret; } + + if (localInc() > 0) + b.X = 0; + } +}"); + } + [Fact] + public async Task StructureWithMePassesThisToTheLocalFunctionAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Public Structure S + Public Property P As Integer + + Shared Function Inc(ByRef v As Integer) As Integer + v += 1 + Return v + End Function + + Sub M() + With Me + If Inc(.P) > 0 Then .P = 0 + End With + End Sub +End Structure", @" +public partial struct S +{ + public int P { get; set; } + + public static int Inc(ref int v) + { + v += 1; + return v; + } + + public void M() + { + int localInc(ref S self) { int argv = self.P; var ret = Inc(ref argv); self.P = argv; return ret; } + + if (localInc(ref this) > 0) + P = 0; + } +}"); + } + [Fact] + public async Task RefLocalDeclaredInsideTheLocalFunctionIsNotPassedAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Public Structure T + Public Property P As Integer +End Structure + +Public Class C + Public Property Total As Integer + Public Inner As T + + Shared Function Apply(ByRef v As Integer, f As System.Func(Of Integer)) As Integer + Return v + f() + End Function + + Sub M() + If Apply(Total, Function() + With Inner + .P = 3 + End With + Return 1 + End Function) > 0 Then Total = 0 + End Sub +End Class", @"using System; + +public partial struct T +{ + public int P { get; set; } +} + +public partial class C +{ + public int Total { get; set; } + public T Inner; + + public static int Apply(ref int v, Func f) + { + return v + f(); + } + + public void M() + { + int localApply() + { + int argv = Total; + var ret = Apply(ref argv, () => + { + { + ref var withBlock = ref Inner; + withBlock.P = 3; + } + return 1; + }); + Total = argv; + return ret; + } + + if (localApply() > 0) + Total = 0; + } +}", incompatibleWithAutomatedCommentTesting: true); // The multi-line lambda is emitted inside the local function, before the If's line + } + [Fact] + public async Task WithByRefParameterIsPassedToTheLocalFunctionAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Public Structure T + Public Property P As Integer +End Structure + +Public Class Box + Public Property X As Integer +End Class + +Public Class C + Shared Function Inc(ByRef v As Integer) As Integer + v += 1 + Return v + End Function + + Sub M(ByRef b As Box, ByRef p As T) + With b + If Inc(.X) > 0 Then .X = 0 + End With + With p + If Inc(.P) > 0 Then .P = 0 + End With + End Sub +End Class", @" +public partial struct T +{ + public int P { get; set; } +} + +public partial class Box +{ + public int X { get; set; } +} + +public partial class C +{ + public static int Inc(ref int v) + { + v += 1; + return v; + } + + public void M(ref Box b, ref T p) + { + int localInc(ref Box b) { int argv = b.X; var ret = Inc(ref argv); b.X = argv; return ret; } + + if (localInc(ref b) > 0) + b.X = 0; + int localInc1(ref T p) { int argv1 = p.P; var ret = Inc(ref argv1); p.P = argv1; return ret; } + + if (localInc1(ref p) > 0) + p.P = 0; + } +}"); + } + [Fact] + public async Task ByRefParameterOnlyInAWithHeaderIsNotPassedAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Public Class Box + Public Property X As Integer +End Class + +Public Class C + Shared Function Inc(ByRef v As Integer) As Integer + v += 1 + Return v + End Function + + Shared Function GetBox(ByRef b As Box) As Box + Return b + End Function + + Sub M(ByRef arr As Box(), i As Integer, ByRef b As Box) + With arr(i) + If Inc(.X) > 0 Then .X = 0 + End With + With GetBox(b) + If Inc(.X) > 0 Then .X = 0 + End With + End Sub +End Class", @" +public partial class Box +{ + public int X { get; set; } +} + +public partial class C +{ + public static int Inc(ref int v) + { + v += 1; + return v; + } + + public static Box GetBox(ref Box b) + { + return b; + } + + public void M(ref Box[] arr, int i, ref Box b) + { + { + var withBlock = arr[i]; + int localInc() { int argv = withBlock.X; var ret = Inc(ref argv); withBlock.X = argv; return ret; } + + if (localInc() > 0) + withBlock.X = 0; + } + { + var withBlock1 = GetBox(ref b); + int localInc1() { int argv1 = withBlock1.X; var ret = Inc(ref argv1); withBlock1.X = argv1; return ret; } + + if (localInc1() > 0) + withBlock1.X = 0; + } + } +}"); + } + [Fact] + public async Task StructureSharedMemberDoesNotPassThisAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Public Structure S + Public Shared Property Total As Integer + + Shared Function Inc(ByRef v As Integer) As Integer + v += 1 + Return v + End Function + + Shared Function M() As Boolean + If Inc(Total) > 0 Then Return Total = 1 + Return False + End Function +End Structure", @" +public partial struct S +{ + public static int Total { get; set; } + + public static int Inc(ref int v) + { + v += 1; + return v; + } + + public static bool M() + { + int localInc() { int argv = Total; var ret = Inc(ref argv); Total = argv; return ret; } + + if (localInc() > 0) + return Total == 1; + return false; + } +}"); + } + [Fact] + public async Task KeywordNamedByRefParametersArePassedToTheLocalFunctionAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Public Class Box + Public Property P As Integer +End Class + +Public Class C + Shared Function Inc(ByRef v As Integer) As Integer + v += 1 + Return v + End Function + + Shared Function M(ByRef [class] As Box, ByRef params As Box, ByRef [string] As Box) As Boolean + If Inc([class].P) + Inc(params.P) + Inc([string].P) > 0 Then Return True + Return False + End Function +End Class", @" +public partial class Box +{ + public int P { get; set; } +} + +public partial class C +{ + public static int Inc(ref int v) + { + v += 1; + return v; + } + + public static bool M(ref Box @class, ref Box @params, ref Box @string) + { + int localInc(ref Box @class) { var tmp = @class; int argv = tmp.P; var ret = Inc(ref argv); tmp.P = argv; return ret; } + + int localInc1(ref Box @params) { var tmp1 = @params; int argv1 = tmp1.P; var ret = Inc(ref argv1); tmp1.P = argv1; return ret; } + + int localInc2(ref Box @string) { var tmp2 = @string; int argv2 = tmp2.P; var ret = Inc(ref argv2); tmp2.P = argv2; return ret; } + + if (localInc(ref @class) + localInc1(ref @params) + localInc2(ref @string) > 0) + return true; + return false; + } +}"); + } + + [Fact] + public async Task AnonymousTypeMemberNamedLikeAByRefParameterIsNotPassedAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Public Class Box + Public Property P As Integer + Public Property Inner As Box +End Class + +Public Class C + Shared Function Inc(ByRef v As Integer) As Integer + v += 1 + Return v + End Function + + Shared Function Take(o As Object, b As Box) As Box + Return b + End Function + + Sub M(arr As Box(), ByRef i As Integer) + With arr(i) + If Inc(Take(New With {.i = 1}, .Inner).P) > 0 Then .P = 0 + End With + End Sub +End Class", @" +public partial class Box +{ + public int P { get; set; } + public Box Inner { get; set; } +} + +public partial class C +{ + public static int Inc(ref int v) + { + v += 1; + return v; + } + + public static Box Take(object o, Box b) + { + return b; + } + + public void M(Box[] arr, ref int i) + { + { + var withBlock = arr[i]; + int localInc() { var tmp = Take(new { i = 1 }, withBlock.Inner); int argv = tmp.P; var ret = Inc(ref argv); tmp.P = argv; return ret; } + + if (localInc() > 0) + withBlock.P = 0; + } + } +}"); + } + + [Fact] + public async Task ObjectInitializerMemberNamedLikeAByRefParameterIsNotPassedAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Public Class Box + Public Property P As Integer + Public i As Integer + Public Property Inner As Box +End Class + +Public Class C + Shared Function Inc(ByRef v As Integer) As Integer + v += 1 + Return v + End Function + + Shared Function Take(o As Object, b As Box) As Box + Return b + End Function + + Sub M(arr As Box(), ByRef i As Integer) + With arr(i) + If Inc(Take(New Box With {.i = 1}, .Inner).P) > 0 Then .P = 0 + End With + End Sub +End Class", @" +public partial class Box +{ + public int P { get; set; } + public int i; + public Box Inner { get; set; } +} + +public partial class C +{ + public static int Inc(ref int v) + { + v += 1; + return v; + } + + public static Box Take(object o, Box b) + { + return b; + } + + public void M(Box[] arr, ref int i) + { + { + var withBlock = arr[i]; + int localInc() { var tmp = Take(new Box() { i = 1 }, withBlock.Inner); int argv = tmp.P; var ret = Inc(ref argv); tmp.P = argv; return ret; } + + if (localInc() > 0) + withBlock.P = 0; + } + } +}"); + } + + [Fact] + public async Task TypeNamedLikeAByRefParameterIsNotPassedAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Public Class H + Public Shared Property S As Integer + Public Property Q As Integer +End Class + +Public Class C + Shared Function Inc(ByRef v As Integer) As Integer + v += 1 + Return v + End Function + + Shared Function GetH(q As Integer) As H + Return New H + End Function + + Shared Function M( ByRef h As H) As Boolean + If Inc(H.S) > 0 Then + h = New H + Return True + End If + h = Nothing + Return False + End Function + + Shared Function M2(ByRef h As Integer, x As H) As Boolean + If Inc(GetH(New H().Q).Q) > 0 Then Return True + Return False + End Function +End Class", @" +public partial class H +{ + public static int S { get; set; } + public int Q { get; set; } +} + +public partial class C +{ + public static int Inc(ref int v) + { + v += 1; + return v; + } + + public static H GetH(int q) + { + return new H(); + } + + public static bool M(out H h) + { + int localInc() { int argv = H.S; var ret = Inc(ref argv); H.S = argv; return ret; } + + if (localInc() > 0) + { + h = new H(); + return true; + } + h = null; + return false; + } + + public static bool M2(ref int h, H x) + { + int localInc() { var tmp = GetH(new H().Q); int argv1 = tmp.Q; var ret = Inc(ref argv1); tmp.Q = argv1; return ret; } + + if (localInc() > 0) + return true; + return false; + } +}"); + } + [Fact] + public async Task WithBlockRefLocalIsPassedToTheLocalFunctionAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Public Structure T + Public Property P As Integer +End Structure + +Public Class C + Public Inner As T + + Sub M() + With Inner + If S.Inc(.P) > 0 Then .P = 0 + End With + End Sub +End Class + +Public Structure S + Public Inner As T + + Shared Function Inc(ByRef v As Integer) As Integer + v += 1 + Return v + End Function + + Sub M() + With Inner + If Inc(.P) > 0 Then .P = 0 + End With + End Sub +End Structure", @" +public partial struct T +{ + public int P { get; set; } +} + +public partial class C +{ + public T Inner; + + public void M() + { + { + ref var withBlock = ref Inner; + int localInc(ref T withBlock) { int argv = withBlock.P; var ret = S.Inc(ref argv); withBlock.P = argv; return ret; } + + if (localInc(ref withBlock) > 0) + withBlock.P = 0; + } + } +} + +public partial struct S +{ + public T Inner; + + public static int Inc(ref int v) + { + v += 1; + return v; + } + + public void M() + { + { + ref var withBlock = ref Inner; + int localInc(ref T withBlock) { int argv1 = withBlock.P; var ret = Inc(ref argv1); withBlock.P = argv1; return ret; } + + if (localInc(ref withBlock) > 0) + withBlock.P = 0; + } + } +}"); + } + [Fact] + public async Task StructureMePassedByRefAfterAWriteBackTakesTheLocalFunctionAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Public Structure S + Public Property P As Integer + + Shared Function Inc(ByRef v As Integer) As Integer + v += 1 + Return v + End Function + + Shared Function ValueOf(ByRef s As S) As Integer + Return s.P + End Function + + Function M() As Integer + Return Inc(P) + ValueOf(Me) + End Function +End Structure", @" +public partial struct S +{ + public int P { get; set; } + + public static int Inc(ref int v) + { + v += 1; + return v; + } + + public static int ValueOf(ref S s) + { + return s.P; + } + + public int M() + { + int localInc(ref S self) { int argv = self.P; var ret = Inc(ref argv); self.P = argv; return ret; } + + int localValueOf(ref S self) { var args = self; var ret = ValueOf(ref args); return ret; } + + return localInc(ref this) + localValueOf(ref this); + } +}"); + } + + [Fact] + public async Task ParameterizedPropertyIsWrittenBackThroughItsSetterIssue909Async() + { + await TestConversionVisualBasicToCSharpAsync(@"Public Class ClsDb + Private ReadOnly _recordValues(10, 30) As String + + Public Sub Get_Equal(ByRef tableBuffer As Integer, ByRef keyIndex As Integer, ByRef keyValue As String, ByRef recordPosition As String, ByRef errorNumber As Integer) + keyValue = ""found"" + End Sub + + Public Property Qr(ByVal tableBuffer As Integer, ByVal fieldNumber As Integer) As String + Get + Return _recordValues(tableBuffer, fieldNumber) + End Get + Set(ByVal value As String) + _recordValues(tableBuffer, fieldNumber) = value + End Set + End Property +End Class + +Module Euro_Str + Public Db As New ClsDb + Public QAdr As Integer + Public CourseBuffer As Integer +End Module + +Public Class Caller + Sub Find(recordPositionQAdr As String, errorCode As Integer) + Db.Get_Equal(QAdr, 0, Db.Qr(CourseBuffer, 21), recordPositionQAdr, errorCode) + End Sub +End Class", @" +public partial class ClsDb +{ + private readonly string[,] _recordValues = new string[11, 31]; + + public void Get_Equal(ref int tableBuffer, ref int keyIndex, ref string keyValue, ref string recordPosition, ref int errorNumber) + { + keyValue = ""found""; + } + + public string get_Qr(int tableBuffer, int fieldNumber) + { + return _recordValues[tableBuffer, fieldNumber]; + } + public void set_Qr(int tableBuffer, int fieldNumber, string value) + { + _recordValues[tableBuffer, fieldNumber] = value; + } +} + +internal static partial class Euro_Str +{ + public static ClsDb Db = new ClsDb(); + public static int QAdr; + public static int CourseBuffer; +} + +public partial class Caller +{ + public void Find(string recordPositionQAdr, int errorCode) + { + int argkeyIndex = 0; + string argkeyValue = Euro_Str.Db.get_Qr(Euro_Str.CourseBuffer, 21); + Euro_Str.Db.Get_Equal(ref Euro_Str.QAdr, ref argkeyIndex, ref argkeyValue, ref recordPositionQAdr, ref errorCode); + Euro_Str.Db.set_Qr(Euro_Str.CourseBuffer, 21, argkeyValue); + } +}"); + } + + [Fact] + public async Task ByRefPropertyTargetEvaluatesReceiverAndIndexesOnceAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Public Class C + Private _index As Integer + + Public Property Qr(a As Integer, b As Integer) As String + Get + Return """" + End Get + Set(value As String) + End Set + End Property + + Default Public Property Item(i As Integer) As String + Get + Return """" + End Get + Set(value As String) + End Set + End Property + + Public Property Plain As String + + Function NextIndex() As Integer + Return 1 + End Function + + Function GetC() As C + Return Me + End Function + + Shared Sub SetValue(ByRef value As String) + End Sub + + Shared Sub SetValueAndIndex(ByRef value As String, ByRef index As Integer) + End Sub + + Sub UsesTwice(other As C) + Dim i = 1 + SetValue(Qr((i), 2)) ' Locals, constants and fields are evaluated again + SetValue(other.Qr(_index, NextIndex())) + SetValue(GetC().Qr(1, 2)) + SetValue(GetC().Plain) + SetValue(other(NextIndex())) + SetValueAndIndex(other.Qr(i, 2), i) ' i is written by the call + End Sub +End Class", @" +public partial class C +{ + private int _index; + + public string get_Qr(int a, int b) + { + return """"; + } + public void set_Qr(int a, int b, string value) + { + } + + public string this[int i] + { + get + { + return """"; + } + set + { + } + } + + public string Plain { get; set; } + + public int NextIndex() + { + return 1; + } + + public C GetC() + { + return this; + } + + public static void SetValue(ref string value) + { + } + + public static void SetValueAndIndex(ref string value, ref int index) + { + } + + public void UsesTwice(C other) + { + int i = 1; + string argvalue = get_Qr(i, 2); + SetValue(ref argvalue); + set_Qr(i, 2, argvalue); // Locals, constants and fields are evaluated again + var tmp = NextIndex(); + string argvalue1 = other.get_Qr(_index, tmp); + SetValue(ref argvalue1); + other.set_Qr(_index, tmp, argvalue1); + var tmp1 = GetC(); + string argvalue2 = tmp1.get_Qr(1, 2); + SetValue(ref argvalue2); + tmp1.set_Qr(1, 2, argvalue2); + var tmp2 = GetC(); + string argvalue3 = tmp2.Plain; + SetValue(ref argvalue3); + tmp2.Plain = argvalue3; + var tmp3 = NextIndex(); + string argvalue4 = other[tmp3]; + SetValue(ref argvalue4); + other[tmp3] = argvalue4; + var tmp4 = i; + string argvalue5 = other.get_Qr(tmp4, 2); + SetValueAndIndex(ref argvalue5, ref i); + other.set_Qr(tmp4, 2, argvalue5); // i is written by the call + } +}"); + } + + [Fact] + public async Task ByRefPropertyTargetCopiesOnlyFieldsThatCanChangeAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Public Class Db + Public Property Qr(a As Integer, b As Integer) As String + Get + Return """" + End Get + Set(value As String) + End Set + End Property +End Class + +Public Class Fields + Private ReadOnly _readOnlyIndex As Integer = 1 + Private _neverWritten As Integer + Private _assignedInConstructor As Integer + Private _writtenElsewhere As Integer + Public PublicIndex As Integer + Private _db As New Db + + Public Sub New() + _assignedInConstructor = 2 + End Sub + + Sub Reset() + _writtenElsewhere = 0 + End Sub + + Sub UsesFields() + SetValue(_db.Qr(_readOnlyIndex, _neverWritten)) + SetValue(_db.Qr(_assignedInConstructor, _writtenElsewhere)) + SetValue(_db.Qr(PublicIndex, 1)) + End Sub + + Shared Sub SetValue(ByRef value As String) + End Sub +End Class", @" +public partial class Db +{ + public string get_Qr(int a, int b) + { + return """"; + } + public void set_Qr(int a, int b, string value) + { + } +} + +public partial class Fields +{ + private readonly int _readOnlyIndex = 1; + private int _neverWritten; + private int _assignedInConstructor; + private int _writtenElsewhere; + public int PublicIndex; + private Db _db = new Db(); + + public Fields() + { + _assignedInConstructor = 2; + } + + public void Reset() + { + _writtenElsewhere = 0; + } + + public void UsesFields() + { + string argvalue = _db.get_Qr(_readOnlyIndex, _neverWritten); + SetValue(ref argvalue); + _db.set_Qr(_readOnlyIndex, _neverWritten, argvalue); + var tmp = _writtenElsewhere; + string argvalue1 = _db.get_Qr(_assignedInConstructor, tmp); + SetValue(ref argvalue1); + _db.set_Qr(_assignedInConstructor, tmp, argvalue1); + var tmp1 = PublicIndex; + string argvalue2 = _db.get_Qr(tmp1, 1); + SetValue(ref argvalue2); + _db.set_Qr(tmp1, 1, argvalue2); + } + + public static void SetValue(ref string value) + { + } +}"); + } + + [Fact] + public async Task ByRefPropertyTargetCopiesFieldsWrittenAfterConstructionAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Option Strict Off + +Public Class Db + Public Property Qr(a As Object) As String + Get + Return """" + End Get + Set(value As String) + End Set + End Property +End Class + +Public Structure Point + Public X As Integer +End Structure + +Public Class C + Private _forVar As Integer + Private _forEachVar As Integer + Private _reDimmed As Integer() + Private _erased As Integer() + Private _midText As String + Private _lateBoundArg As Integer + Private _writtenInConstructorLambda As Integer + Private _writtenOnOtherInstance As Integer + Private Shared _sharedWrittenInInstanceConstructor As Integer + Private _byInitializer As Integer + Private _initialized As Integer = Inc(_byInitializer) + Private Shared _sharedByInitializer As Integer + Private Shared _sharedInitialized As Integer = Inc(_sharedByInitializer) + Private Shared _sharedInSharedConstructor As Integer + Friend _friendNeverWritten As Integer + Private _point As Point + Private ReadOnly _db As New Db + + Shared Sub New() + _sharedInSharedConstructor = 1 + End Sub + + Public Sub New(other As C) + Dim a As Action = Sub() _writtenInConstructorLambda = 1 + other._writtenOnOtherInstance = 1 + _sharedWrittenInInstanceConstructor = 1 + End Sub + + Sub Writes(o As Object) + For _forVar = 1 To 2 + Next + For Each _forEachVar In {1} + Next + ReDim _reDimmed(3) + Erase _erased + Mid(_midText, 1) = ""x"" + o.Foo(_lateBoundArg) + End Sub + + Sub UsesFields() + SetValue(_db.Qr(_forVar)) + SetValue(_db.Qr(_forEachVar)) + SetValue(_db.Qr(_reDimmed)) + SetValue(_db.Qr(_erased)) + SetValue(_db.Qr(_midText)) + SetValue(_db.Qr(_lateBoundArg)) + SetValue(_db.Qr(_writtenInConstructorLambda)) + SetValue(_db.Qr(_writtenOnOtherInstance)) + SetValue(_db.Qr(_sharedWrittenInInstanceConstructor)) + SetValue(_db.Qr(_byInitializer)) ' Reused from here on + SetValue(_db.Qr(_sharedByInitializer)) + SetValue(_db.Qr(_sharedInSharedConstructor)) + SetValue(_db.Qr(_friendNeverWritten)) + SetValue(_db.Qr(_point)) ' A structure can change without being assigned + End Sub + + Shared Function Inc(ByRef x As Integer) As Integer + x += 1 + Return x + End Function + + Shared Sub SetValue(ByRef value As String) + End Sub +End Class", @"using System; +using Microsoft.VisualBasic.CompilerServices; // Install-Package Microsoft.VisualBasic + +public partial class Db +{ + public string get_Qr(object a) + { + return """"; + } + public void set_Qr(object a, string value) + { + } +} + +public partial struct Point +{ + public int X; +} + +public partial class C +{ + private int _forVar; + private int _forEachVar; + private int[] _reDimmed; + private int[] _erased; + private string _midText; + private int _lateBoundArg; + private int _writtenInConstructorLambda; + private int _writtenOnOtherInstance; + private static int _sharedWrittenInInstanceConstructor; + private int _byInitializer; + private int _initialized; + private static int _sharedByInitializer; + private static int _sharedInitialized = Inc(ref _sharedByInitializer); + private static int _sharedInSharedConstructor; + internal int _friendNeverWritten; + private Point _point; + private readonly Db _db = new Db(); + + static C() + { + _sharedInSharedConstructor = 1; + } + + public C(C other) + { + _initialized = Inc(ref _byInitializer); + Action a = () => _writtenInConstructorLambda = 1; + other._writtenOnOtherInstance = 1; + _sharedWrittenInInstanceConstructor = 1; + } + + public void Writes(object o) + { + for (_forVar = 1; _forVar <= 2; _forVar++) + { + } + foreach (var current_forEachVar in new[] { 1 }) + _forEachVar = current_forEachVar; + _reDimmed = new int[4]; + _erased = null; + StringType.MidStmtStr(ref _midText, 1, ""x"".Length, ""x""); + ((dynamic)o).Foo(_lateBoundArg); + } + + public void UsesFields() + { + var tmp = _forVar; + string argvalue = _db.get_Qr(tmp); + SetValue(ref argvalue); + _db.set_Qr(tmp, argvalue); + var tmp1 = _forEachVar; + string argvalue1 = _db.get_Qr(tmp1); + SetValue(ref argvalue1); + _db.set_Qr(tmp1, argvalue1); + var tmp2 = _reDimmed; + string argvalue2 = _db.get_Qr(tmp2); + SetValue(ref argvalue2); + _db.set_Qr(tmp2, argvalue2); + var tmp3 = _erased; + string argvalue3 = _db.get_Qr(tmp3); + SetValue(ref argvalue3); + _db.set_Qr(tmp3, argvalue3); + var tmp4 = _midText; + string argvalue4 = _db.get_Qr(tmp4); + SetValue(ref argvalue4); + _db.set_Qr(tmp4, argvalue4); + var tmp5 = _lateBoundArg; + string argvalue5 = _db.get_Qr(tmp5); + SetValue(ref argvalue5); + _db.set_Qr(tmp5, argvalue5); + var tmp6 = _writtenInConstructorLambda; + string argvalue6 = _db.get_Qr(tmp6); + SetValue(ref argvalue6); + _db.set_Qr(tmp6, argvalue6); + var tmp7 = _writtenOnOtherInstance; + string argvalue7 = _db.get_Qr(tmp7); + SetValue(ref argvalue7); + _db.set_Qr(tmp7, argvalue7); + var tmp8 = _sharedWrittenInInstanceConstructor; + string argvalue8 = _db.get_Qr(tmp8); + SetValue(ref argvalue8); + _db.set_Qr(tmp8, argvalue8); + string argvalue9 = _db.get_Qr(_byInitializer); + SetValue(ref argvalue9); + _db.set_Qr(_byInitializer, argvalue9); // Reused from here on + string argvalue10 = _db.get_Qr(_sharedByInitializer); + SetValue(ref argvalue10); + _db.set_Qr(_sharedByInitializer, argvalue10); + string argvalue11 = _db.get_Qr(_sharedInSharedConstructor); + SetValue(ref argvalue11); + _db.set_Qr(_sharedInSharedConstructor, argvalue11); + string argvalue12 = _db.get_Qr(_friendNeverWritten); + SetValue(ref argvalue12); + _db.set_Qr(_friendNeverWritten, argvalue12); + var tmp9 = _point; + string argvalue13 = _db.get_Qr(tmp9); + SetValue(ref argvalue13); + _db.set_Qr(tmp9, argvalue13); // A structure can change without being assigned + } + + public static int Inc(ref int x) + { + x += 1; + return x; + } + + public static void SetValue(ref string value) + { + } +}"); + } + + [Fact] + public async Task ByRefPropertyTargetCopiesFriendFieldsVisibleToFriendAssembliesAsync() + { + await TestConversionVisualBasicToCSharpAsync(@" + +Public Class Db + Public Property Qr(a As Integer) As String + Get + Return """" + End Get + Set(value As String) + End Set + End Property +End Class + +Public Class C + Friend _friendNeverWritten As Integer + Private _privateNeverWritten As Integer + Private Shared _sharedWrittenByAnotherTypesConstructor As Integer + Private ReadOnly _db As New Db + + Private Class Other + Sub New() + C._sharedWrittenByAnotherTypesConstructor = 1 + End Sub + End Class + + Sub UsesFields() + SetValue(_db.Qr(_friendNeverWritten)) + SetValue(_db.Qr(_privateNeverWritten)) + SetValue(_db.Qr(_sharedWrittenByAnotherTypesConstructor)) + End Sub + + Shared Sub SetValue(ByRef value As String) + End Sub +End Class", @"using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo(""Other"")] + +public partial class Db +{ + public string get_Qr(int a) + { + return """"; + } + public void set_Qr(int a, string value) + { + } +} + +public partial class C +{ + internal int _friendNeverWritten; + private int _privateNeverWritten; + private static int _sharedWrittenByAnotherTypesConstructor; + private readonly Db _db = new Db(); + + private partial class Other + { + public Other() + { + _sharedWrittenByAnotherTypesConstructor = 1; + } + } + + public void UsesFields() + { + var tmp = _friendNeverWritten; + string argvalue = _db.get_Qr(tmp); + SetValue(ref argvalue); + _db.set_Qr(tmp, argvalue); + string argvalue1 = _db.get_Qr(_privateNeverWritten); + SetValue(ref argvalue1); + _db.set_Qr(_privateNeverWritten, argvalue1); + var tmp1 = _sharedWrittenByAnotherTypesConstructor; + string argvalue2 = _db.get_Qr(tmp1); + SetValue(ref argvalue2); + _db.set_Qr(tmp1, argvalue2); + } + + public static void SetValue(ref string value) + { + } +}"); + } + + [Fact] + public async Task ByRefPropertyTargetReusesIntrinsicOperatorsOnReusableOperandsAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Option Strict Off + +Public Structure Money + Public Shared Operator +(a As Money, b As Money) As Integer + Return 0 + End Operator +End Structure + +Public Class C + Public Property Qr(a As Integer, b As Integer) As String + Get + Return """" + End Get + Set(value As String) + End Set + End Property + + Sub UsesOperators(i As Integer, o As Object, m As Money) + SetValue(Qr(i + 1, -i)) + SetValue(Qr(o + 1, 2)) + SetValue(Qr(m + m, 2)) + End Sub + + Shared Sub SetValue(ByRef value As String) + End Sub +End Class", @"using Microsoft.VisualBasic.CompilerServices; // Install-Package Microsoft.VisualBasic + +public partial struct Money +{ + public static int operator +(Money a, Money b) + { + return 0; + } +} + +public partial class C +{ + public string get_Qr(int a, int b) + { + return """"; + } + public void set_Qr(int a, int b, string value) + { + } + + public void UsesOperators(int i, object o, Money m) + { + string argvalue = get_Qr(i + 1, -i); + SetValue(ref argvalue); + set_Qr(i + 1, -i, argvalue); + var tmp = Conversions.ToInteger(Operators.AddObject(o, 1)); + string argvalue1 = get_Qr(tmp, 2); + SetValue(ref argvalue1); + set_Qr(tmp, 2, argvalue1); + var tmp1 = m + m; + string argvalue2 = get_Qr(tmp1, 2); + SetValue(ref argvalue2); + set_Qr(tmp1, 2, argvalue2); + } + + public static void SetValue(ref string value) + { + } +}", incompatibleWithAutomatedCommentTesting: true); // The comment on Option Strict Off is lost before the added using directive + } + + [Fact] + public async Task ModuleParameterizedPropertyIsWrittenBackThroughItsSetterAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Module M + Private ReadOnly _values As New System.Collections.Generic.Dictionary(Of Integer, String) + + Property Qr(i As Integer) As String + Get + Return _values(i) + End Get + Set(value As String) + _values(i) = value + End Set + End Property + + Sub UsesQr() + SetValue(Qr(1)) + End Sub + + Sub SetValue(ByRef value As String) + End Sub +End Module", @"using System.Collections.Generic; + +internal static partial class M +{ + private readonly static Dictionary _values = new Dictionary(); + + public static string get_Qr(int i) + { + return _values[i]; + } + public static void set_Qr(int i, string value) + { + _values[i] = value; + } + + public static void UsesQr() + { + string argvalue = get_Qr(1); + SetValue(ref argvalue); + set_Qr(1, argvalue); + } + + public static void SetValue(ref string value) + { + } +}"); + } + + [Fact] + public async Task ByRefDefaultPropertyOnMeIsWrittenBackWithoutCopyingMeAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Public Class C + Default Public Property Item(i As Integer, j As Integer) As String + Get + Return """" + End Get + Set(value As String) + End Set + End Property + + Sub M(i As Integer, values As Object()) + SetValue(Me(i, 5)) + SetValue(Me.Item(i, 6)) + SetNumber(values(i)) + End Sub + + Shared Sub SetValue(ByRef value As String) + End Sub + + Shared Sub SetNumber(ByRef value As Integer) + End Sub +End Class", @"using Microsoft.VisualBasic.CompilerServices; // Install-Package Microsoft.VisualBasic + +public partial class C +{ + public string this[int i, int j] + { + get + { + return """"; + } + set + { + } + } + + public void M(int i, object[] values) + { + string argvalue = this[i, 5]; + SetValue(ref argvalue); + this[i, 5] = argvalue; + string argvalue1 = this[i, 6]; + SetValue(ref argvalue1); + this[i, 6] = argvalue1; + int argvalue2 = Conversions.ToInteger(values[i]); + SetNumber(ref argvalue2); + values[i] = argvalue2; + } + + public static void SetValue(ref string value) + { + } + + public static void SetNumber(ref int value) + { + } +}"); + } + + [Fact] + public async Task ByRefDefaultPropertyOnMyBaseIsWrittenBackThroughBaseAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Public Class B + Default Public Property Item(i As Integer) As String + Get + Return """" + End Get + Set(value As String) + End Set + End Property +End Class + +Public Class C + Inherits B + + Sub M(i As Integer) + SetValue(MyBase.Item(i)) + End Sub + + Shared Sub SetValue(ByRef value As String) + End Sub +End Class", @" +public partial class B +{ + public string this[int i] + { + get + { + return """"; + } + set + { + } + } +} + +public partial class C : B +{ + + public void M(int i) + { + string argvalue = base[i]; + SetValue(ref argvalue); + base[i] = argvalue; + } + + public static void SetValue(ref string value) + { + } +}"); + } + + [Fact] + public async Task ParameterizedPropertyInAStructureOrWithBlockIsWrittenBackInTheLocalFunctionAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Public Structure S + Private _n As Integer + + Public Property Qr(a As Integer, b As Integer) As String + Get + Return """" + End Get + Set(value As String) + End Set + End Property + + Default Public Property Item(a As Integer) As String + Get + Return """" + End Get + Set(value As String) + End Set + End Property + + Public Function NextIndex() As Integer + _n += 1 + Return _n + End Function + + Public Sub M(i As Integer) + If SetValue(Qr(NextIndex(), 2)) Then + End If + If SetValue(Me(i)) Then + End If + End Sub + + Public Shared Sub WithByRef(ByRef s As S) + With s + If SetValue(.Qr(.NextIndex(), 2)) Then + End If + End With + End Sub + + Private Shared Function SetValue(ByRef v As String) As Boolean + v = ""changed"" + Return True + End Function +End Structure + +Public Class Holder + Public F As S + + Public Sub WithField() + With F + If SetValue(.Qr(.NextIndex(), 2)) Then + End If + End With + End Sub + + Private Shared Function SetValue(ByRef v As String) As Boolean + Return True + End Function +End Class", @" +public partial struct S +{ + private int _n; + + public string get_Qr(int a, int b) + { + return """"; + } + public void set_Qr(int a, int b, string value) + { + } + + public string this[int a] + { + get + { + return """"; + } + set + { + } + } + + public int NextIndex() + { + _n += 1; + return _n; + } + + public void M(int i) + { + bool localSetValue(ref S self) { var tmp = self.NextIndex(); string argv = self.get_Qr(tmp, 2); var ret = SetValue(ref argv); self.set_Qr(tmp, 2, argv); return ret; } + + if (localSetValue(ref this)) + { + } + bool localSetValue1(ref S self) { string argv1 = self[i]; var ret = SetValue(ref argv1); self[i] = argv1; return ret; } + + if (localSetValue1(ref this)) + { + } + } + + public static void WithByRef(ref S s) + { + bool localSetValue(ref S s) { var tmp1 = s.NextIndex(); string argv2 = s.get_Qr(tmp1, 2); var ret = SetValue(ref argv2); s.set_Qr(tmp1, 2, argv2); return ret; } + + if (localSetValue(ref s)) + { + } + } + + private static bool SetValue(ref string v) + { + v = ""changed""; + return true; + } +} + +public partial class Holder +{ + public S F; + + public void WithField() + { + { + ref var withBlock = ref F; + bool localSetValue(ref S withBlock) { var tmp2 = withBlock.NextIndex(); string argv3 = withBlock.get_Qr(tmp2, 2); var ret = SetValue(ref argv3); withBlock.set_Qr(tmp2, 2, argv3); return ret; } + + if (localSetValue(ref withBlock)) + { + } + } + } + + private static bool SetValue(ref string v) + { + return true; + } +}"); + } } \ No newline at end of file diff --git a/Tests/CSharp/StatementTests/MethodStatementTests.cs b/Tests/CSharp/StatementTests/MethodStatementTests.cs index 4c2d08d0c..ae0f2aead 100644 --- a/Tests/CSharp/StatementTests/MethodStatementTests.cs +++ b/Tests/CSharp/StatementTests/MethodStatementTests.cs @@ -1817,7 +1817,7 @@ public partial class TestClass public void TestMethod() { { - ref var withBlock = ref _Data; + var withBlock = _Data; x = withBlock.x?.Name; } } diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyInStructureTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyInStructureTests.vb new file mode 100644 index 000000000..d5c44b7a8 --- /dev/null +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyInStructureTests.vb @@ -0,0 +1,199 @@ +Imports System +Imports System.Collections.Generic +Imports Xunit + +Public Class ByRefParameterizedPropertyInStructureTests + + + Public Sub StructureParameterizedPropertyInIfConditionWritesBackBeforeTheBody() + Dim s As New SDb + Assert.Equal("index 1;get 1,2;set 1,2=changed;body changed", s.ParamPropInIf()) + End Sub + + + Public Sub StructureDefaultPropertyOnMeInIfConditionEvaluatesItsIndexOnce() + Dim s As New SDb + Assert.Equal("index 1;getd 1;setd 1=changed;body changed", s.MeDefaultInIf()) + End Sub + + + Public Sub StructureDefaultPropertyOnMeInIfConditionWritesBack() + Dim s As New SDb + Assert.Equal("getd 3;setd 3=changed;body changed", s.MeDefaultPlainInIf(3)) + End Sub + + + Public Sub StructureParameterizedPropertyOperandWritesBackBeforeTheNextOperand() + Dim s As New SDb + Assert.Equal("index 1;get 1,2;set 1,2=changed;10", s.ParamPropOperand()) + End Sub + + + Public Sub StructureWithMeParameterizedPropertyInIfConditionWritesBack() + Dim s As New SDb + Assert.Equal("index 1;get 1,2;set 1,2=changed;body changed", s.WithMeInIf()) + End Sub + + + Public Sub WithStructureFieldParameterizedPropertyInIfConditionWritesBackInPlace() + Dim h As New Holder + Assert.Equal("index 1;get 1,2;set 1,2=changed;body changed", h.WithFieldInIf()) + Assert.Equal("changed", h.S.Stored) + End Sub + + + Public Sub WithByRefStructureParameterParameterizedPropertyInIfConditionWritesBackInPlace() + Dim s As New SDb + Assert.Equal("index 1;get 1,2;set 1,2=changed;body changed", Holder.WithByRefInIf(s)) + Assert.Equal("changed", s.Stored) + End Sub + + + Public Sub WithClassLocalParameterizedPropertyInIfConditionWritesBack() + Assert.Equal("index 1;get 1,2;set 1,2=changed;body changed", Holder.WithClassInIf()) + End Sub + + + Public Sub StructureParameterizedPropertyInWhileConditionWritesBackEachTime() + Dim s As New SDb + Assert.Equal("index 1;get 1,2;set 1,2=changed;loop;index 2;get 2,2;set 2,2=changed;", s.WhileLoop()) + End Sub + + Public Class CDb + Public Log As String = "" + Public Stored As String = "orig" + Public Property Qr(a As Integer, b As Integer) As String + Get + Log &= "get " & a & "," & b & ";" + Return Stored + End Get + Set(value As String) + Log &= "set " & a & "," & b & "=" & value & ";" + Stored = value + End Set + End Property + Public Function NextIndex() As Integer + Log &= "index 1;" + Return 1 + End Function + End Class + + Public Structure SDb + Public Log As String + Public Stored As String + Private _n As Integer + + Public Property Qr(a As Integer, b As Integer) As String + Get + Log &= "get " & a & "," & b & ";" + Return Stored + End Get + Set(value As String) + Log &= "set " & a & "," & b & "=" & value & ";" + Stored = value + End Set + End Property + + Default Public Property Item(a As Integer) As String + Get + Log &= "getd " & a & ";" + Return Stored + End Get + Set(value As String) + Log &= "setd " & a & "=" & value & ";" + Stored = value + End Set + End Property + + Public Function NextIndex() As Integer + _n += 1 + Log &= "index " & _n & ";" + Return _n + End Function + + Public Function ParamPropInIf() As String + If SetValue(Qr(NextIndex(), 2)) Then + Log &= "body " & Stored + End If + Return Log + End Function + + Public Function MeDefaultInIf() As String + If SetValue(Me(NextIndex())) Then + Log &= "body " & Stored + End If + Return Log + End Function + + Public Function MeDefaultPlainInIf(i As Integer) As String + If SetValue(Me(i)) Then + Log &= "body " & Stored + End If + Return Log + End Function + + Public Function ParamPropOperand() As String + Dim r = Len(SetValueS(Qr(NextIndex(), 2))) + Len(Stored) + Return Log & (r - 4) + End Function + + Public Function WithMeInIf() As String + With Me + If SetValue(.Qr(.NextIndex(), 2)) Then + Log &= "body " & .Stored + End If + End With + Return Log + End Function + + Public Function WhileLoop() As String + While SetValue(Qr(NextIndex(), 2)) AndAlso _n < 2 + Log &= "loop;" + Stored = "orig" + End While + Return Log + End Function + End Structure + + Public Class Holder + Public S As SDb + + Public Function WithFieldInIf() As String + With S + If SetValue(.Qr(.NextIndex(), 2)) Then + .Log &= "body " & .Stored + End If + End With + Return S.Log + End Function + + Public Shared Function WithByRefInIf(ByRef s As SDb) As String + With s + If SetValue(.Qr(.NextIndex(), 2)) Then + .Log &= "body " & .Stored + End If + End With + Return s.Log + End Function + + Public Shared Function WithClassInIf() As String + Dim c As New CDb + With c + If SetValue(.Qr(.NextIndex(), 2)) Then + .Log &= "body " & .Stored + End If + End With + Return c.Log + End Function + End Class + + Private Shared Function SetValue(ByRef v As String) As Boolean + v = "changed" + Return True + End Function + + Private Shared Function SetValueS(ByRef v As String) As String + v = "changed" + Return v + End Function +End Class diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyOptionStrictOffTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyOptionStrictOffTests.vb new file mode 100644 index 000000000..0d30c5dde --- /dev/null +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyOptionStrictOffTests.vb @@ -0,0 +1,42 @@ +Option Strict Off + +Imports System.Collections.Generic +Imports Xunit + +Public Class ByRefParameterizedPropertyOptionStrictOffTests + Private ReadOnly _log As New List(Of String) + + + Public Sub ConvertedValueIsWrittenBackThroughTheSetter() + Dim table As New Table(_log) + Dim index As Object = "2" + Increment(table.Cell(index)) + Assert.Equal(11, table.Cell(2)) + Assert.Equal("get 2;set 2=11;get 2", String.Join(";", _log)) + End Sub + + Private Shared Sub Increment(ByRef value As String) + value = CStr(CInt(value) + 1) + End Sub + + Private Class Table + Private ReadOnly _log As List(Of String) + Private ReadOnly _values As New Dictionary(Of Integer, Integer) + + Public Sub New(log As List(Of String)) + _log = log + End Sub + + Public Property Cell(index As Integer) As Integer + Get + _log.Add("get " & index) + Dim value As Integer + Return If(_values.TryGetValue(index, value), value, 10) + End Get + Set(value As Integer) + _log.Add("set " & index & "=" & value) + _values(index) = value + End Set + End Property + End Class +End Class diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb new file mode 100644 index 000000000..106c2afee --- /dev/null +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefParameterizedPropertyTests.vb @@ -0,0 +1,612 @@ +Imports System +Imports System.Collections.Generic +Imports Xunit + +Public Class ByRefParameterizedPropertyTests + Private ReadOnly _log As New List(Of String) + Private _fieldIndex As Integer = 1 + Private _db As Db + Private _index As Integer = 1 + + + Public Sub ParameterizedPropertyIsWrittenBackThroughItsSetterIssue909() + Dim db As New Db(_log) + db.Get_Equal(1, db.Qr(1, 21), "position") + Assert.Equal("changed", db.Qr(1, 21)) + Assert.Equal("get 1,21;set 1,21=changed;get 1,21", LogText()) + End Sub + + + Public Sub IndexArgumentsAreEvaluatedOnce() + Dim db As New Db(_log) + SetValue(db.Qr(NextIndex(), 21)) + Assert.Equal("index 1;get 1,21;set 1,21=changed", LogText()) + End Sub + + + Public Sub ReceiverIsEvaluatedOnce() + SetValue(GetDb().Qr(1, 21)) + Assert.Equal("receiver;get 1,21;set 1,21=changed", LogText()) + End Sub + + + Public Sub NamedIndexArgumentsAreWrittenBackThroughTheSetter() + Dim db As New Db(_log) + SetValue(db.Qr(fieldNumber:=21, tableBuffer:=NextIndex())) + Assert.Equal("index 1;get 1,21;set 1,21=changed", LogText()) + End Sub + + + Public Sub OmittedOptionalIndexIsWrittenBackThroughTheSetter() + Dim db As New Db(_log) + SetValue(db.WithDefault()) + Assert.Equal("get 7;set 7=changed", LogText()) + End Sub + + + Public Sub ImplicitMeParameterizedPropertyIsWrittenBack() + Dim db As New Db(_log) + db.SetOwnValue() + db.SetOwnValueWithMe() + Assert.Equal("get 2,3;set 2,3=changed;get 4,5;set 4,5=changed", LogText()) + End Sub + + + Public Sub LocalIndexWrittenByAnotherArgumentUsesItsOriginalValue() + Dim db As New Db(_log) + Dim index = 1 + SetValueAndIndex(db.Qr(index, 21), index) + Assert.Equal(5, index) + Assert.Equal("get 1,21;set 1,21=changed", LogText()) + End Sub + + + Public Sub FieldIndexWrittenByAnotherArgumentUsesItsOriginalValue() + Dim db As New Db(_log) + SetValueAndIndex(db.Qr(_fieldIndex, 21), _fieldIndex) + Assert.Equal(5, _fieldIndex) + Assert.Equal("get 1,21;set 1,21=changed", LogText()) + End Sub + + + Public Sub FieldReceiverReassignedByTheCalledMethodIsWrittenBackToTheOriginal() + _db = New Db(_log) + Dim original = _db + ReplaceDbAndSetValue(_db.Qr(1, 21)) + Assert.NotSame(original, _db) + Assert.Equal("changed", original.Qr(1, 21)) + Assert.Equal("get 1,21;set 1,21=changed;get 1,21", LogText()) + End Sub + + Private Sub ReplaceDbAndSetValue(ByRef value As String) + _db = New Db(New List(Of String)) + value = "changed" + End Sub + + + Public Sub FieldIndexChangedByTheCalledMethodUsesItsOriginalValue() + Dim db As New Db(_log) + _index = 1 + ChangeIndexAndSetValue(db.Qr(_index, 21)) + Assert.Equal(7, _index) + Assert.Equal("get 1,21;set 1,21=changed", LogText()) + End Sub + + Private Sub ChangeIndexAndSetValue(ByRef value As String) + _index = 7 + value = "changed" + End Sub + + + Public Sub LocalIndexChangedByALambdaTheCalledMethodRunsUsesItsOriginalValue() + Dim db As New Db(_log) + Dim index = 1 + Dim changeIndex As Action = Sub() index = 7 + SetValueAndRun(db.Qr(index, 21), changeIndex) + Assert.Equal(7, index) + Assert.Equal("get 1,21;set 1,21=changed", LogText()) + End Sub + + + Public Sub ByRefParameterIndexChangedByTheCalledMethodUsesItsOriginalValue() + _index = 1 + SetValueIndexedBy(_index) + Assert.Equal(7, _index) + Assert.Equal("get 1,21;set 1,21=changed", LogText()) + End Sub + + Private Sub SetValueIndexedBy(ByRef index As Integer) + Dim db As New Db(_log) + ChangeIndexAndSetValue(db.Qr(index, 21)) + End Sub + + + Public Sub AssignedIndexIsWrittenBackWithItsOriginalValue() + Dim db As New Db(_log) + Dim index = 1 + index = SetValueReturnFive(db.Qr(index, 21)) + Assert.Equal(5, index) + Assert.Equal("get 1,21;set 1,21=changed", LogText()) + End Sub + + Private Shared Function SetValueReturnFive(ByRef value As String) As Integer + value = "changed" + Return 5 + End Function + + + Public Sub AssignedReceiverIsWrittenBackToTheOriginal() + Dim db As New Db(_log) + Dim original = db + db = SetValueReturnNewDb(db.Qr(1, 21)) + Assert.NotSame(original, db) + Assert.Equal("changed", original.Qr(1, 21)) + Assert.Equal("get 1,21;set 1,21=changed;get 1,21", LogText()) + End Sub + + Private Shared Function SetValueReturnNewDb(ByRef value As String) As Db + value = "changed" + Return New Db(New List(Of String)) + End Function + + + Public Sub LocalIndexChangedByALoopInALambdaUsesItsOriginalValue() + Dim db As New Db(_log) + Dim index = 1 + Dim loopOverIndex As Action = Sub() + For index = 5 To 7 + Next + End Sub + SetValueAndRun(db.Qr(index, 1), loopOverIndex) + Assert.Equal(8, index) + Assert.Equal("get 1,1;set 1,1=changed", LogText()) + End Sub + + + Public Sub StaticLocalIndexChangedByARecursiveCallUsesItsOriginalValue() + Dim db As New Db(_log) + SetWithStaticIndex(db, True) + Assert.Equal("get 1,1;get 2,1;set 2,1=changed;set 1,1=changed", LogText()) + End Sub + + Private Sub SetWithStaticIndex(db As Db, recurse As Boolean) + Static index As Integer = 0 + index += 1 + SetValueAndRun(db.Qr(index, 1), Sub() + If recurse Then SetWithStaticIndex(db, False) + End Sub) + End Sub + + Private Property Idx As Integer = 1 + + + Public Sub AutoPropertyBackingFieldIndexChangedThroughThePropertyUsesItsOriginalValue() + Dim db As New Db(_log) + SetValueAndRun(db.Qr(_Idx, 1), Sub() Idx = 9) + Assert.Equal(9, Idx) + Assert.Equal("get 1,1;set 1,1=changed", LogText()) + End Sub + + + Public Sub ByRefExtensionReceiverPropertyIsWrittenBack() + Dim db As New Db(_log) + db.Plain.ChangeByRef() + Assert.Equal("plain get;plain set=changed", LogText()) + End Sub + + + Public Sub NumberToStringIndexUsesTheCultureBeforeTheCall() + Dim original = Threading.Thread.CurrentThread.CurrentCulture + Try + Threading.Thread.CurrentThread.CurrentCulture = Globalization.CultureInfo.InvariantCulture + Dim db As New Db(_log) + Dim d As Double = 1.5 + SetTwoValuesInGermanCulture(db.Qs(d & ""), db.Qs(CStr(d))) + Assert.Equal("get 1.5;get 1.5;set 1.5=changed;set 1.5=changed", LogText()) + Finally + Threading.Thread.CurrentThread.CurrentCulture = original + End Try + End Sub + + Private Shared Sub SetTwoValuesInGermanCulture(ByRef first As String, ByRef second As String) + Threading.Thread.CurrentThread.CurrentCulture = New Globalization.CultureInfo("de-DE") + first = "changed" + second = "changed" + End Sub + + + Public Sub LocalInALambdaInAFieldInitializerChangedByAnotherLambdaUsesItsOriginalValue() + Dim db As New Db(_log) + Dim initialized As New InitializedLambda + initialized.SetThroughLocal(db) + Assert.Equal("get 1,1;set 1,1=changed", LogText()) + End Sub + + Private Class InitializedLambda + Public ReadOnly SetThroughLocal As Func(Of Db, String) = Function(db As Db) + Dim i = 1 + Dim changeIndex As Action = Sub() i = 5 + SetValueAndRun(db.Qr(i, 1), changeIndex) + Return Nothing + End Function + End Class + + Private Shared _replacedIndexer As IndexHolder + + + Public Sub StructureFieldIndexOverwrittenByAssigningTheStructureUsesItsOriginalValue() + Dim db As New Db(_log) + _replacedIndexer = New IndexHolder(1) + _replacedIndexer.SetValueReplacingMe(db) + Assert.Equal("get 1,21;set 1,21=changed;get 2,22;set 2,22=changed", LogText()) + End Sub + + Private Shared Sub ReplaceIndexHolderAndSetValue(ByRef value As String) + _replacedIndexer = New IndexHolder(9) + value = "changed" + End Sub + + Private Structure IndexHolder + Private ReadOnly _readOnlyIndex As Integer + Private _constructorIndex As Integer + + Public Sub New(index As Integer) + _readOnlyIndex = index + _constructorIndex = index + 1 + End Sub + + Public Sub SetValueReplacingMe(db As Db) + ReplaceIndexHolderAndSetValue(db.Qr(_readOnlyIndex, 21)) + _replacedIndexer = New IndexHolder(1) + _replacedIndexer.SetConstructorIndexReplacingMe(db) + End Sub + + Public Sub SetConstructorIndexReplacingMe(db As Db) + ReplaceIndexHolderAndSetValue(db.Qr(_constructorIndex, 22)) + End Sub + End Structure + + + Public Sub MyBaseDefaultPropertyIsWrittenBack() + Dim db As New DerivedDb(_log) + db.SetBaseItem() + Assert.Equal("item get 1;item set 1=changed", LogText()) + End Sub + + Private Class DerivedDb + Inherits Db + + Public Sub New(log As List(Of String)) + MyBase.New(log) + End Sub + + Public Sub SetBaseItem() + SetValue(MyBase.Item(1)) + End Sub + End Class + + + Public Sub SharedParameterizedPropertyIsWrittenBackThroughItsSetter() + Db.SharedLog = _log + SetValue(Db.SharedQr(NextIndex())) + Assert.Equal("index 1;shared get 1;shared set 1=changed", LogText()) + End Sub + + Private _table As Table + + + Public Sub StructureFieldReceiverOfAParameterizedPropertyIsWrittenInPlace() + SetValue(_table.Cell(NextIndex())) + Assert.Equal("1=changed", _table.Last) + End Sub + + Private Shared _sharedTable As Table + + + Public Sub SharedStructureFieldReceiverIsWrittenInPlace() + SetValue(_sharedTable.Cell(NextIndex())) + Assert.Equal("1=changed", _sharedTable.Last) + End Sub + + + Public Sub StructureReturnedByAFunctionIsWrittenBackToItsCopy() + SetValue(GetCell().Text) + Assert.Equal("cell", LogText()) + End Sub + + Private Function GetCell() As Cell + _log.Add("cell") + Return New Cell + End Function + + + Public Sub ByRefTargetInAFieldInitializerIsEvaluatedOnce() + Dim initialized As New Initialized + Assert.Equal("changed", initialized.Value) + Assert.Equal("index 1;get 1,1;set 1,1=changed", String.Join(";", initialized.Log)) + End Sub + + Private Class Initialized + Public ReadOnly Log As New List(Of String) + Private ReadOnly _db As New Db(Log) + Public Value As String = SetValue(_db.Qr(NextLoggedIndex(), 1)) + + Private Function NextLoggedIndex() As Integer + Log.Add("index 1") + Return 1 + End Function + End Class + + Private Structure Table + Public Last As String + Public Property Cell(index As Integer) As String + Get + Return Nothing + End Get + Set(value As String) + Last = index & "=" & value + End Set + End Property + End Structure + + + Public Sub ReadOnlyParameterizedPropertyIsNotWrittenBack() + Dim db As New Db(_log) + SetValue(db.ReadOnlyQr(NextIndex())) + Assert.Equal("index 1;readonly get 1", LogText()) + End Sub + + + Public Sub DefaultPropertyIndexIsEvaluatedOnce() + Dim db As New Db(_log) + SetValue(db(NextIndex())) + Assert.Equal("index 1;item get 1;item set 1=changed", LogText()) + End Sub + + + Public Sub PropertyReceiverIsEvaluatedOnce() + SetValue(GetDb().Plain) + Assert.Equal("receiver;plain get;plain set=changed", LogText()) + End Sub + + + Public Sub SettersAreCalledFromTheLastArgumentToTheFirst() + Dim db As New Db(_log) + SetTwoValues(db.Qr(1, 1), db.Qr(NextIndex(), 2)) + Assert.Equal("get 1,1;index 1;get 1,2;set 1,2=second;set 1,1=first", LogText()) + End Sub + + Private Shared Sub SetTwoValues(ByRef first As String, ByRef second As String) + first = "first" + second = "second" + End Sub + + + Public Sub StructureReceiverInAnArrayIsWrittenInPlace() + Dim cells(2) As Cell + SetValue(cells(NextIndex()).Text) + Assert.Equal("changed", cells(1).Text) + Assert.Equal("index 1", LogText()) + End Sub + + + Public Sub StructureFieldReceiverIsWrittenInPlace() + Dim holder As New CellHolder + SetValue(holder.Cell.Text) + SetValue(GetHolder(holder).Cell.Text) + Assert.Equal("changedchanged", holder.Cell.Text) + Assert.Equal("holder", LogText()) + End Sub + + + Public Sub StructureLocalWrittenByAnotherArgumentIsWrittenInPlace() + Dim cell As Cell + SetValueAndCell(cell.Text, cell) + Assert.Equal("replacedchanged", cell.Text) + End Sub + + Private Shared Sub SetValueAndCell(ByRef value As String, ByRef cell As Cell) + value = "changed" + cell = New Cell With {.Text = "replaced"} + End Sub + + + Public Sub LocalIndexAssignedInALambdaUsesItsOriginalValue() + Dim db As New Db(_log) + Dim index = 1 + SetValueAndRun(db.Qr(index, 21), Sub() index = 5) + Assert.Equal(5, index) + Assert.Equal("get 1,21;set 1,21=changed", LogText()) + End Sub + + Private Shared Sub SetValueAndRun(ByRef value As String, action As Action) + action() + value = "changed" + End Sub + + + Public Sub OmittedIndexBeforeAGivenOneIsWrittenBackThroughTheSetter() + Dim db As New Db(_log) + SetValue(db.TwoDefaults(, NextIndex())) + Assert.Equal("index 1;get 7,1;set 7,1=changed", LogText()) + End Sub + + Private Function GetHolder(holder As CellHolder) As CellHolder + _log.Add("holder") + Return holder + End Function + + Private Class CellHolder + Public Cell As Cell + End Class + + Private Structure Cell + Private _text As String + Public Property Text As String + Get + Return _text + End Get + Set(value As String) + _text &= value + End Set + End Property + End Structure + + + Public Sub ReturnWritesBackThroughTheSetterBeforeReturning() + Dim db As New Db(_log) + Assert.Equal("changed", ReturnSetValue(db)) + Assert.Equal("index 1;get 1,21;set 1,21=changed", LogText()) + End Sub + + + Public Sub ConditionWritesBackThroughTheSetterBeforeTheBlock() + Dim db As New Db(_log) + If SetValue(db.Qr(NextIndex(), 21)) = "changed" Then + _log.Add("then " & db.Qr(1, 21)) + End If + Assert.Equal("index 1;get 1,21;set 1,21=changed;get 1,21;then changed", LogText()) + End Sub + + Private Function ReturnSetValue(db As Db) As String + Return SetValue(db.Qr(NextIndex(), 21)) + End Function + + Private Function LogText() As String + Return String.Join(";", _log) + End Function + + Private Function NextIndex() As Integer + _log.Add("index 1") + Return 1 + End Function + + Private Function GetDb() As Db + _log.Add("receiver") + Return New Db(_log) + End Function + + Private Shared Function SetValue(ByRef value As String) As String + value = "changed" + Return value + End Function + + Private Shared Sub SetValueAndIndex(ByRef value As String, ByRef index As Integer) + value = "changed" + index = 5 + End Sub + + Private Class Db + Private ReadOnly _log As List(Of String) + Private ReadOnly _values As New Dictionary(Of String, String) + + Public Sub New(log As List(Of String)) + _log = log + End Sub + + Public Sub Get_Equal(ByRef tableBuffer As Integer, ByRef keyValue As String, ByRef recordPosition As String) + keyValue = "changed" + End Sub + + Public Sub SetOwnValue() + SetValue(Qr(2, 3)) + End Sub + + Public Sub SetOwnValueWithMe() + SetValue(Me.Qr(4, 5)) + End Sub + + Public Property Qr(tableBuffer As Integer, fieldNumber As Integer) As String + Get + _log.Add("get " & tableBuffer & "," & fieldNumber) + Return Lookup(tableBuffer & "," & fieldNumber) + End Get + Set(value As String) + _log.Add("set " & tableBuffer & "," & fieldNumber & "=" & value) + _values(tableBuffer & "," & fieldNumber) = value + End Set + End Property + + Public Property TwoDefaults(Optional a As Integer = 7, Optional b As Integer = 8) As String + Get + _log.Add("get " & a & "," & b) + Return Nothing + End Get + Set(value As String) + _log.Add("set " & a & "," & b & "=" & value) + End Set + End Property + + Public Property Qs(key As String) As String + Get + _log.Add("get " & key) + Return Nothing + End Get + Set(value As String) + _log.Add("set " & key & "=" & value) + End Set + End Property + + Public Shared SharedLog As List(Of String) + + Public Shared Property SharedQr(index As Integer) As String + Get + SharedLog.Add("shared get " & index) + Return Nothing + End Get + Set(value As String) + SharedLog.Add("shared set " & index & "=" & value) + End Set + End Property + + Public Property WithDefault(Optional index As Integer = 7) As String + Get + _log.Add("get " & index) + Return Lookup(CStr(index)) + End Get + Set(value As String) + _log.Add("set " & index & "=" & value) + End Set + End Property + + Public ReadOnly Property ReadOnlyQr(index As Integer) As String + Get + _log.Add("readonly get " & index) + Return Lookup(CStr(index)) + End Get + End Property + + Default Public Property Item(index As Integer) As String + Get + _log.Add("item get " & index) + Return Lookup(CStr(index)) + End Get + Set(value As String) + _log.Add("item set " & index & "=" & value) + End Set + End Property + + Public Property Plain As String + Get + _log.Add("plain get") + Return Nothing + End Get + Set(value As String) + _log.Add("plain set=" & value) + End Set + End Property + + Private Function Lookup(key As String) As String + Dim value As String = Nothing + _values.TryGetValue(key, value) + Return value + End Function + End Class +End Class + +Public Module ByRefParameterizedPropertyExtensions + + Public Sub ChangeByRef(ByRef value As String) + value = "changed" + End Sub +End Module diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb index f4a5112f5..e73e7ddcb 100644 --- a/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/ByRefWriteBackPlacementTests.vb @@ -582,6 +582,362 @@ Public Class ByRefWriteBackPlacementTests Assert.Equal("xxx", h.Plain) End Sub + + Public Sub StructureIfConditionWritesBackBeforeTheBody() + Dim s As New LoggedValue(New List(Of String)) + s.IfCondition() + Assert.Equal("get 0,set 1,then 1", s.LogText) + End Sub + + + Public Sub StructureElseIfConditionWritesBackBeforeTheBody() + Dim s As New LoggedValue(New List(Of String)) + s.ElseIfCondition() + Assert.Equal("mark if,get 0,set 1,elseif 1", s.LogText) + End Sub + + + Public Sub StructureShortCircuitedOperandOnlyWritesBackWhenCalled() + Dim s As New LoggedValue(New List(Of String)) + s.ShortCircuitedOperand(False) + s.ShortCircuitedOperand(True) + Assert.Equal("mark left,mark left,get 0,set 1,then 1", s.LogText) + End Sub + + + Public Sub StructureWhileConditionWritesBackEachTime() + Dim s As New LoggedValue(New List(Of String)) + s.WhileCondition() + Assert.Equal("get 0,set 1,body 1,get 1,set 2,body 2,get 2,set 3", s.LogText) + End Sub + + + Public Sub StructureDoLoopUntilConditionWritesBackEachTime() + Dim s As New LoggedValue(New List(Of String)) + s.DoLoopUntilCondition() + Assert.Equal("body 0,get 0,set 1,body 1,get 1,set 2", s.LogText) + End Sub + + + Public Sub StructureOperandWritesBackBeforeTheNextOperand() + Dim s As New LoggedValue(New List(Of String)) + Assert.Equal(2, s.OperandFollowedByPeek()) + Assert.Equal("get 0,set 1,peek 1", s.LogText) + End Sub + + + Public Sub StructureDeclaratorWritesBackBeforeTheNext() + Dim s As New LoggedValue(New List(Of String)) + Assert.Equal(2, s.DeclaratorFollowedByPeek()) + Assert.Equal("get 0,set 1,peek 1", s.LogText) + End Sub + + + Public Sub StructureNestedCallsWriteBackInnerFirst() + Dim s As New LoggedValue(New List(Of String)) + s.NestedCalls() + Assert.Equal("get 0,get 0,set 1,set 0,then 0", s.LogText) + End Sub + + + Public Sub StructureInstanceMethodSeesItsOwnState() + Dim s As New LoggedValue(New List(Of String)) + s.InstanceMethodInCondition() + Assert.Equal("get 0,instance 0,set 1,then 1", s.LogText) + End Sub + + + Public Sub StructureConstructorConditionWritesBackBeforeTheBody() + Dim s As New LoggedValue(New List(Of String), True) + Assert.Equal("get 0,set 1,then 1", s.LogText) + End Sub + + + Public Sub StructurePropertyGetterConditionWritesBackBeforeTheBody() + Dim s As New LoggedValue(New List(Of String)) + Assert.Equal(1, s.IncrementedIfPositive) + Assert.Equal("get 0,set 1,get 1", s.LogText) + End Sub + + + Public Sub StructureSharedMemberConditionWritesBackBeforeTheBody() + LoggedValue.SharedValue = 0 + Assert.True(LoggedValue.SharedCondition()) + Assert.Equal(1, LoggedValue.SharedValue) + End Sub + + + Public Sub WithStructureFieldConditionWritesBackBeforeTheBody() + Dim h As New CounterHolder + Assert.Equal(1, h.IncrementInWith()) + Assert.Equal(1, h.Inner.P) + End Sub + + + Public Sub WithInsideALambdaArgumentStaysInTheLambda() + Dim h As New CounterHolder + Assert.Equal(13, h.WithInLambdaArgument()) + End Sub + + Public Sub WithByRefParameterConditionWritesBackBeforeTheBody() + Dim h As New CounterHolder + Dim c As New Counter + Assert.Equal(11, CounterHolder.IncrementInWithByRefParameters(h, c)) + Assert.Equal(1, c.P) + End Sub + + Public Sub WithOverAReassignedClassVariableKeepsTheOriginalObject() + Dim h As New CounterHolder + Dim original = h + With h + h = New CounterHolder + .Total = 1 + End With + Assert.Equal("1,0", original.Total & "," & h.Total) + End Sub + + Public Sub ByRefParametersWithKeywordNamesArePassedToTheLocalFunction() + Dim a As New Counter, b As New Counter, c As New Counter + Assert.True(IncrementKeywordNamedParameters(a, b, c)) + Assert.Equal("1,1,1", a.P & "," & b.P & "," & c.P) + End Sub + Private Shared Function IncrementKeywordNamedParameters(ByRef [class] As Counter, ByRef params As Counter, ByRef [string] As Counter) As Boolean + If Increment([class].P) + Increment(params.P) + Increment([string].P) = 3 Then + Return [class].P + params.P + [string].P = 3 + End If + Return False + End Function + + Public Sub OutParameterNamedLikeItsTypeIsNotPassedToTheLocalFunction() + Tally.Count = 0 + Dim created As Tally = Nothing + Assert.True(TryCreateTally(created)) + Assert.Equal("1,True", Tally.Count & "," & (created IsNot Nothing)) + End Sub + Private Shared Function TryCreateTally( ByRef tally As Tally) As Boolean + If Increment(Tally.Count) > 0 Then + tally = New Tally + Return True + End If + tally = Nothing + Return False + End Function + Private Class Tally + Public Shared Property Count As Integer + End Class + Private Class CounterHolder + Public Inner As Counter + Public Property Total As Integer + + Public Shared Function IncrementInWithByRefParameters(ByRef holder As CounterHolder, ByRef counter As Counter) As Integer + Dim result = 0 + With holder + If Increment(.Total) > 0 Then result = .Total * 10 + End With + With counter + If Increment(.P) > 0 Then result += .P + End With + Return result + End Function + Public Function WithInLambdaArgument() As Integer + If AddResult(Total, Function() + With Inner + .P = 3 + End With + Return 1 + End Function) > 0 Then Return Total * 10 + Inner.P + Return -1 + End Function + + Private Shared Function AddResult(ByRef target As Integer, f As Func(Of Integer)) As Integer + target += f() + Return target + End Function + + Public Function IncrementInWith() As Integer + With Inner + If Increment(.P) > 0 Then Return .P + End With + Return -1 + End Function + End Class + + + Public Sub StructureWithStructureFieldConditionWritesBackBeforeTheBody() + Dim s As New LoggedValue(New List(Of String)) + Assert.Equal(1, s.IncrementInnerInWith()) + Assert.Equal(1, s.Inner.P) + End Sub + + + Public Sub StructureWithMeConditionWritesBackBeforeTheBody() + Dim s As New LoggedValue(New List(Of String)) + s.IfConditionInWithMe() + Assert.Equal("get 0,set 1,then 1", s.LogText) + End Sub + + Public Sub StructureMePassedByRefIsCopiedAfterAnEarlierWriteBack() + Dim s As New LoggedValue(New List(Of String)) + Assert.Equal(2, s.OperandThenMeByRef()) + End Sub + + + Public Sub StructureMePassedByRefAfterAndAlsoIsCopiedAfterAnEarlierWriteBack() + Dim s As New LoggedValue(New List(Of String)) + Assert.True(s.MeByRefAfterAndAlso()) + End Sub + + Private Structure LoggedValue + Public Shared SharedValue As Integer + Private ReadOnly _log As List(Of String) + Private _value As Integer + Public Inner As Counter + + Public Sub New(log As List(Of String)) + _log = log + End Sub + + Public Sub New(log As List(Of String), incrementInCondition As Boolean) + _log = log + If incrementInCondition AndAlso Increment(Value) > 0 Then + _log.Add("then " & _value) + End If + End Sub + + Public ReadOnly Property LogText As String + Get + Return String.Join(",", _log) + End Get + End Property + + Public Property Value As Integer + Get + _log.Add("get " & _value) + Return _value + End Get + Set(v As Integer) + _log.Add("set " & v) + _value = v + End Set + End Property + + Public ReadOnly Property IncrementedIfPositive As Integer + Get + If Increment(Value) > 0 Then + Return Value + End If + Return -1 + End Get + End Property + + Private Function Mark(name As String, result As Boolean) As Boolean + _log.Add("mark " & name) + Return result + End Function + + Private Function Peek() As Integer + _log.Add("peek " & _value) + Return _value + End Function + + Private Function IncrementLogged(ByRef v As Integer) As Integer + _log.Add("instance " & _value) + v += 1 + Return v + End Function + + Public Sub IfCondition() + If Increment(Value) > 0 Then + _log.Add("then " & _value) + End If + End Sub + + Public Sub ElseIfCondition() + If Mark("if", False) Then + _log.Add("if") + ElseIf Increment(Me.Value) > 0 Then + _log.Add("elseif " & _value) + End If + End Sub + + Public Sub ShortCircuitedOperand(callIt As Boolean) + If Mark("left", callIt) AndAlso Increment(Value) > 0 Then + _log.Add("then " & _value) + End If + End Sub + + Public Sub WhileCondition() + While Increment(Value) < 3 + _log.Add("body " & _value) + End While + End Sub + + Public Sub DoLoopUntilCondition() + Do + _log.Add("body " & _value) + Loop Until Increment(Value) >= 2 + End Sub + + Public Function OperandFollowedByPeek() As Integer + Return Increment(Value) + Peek() + End Function + + Public Function DeclaratorFollowedByPeek() As Integer + Dim a = Increment(Value), b = Peek() + Return a + b + End Function + + Public Sub NestedCalls() + If AddTo(Value, Increment(Value)) > 0 Then + _log.Add("then " & _value) + End If + End Sub + + Public Sub InstanceMethodInCondition() + If IncrementLogged(Value) > 0 Then + _log.Add("then " & _value) + End If + End Sub + + Public Function IncrementInnerInWith() As Integer + With Inner + If Increment(.P) > 0 Then Return .P + End With + Return -1 + End Function + + Public Sub IfConditionInWithMe() + With Me + If Increment(.Value) > 0 Then + _log.Add("then " & _value) + End If + End With + End Sub + Public Function OperandThenMeByRef() As Integer + Return Increment(Value) + ValueOf(Me) + End Function + + Public Function MeByRefAfterAndAlso() As Boolean + Return Increment(Value) > 0 AndAlso ValueOf(Me) = 1 + End Function + + Private Shared Function ValueOf(ByRef s As LoggedValue) As Integer + Return s._value + End Function + + Public Shared Function SharedCondition() As Boolean + If Increment(SharedValue) > 0 Then + Return SharedValue = 1 + End If + Return False + End Function + End Structure + + Private Shared Function AddTo(ByRef target As Integer, amount As Integer) As Integer + target = 0 + Return amount + End Function + Private Shared Function Increment(ByRef value As Integer) As Integer value += 1 Return value