Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
61 commits
Select commit Hold shift + click to select a range
a116487
Build a local function's arguments and parameters in shared lists
claude Nov 18, 2026
482b2b9
Pass this by ref to a struct's write-back local function
claude Nov 18, 2026
55b4b4d
Look up a local function's enclosing symbol and operation once
claude Nov 18, 2026
7a2e552
Only pass this to a struct's local function when it uses this
claude Nov 18, 2026
74c5ded
Pass ref locals to a write-back local function by ref
claude Nov 18, 2026
66c9f04
Copy a structure's Me at the call when it's passed ByRef
claude Nov 18, 2026
44a635f
Document further pre-existing ByRef gaps found in review
claude Nov 18, 2026
0b2cc99
Pass this to a write-back local function inside With Me in a structure
claude Nov 18, 2026
e762991
Don't pass a ref local declared inside the write-back local function
claude Nov 18, 2026
067bc7f
Pass a ByRef parameter used as a With receiver to the local function
claude Nov 18, 2026
1f19e57
Keep a ref local's TypeSyntax instead of reparsing it
claude Nov 18, 2026
6330662
Extract adding a parameterized property setter's value argument
claude Nov 15, 2026
ae65b03
Write back a ByRef parameterized property through its setter (#909)
claude Nov 15, 2026
33eee75
Evaluate a ByRef property target's receiver and indexes once
claude Nov 16, 2026
5a58e8f
Document what a ByRef write-back writes to
claude Nov 16, 2026
9ec4b83
Write a ByRef structure property back in place
claude Nov 17, 2026
077b82d
Test that ByRef setters write back in VB's reverse order
claude Nov 17, 2026
15ae6ec
Test more shapes of ByRef property targets
claude Nov 17, 2026
80d2bb6
Drop unreachable cases from ByRef target temporaries
claude Nov 17, 2026
baa5344
Document remaining ByRef property target gaps
claude Nov 17, 2026
1a94b44
Ask an oracle whether a call may change a field
claude Nov 17, 2026
4eedd83
Copy a ByRef target's field when the call could change it
claude Nov 17, 2026
65c25b5
Copy a ByRef target's local when the call could change it
claude Nov 17, 2026
8a399a9
Document late-bound ByRef parameterized properties as a gap
claude Nov 17, 2026
5a46f1b
Test which field writes make a ByRef target copy the field
claude Nov 17, 2026
95006f3
Test a ByRef setter write-back before an assignment replaces its target
claude Nov 17, 2026
c1e0cf4
Move the ByRef target temporaries and field analysis into ByRefArguments
claude Nov 17, 2026
45e5cb4
Extract what counts as writing a variable
claude Nov 17, 2026
70c4196
Test more ByRef property targets that coverage showed untested
claude Nov 17, 2026
1f631ed
Copy a ByRef target's local written by any kind of statement
claude Nov 17, 2026
222470c
Always copy a Static local used in a ByRef target
claude Nov 17, 2026
ef133f3
Treat an auto-property's backing field as changeable
claude Nov 17, 2026
39a43fa
Reuse intrinsic operators on reusable operands in a ByRef target
claude Nov 17, 2026
9f329bc
Document the ByRef target rules found in review
claude Nov 17, 2026
3e1e94a
Test a Shared structure field receiver written in place
claude Nov 17, 2026
da61c89
Name the setter by renaming the getter call's last identifier
claude Nov 17, 2026
d3a4aa2
Make two write-analysis assumptions explicit
claude Nov 17, 2026
0b16c8f
Copy a ByRef target's culture-dependent operators and conversions
claude Nov 17, 2026
47bddb0
Look for lambdas that write a local in an initializer's lambda too
claude Nov 17, 2026
898def8
Test a property passed as a ByRef extension receiver
claude Nov 17, 2026
7020f37
Document the culture-free and initializer-lambda rules
claude Nov 17, 2026
733bd61
Build the field write analysis once per project
claude Nov 18, 2026
21f9b1e
Copy a structure's instance field used in a ByRef target
claude Nov 18, 2026
e194d7e
Copy an element access's container only when it could change
claude Nov 18, 2026
5896c82
Test a ByRef default property on MyBase
claude Nov 18, 2026
879fd38
Pass only the ByRef parameters the local function's body uses
claude Nov 18, 2026
4645ea1
Throw when a ref local reference has no recorded type
claude Nov 18, 2026
553c78e
Pin that a structure's Shared member's local function takes no self
claude Nov 18, 2026
bb5997f
Merge #9's branch (fix-896-1081-byref-writeback-placement) into fix-909
claude Nov 18, 2026
2e2d43a
Merge master into fix-909
claude Nov 18, 2026
bc8edc0
Copy a With block's class reference instead of taking a ref to it
claude Nov 18, 2026
0d0ecc2
Note that MyBase can't reach a structure's local function
claude Nov 18, 2026
12ba186
Test ByRef parameterized properties in a structure and in With blocks
claude Nov 18, 2026
049bcf9
Merge #9's latest commits into fix-909
claude Nov 18, 2026
c15ced0
Take a local function's ByRef parameters from the VB call's references
claude Nov 18, 2026
3861a12
Merge origin/master into claude/fix-896-1081-byref-writeback-placement
claude Nov 18, 2026
b22e784
Merge #9's branch (3861a12) into fix-909
claude Nov 18, 2026
b870edb
Evaluate the receiver once in #9's TypeNamedLikeAByRefParameterIsNotP…
claude Nov 18, 2026
666d576
Pass a ByRef parameter with a keyword name to the local function
claude Nov 18, 2026
bcdfa5f
Don't pass a ByRef parameter named only by an anonymous-type member
claude Nov 18, 2026
7c244dd
Don't pass a ByRef parameter named only by an object-initializer member
claude Nov 18, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 13 additions & 10 deletions CodeConverter/CSharp/AdditionalAssignment.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
/// <summary>
/// A parameterized property becomes a pair of methods in C#, so there's nothing to assign to: call its setter instead.
/// </summary>
public static AdditionalAssignment ViaSetter(InvocationExpressionSyntax setterCall) => new(setterCall);

public static StatementSyntax CreateAssignment(AdditionalAssignment additionalAssignment) =>
SyntaxFactory.ExpressionStatement(additionalAssignment._assignment);
}
5 changes: 3 additions & 2 deletions CodeConverter/CSharp/ArgumentConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<CSharpSyntaxNode> ConvertSimpleArgumentAsync(VBSyntax.SimpleArgumentSyntax node)
Expand Down
32 changes: 25 additions & 7 deletions CodeConverter/CSharp/ByRefArguments/ByRefArgumentHoister.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
namespace ICSharpCode.CodeConverter.CSharp.ByRefArguments;
using Microsoft.CodeAnalysis.Operations;

namespace ICSharpCode.CodeConverter.CSharp.ByRefArguments;

/// <summary>
/// C# can only pass a variable by reference, so a ByRef argument that isn't one gets a temporary, and VB's copy-back becomes a write-back statement.
Expand All @@ -7,17 +9,19 @@ internal class ByRefArgumentHoister
{
private readonly ITypeContext _typeContext;
private readonly SemanticModel _semanticModel;
private readonly IFieldMutationOracle _fieldMutations;
private CommonConversions CommonConversions { get; }

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

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

Expand Down Expand Up @@ -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);
Expand All @@ -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));
}
}
188 changes: 188 additions & 0 deletions CodeConverter/CSharp/ByRefArguments/ByRefTargetTemporaries.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.Operations;

namespace ICSharpCode.CodeConverter.CSharp.ByRefArguments;

/// <summary>
/// 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.
/// </summary>
/// <remarks>
/// 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 (<see cref="IFieldMutationOracle"/>).
/// An intrinsic operator on such parts gives the same value again too.
/// </remarks>
internal class ByRefTargetTemporaries
{
private readonly SemanticModel _semanticModel;
private readonly ITypeContext _typeContext;
private readonly IFieldMutationOracle _fieldMutations;
private readonly VBSyntax.ExpressionSyntax _vbTarget;
private readonly Lazy<HashSet<ISymbol>> _writtenSymbols;

private ByRefTargetTemporaries(SemanticModel semanticModel, ITypeContext typeContext, IFieldMutationOracle fieldMutations, VBSyntax.ExpressionSyntax vbTarget)
{
_semanticModel = semanticModel;
_typeContext = typeContext;
_fieldMutations = fieldMutations;
_vbTarget = vbTarget;
_writtenSymbols = new Lazy<HashSet<ISymbol>>(GetSymbolsWrittenInEnclosingExpression);
}

/// <returns>The C# target with each part VB evaluates once replaced by a hoisted temporary, where its value could otherwise differ.</returns>
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));
}

/// <summary>
/// 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.
/// </summary>
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<CSSyntax.ArgumentSyntax> HoistArguments(SeparatedSyntaxList<CSSyntax.ArgumentSyntax> 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<CSSyntax.ArgumentSyntax> HoistIndices(SeparatedSyntaxList<CSSyntax.ArgumentSyntax> csArgs, ImmutableArray<IOperation> indices)
{
return CS.SyntaxFactory.SeparatedList(csArgs.Select((csArg, i) =>
IsReusable(indices.ElementAtOrDefault(i)) ? csArg : csArg.WithExpression(HoistValue(csArg.Expression))));
}

/// <remarks>A ParamArray's elements don't map one to one onto C# arguments, so they're each copied.</remarks>
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
};

/// <returns>The call (or object creation, or event raise) that the ByRef target is an argument of.</returns>
private IOperation GetCall() => _semanticModel.GetOperation(_vbTarget)?.Parent is IArgumentOperation { Parent: var call } ? call : null;

/// <summary>
/// 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.
/// </summary>
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 };
}

/// <summary>
/// Besides conversions between culture-free types, a widening reference or boxing conversion only changes the static type.
/// </summary>
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;

/// <summary>
/// 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.
/// </summary>
private HashSet<ISymbol> 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<VBSyntax.LambdaExpressionSyntax>()
?? Enumerable.Empty<VBSyntax.LambdaExpressionSyntax>();

var written = lambdasInMember.Prepend<SyntaxNode>(enclosing)
.SelectMany(GetVariablesWrittenIn);
return new HashSet<ISymbol>(written, SymbolEqualityComparer.Default);
}

private IEnumerable<ISymbol> 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<ISymbol>();

private static ISymbol GetReferencedVariable(IOperation operation) => operation switch {
ILocalReferenceOperation l => l.Local,
IParameterReferenceOperation p => p.Parameter,
IFieldReferenceOperation f => f.Field,
_ => null
};
}
Loading
Loading