Skip to content

Write back ByRef parameterized properties through the setter, evaluating receiver and indexes once - #1326

Merged
GrahamTheCoder merged 61 commits into
icsharpcode:masterfrom
GrahamTheCoder:claude/fix-909-parameterized-property-byref
Nov 18, 2026
Merged

GrahamTheCoder merged 61 commits into
icsharpcode:masterfrom
GrahamTheCoder:claude/fix-909-parameterized-property-byref

Conversation

@GrahamTheCoder

Copy link
Copy Markdown
Member

Fixes #909

This PR carries all the ByRef work after c8c3931, the commit upstream already merged (#1317, which fixed #896 and #1081). It contains #9's follow-ups and the #909 fix. It doesn't claim #896 or #1081 again: the follow-ups are refinements of that merged fix, not new fixes for those issues.

The branch merged #9's branch (up to 3861a12) and master with merge commits. The only conflicts were master's ErrUsage and this PR's FieldWriteAnalysis being threaded through the same constructors; both are kept.

ByRef write-back follow-ups (from #9, after c8c3931)

  • Structures: the local function takes ref this. A local function in a struct can't use this (CS1673). Where the call uses an instance member, the local function takes ref S self, is called with ref this, and its body uses self: int localInc(ref S self) { int argv = self.P; var ret = Inc(ref argv); self.P = argv; return ret; } then if (b && localInc(ref this) > x).
    • This replaces the old after-the-statement fallback (compiling, but late) for operands, If/ElseIf, block headers, Dim declarators and compound or receiver-target assignments. It also fixes struct loop conditions, which gave CS1673.
    • Whether self is needed is decided from the converted body: it qualifies every instance member with this before simplification, so With Me is covered too, and a With on a local isn't.
    • ref this is legal in every context VB can reach. VB has no read-only members (CS1605), no MyBase in a structure (BC30044) and no Me in a structure's lambdas (BC36638). Shared members keep a parameterless local function.
  • With ref locals and ByRef parameters are passed as ref parameters.
    • A local function can't use a ref local (CS8175), such as ref var withBlock = ref Inner; over a structure field. References to ref locals are annotated with their type (RefLocalReferences), and the local function takes each one it uses as a ref parameter of the same name. Ref locals declared inside the body (e.g. inside a lambda argument) aren't passed.
    • The enclosing method's ByRef parameters (CS1628) are passed the same way, including one reused directly as a With receiver (With b : Inc(.X)).
  • Which ByRef parameters are passed. The candidates are the ByRef parameters the VB call's operations reference, with a With block's implicit receiver resolved to the With expression. The converted body then drops any it no longer mentions (e.g. a header evaluated into withBlock), comparing escaped names ordinally and ignoring member names (member accesses, named arguments, anonymous-type and object-initializer members). So a type named like a parameter (H.S beside <Out> ByRef h As H, which gave CS0269) isn't passed, and neither is an unused ref h.
  • With over a class-typed variable copies the reference: var withBlock = b; instead of ref var withBlock = ref b;, which followed a reassignment of b inside the block (VB keeps the original object). Only a value type or unconstrained type parameter gets a ref local. Changed expectation: MethodStatementTests.WithBlockWithNullConditionalAccessAsync.
  • A structure's Me passed ByRef after a write-back (Return Inc(P) + ValueOf(Me)) takes the local function, so the copy of Me is taken at the call: VB returns 2, and C# returned 1 before.
  • Tests: self-verifying ByRefWriteBackPlacementTests.vb (struct evaluation order, With over structure fields, With Me, With inside a lambda argument, With over ByRef parameters and a reassigned class variable, an Out parameter named like its type, ByRef parameters with keyword names, a struct's Me passed ByRef). Conversion tests in ByRefTests: Structure…PassThisToTheLocalFunctionAsync (3), StructureWithBlockOnALocalDoesNotPassThisAsync, StructureWithMePassesThisToTheLocalFunctionAsync, StructureSharedMemberDoesNotPassThisAsync, WithBlockRefLocalIsPassedToTheLocalFunctionAsync, RefLocalDeclaredInsideTheLocalFunctionIsNotPassedAsync, WithByRefParameterIsPassedToTheLocalFunctionAsync, ByRefParameterOnlyInAWithHeaderIsNotPassedAsync, TypeNamedLikeAByRefParameterIsNotPassedAsync, KeywordNamedByRefParametersArePassedToTheLocalFunctionAsync, AnonymousTypeMemberNamedLikeAByRefParameterIsNotPassedAsync, ObjectInitializerMemberNamedLikeAByRefParameterIsNotPassedAsync, StructureMePassedByRefAfterAWriteBackTakesTheLocalFunctionAsync.
  • Known gaps (see CodeConverter/CSharp/ByRefArguments/README.md):
    • aliasing through two names (h1.P = F(h2.P) with h1 Is h2);
    • a ByRef New argument in an assignment (WF = New W(WF.Name)), and ByRef arguments of New in a block header, which write back after the block;
    • a setter with side effects on the written-back target;
    • a non-constant For … Step, re-evaluated each iteration (not ByRef-specific);
    • a ReadOnly auto-property passed ByRef in a constructor or initializer isn't written back;
    • a lambda parameter inside a ByRef argument (CS0103), and an auto-property initializer (ph… placeholder, CS0103);
    • partial-class instance initializers run in part order;
    • Inc(InnerProp.P) with a structure-returning property (CS1612), and Select Case Inc(P) with Case Inc(P) (CS0825).
    • Always use project context for conversion #9's gaps "Inc(Item(0)) gives CS0131" and "the receiver is evaluated again on write-back (F(GetH(h).P))" are fixed by the VB -> C#: Property Getter is used instead of Setter for ref argument #909 work below.

Review round 5 (ByRef placement, c15ced0)

Fixed, test-first, one commit each:

  • 666d576 (bug): a ByRef parameter with a keyword name ([class], params, [string]) wasn't passed to the local function, which gave CS1628. CsEscapedIdentifier("params") gives a token whose ValueText keeps the @, so the name comparison missed it. The comparison now uses the escaped name. The parameter is declared and passed with the same escaped identifier (localInc1(ref Box @params), localInc1(ref @params)), so the tree binds the way its text does. Tests: the conversion test KeywordNamedByRefParametersArePassedToTheLocalFunctionAsync and the self-verifying ByRefParametersWithKeywordNamesArePassedToTheLocalFunction; both were red with CS1628 first.
  • bcdfa5f (ugly output): an anonymous-type member New With {.i = 1} counted as a use of a ByRef i, which gave an unused ref int i. NameEquals names are now member names, like NameColon ones. Test: AnonymousTypeMemberNamedLikeAByRefParameterIsNotPassedAsync, red first.

Review round 6 (ByRef placement)

No bugs; the review has converged. One cleanup of the same kind as bcdfa5f, test-first:

  • 7c244dd (ugly output): an object-initializer member New Box With {.i = 1} counted as a use of a ByRef i, which gave an unused ref int i. The left side of an assignment in an object initializer is now a member name. Test: ObjectInitializerMemberNamedLikeAByRefParameterIsNotPassedAsync, red first.
  • Declined (harmless): a parameter used only in nameof is still passed as ref.
  • Suite at 7c244dd: 2019 passed, 5 skipped, 0 failed, no hang.

#909: root cause

A parameterized property (not the default one) converts to get_Qr/set_Qr methods. A ByRef argument Db.Qr(CourseBuffer, 21) converts to the getter call. HoistByRefDeclaration (now ByRefArguments/ByRefArgumentHoister) used that converted target as the write-back's assignment target, which gave Db.get_Qr(CourseBuffer, 21) = argkeyValue; (CS0131).

There was a second problem in the same place. VB evaluates a copied-back target's receiver and index arguments once, and reuses them for the write (Roslyn UseTwiceRewriter.vb, called from RewriteByRefArgumentWithCopyBack in LocalRewriter_Call.vb). The C# read and the write-back each evaluated them. So db.Qr(NextIndex(), 1), GetC().Plain and other(NextIndex()) ran NextIndex()/GetC() twice, and a field the called method reassigned was read again with its new value. This affected C#-visible indexers and plain properties too, not only parameterized ones.

#909: design

  • ByRefArgumentHoister.CreateWriteBack: for a parameterized property, the write-back calls the setter with the same index arguments plus the value (AdditionalAssignment.ViaSetter). The value-argument logic moved to CommonConversions.AddSetterValueArgument, which ordinary assignments share. The setter call takes its place in the reversed per-call write-back order like any other write-back.

  • ByRefTargetTemporaries (new, in CSharp/ByRefArguments/ with the other ByRef pieces): when there is a write-back, it hoists into a tmp only the parts whose second evaluation could give a different value. Simple output is unchanged.

    • Never copied: constants, literals and Me, and intrinsic unary or binary operators or conversions on parts that aren't copied (i + 1), when everything involved is numeric, Boolean, Char or an enum (or their nullables), or the conversion is an identity, widening reference or boxing one. Those give the same result, or throw the same exception, again. Anything involving String or Date can read the current culture, which the call can change (d & "" gives 1.5 before a call that switches to de-DE and 1,5 after it); an operator on Object is late bound; a user-defined one runs user code. Those are copied.
    • A local or ByVal parameter is copied only if the enclosing expression writes it, or a lambda in the same method does (outside a method, e.g. in a field initializer's lambda, the outermost enclosing lambda): the call could run that lambda. A write is anything in VariableWrites, which FieldWriteAnalysis uses too: an assignment, compound assignment, ByRef or late-bound argument, For/For Each control variable, ReDim, Erase or Mid statement.
    • A ByRef parameter is always copied, since it aliases a variable the call might reach. A Static local is always copied, since it outlives the call like a field.
    • A field is copied if either of those writes it, or if IFieldMutationOracle.MayChangeDuringCall(field, call) says the call could change it (see below).
    • Everything else is copied: calls, property reads, other operators and conversions, and ParamArray elements.
    • An element access's container (a default property's or indexer's receiver, or an array) follows the same receiver rules, so Me(i, 5) stays this[i, 5] and MyBase.Item(i) stays base[i] (it used to give var tmp = base;, CS0175).
    • A structure variable receiver stays in place, because writing through a copy would lose the write. Only the parts that locate it are copied: the array and indexes, or the reference holding the field. VB does the same.
    • Temporaries only apply when there's a write-back. A ReadOnly property (VB doesn't copy back) is already evaluated once.
  • FieldWriteAnalysis : IFieldMutationOracle answers once per project: VBToCSProjectContentsConverter creates it (like typeToInheritors) and passes it down to ByRefArgumentHoister. Each document is converted with its own compilation (after WithExpandedRootAsync), so fields are matched by documentation ID. It's sound without knowing what the call reaches. A field can't change during any call if:

    • it's Const, or ReadOnly and not an instance field of a structure; or
    • only this compilation can write it (it, or a type containing it, is Private, or Friend with no InternalsVisibleTo), and nothing in the compilation writes it outside construction.

    Construction means a constructor writing its own instance's field, a shared constructor writing a shared field, or a field or property initializer. It has finished before anything can read the field. A lambda inside a constructor isn't excluded, since it can run later.

    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), since it's written through the property. So is any instance field of a structure, even ReadOnly or only set in its constructor, because assigning the whole structure (s = New S(9)) overwrites it.

    The call parameter is unused for now. It's there so a call-graph implementation (a graph of method references) can later narrow the answer to the fields the call can transitively write. Such an implementation would treat overridable and interface calls, delegates, late-bound calls and calls outside the compilation conservatively. The README describes this.

  • Inside the follow-ups' local functions, the setter and temporaries go through the ref parameter: 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; }, self[i] = argv for Me(i), and withBlock.set_Qr(…) / s.set_Qr(…) in a With over a structure field or ByRef structure parameter. No extra code was needed for this; tests pin it.

VB argument (ByRef parameter) C#
Db.Qr(CourseBuffer, 21) (issue; Module Euro_Str, fields never written outside it) string argkeyValue = Euro_Str.Db.get_Qr(Euro_Str.CourseBuffer, 21); … Euro_Str.Db.set_Qr(Euro_Str.CourseBuffer, 21, argkeyValue);
_db.Qr(_readOnlyIndex, _neverWritten) (Private; _db and _readOnlyIndex ReadOnly) _db.get_Qr(_readOnlyIndex, _neverWritten) … _db.set_Qr(_readOnlyIndex, _neverWritten, argvalue)
_db.Qr(_assignedInConstructor, _writtenElsewhere) var tmp = _writtenElsewhere; … _db.set_Qr(_assignedInConstructor, tmp, argvalue1)
_db.Qr(PublicIndex, 1) (a Public field) var tmp1 = PublicIndex; … _db.set_Qr(tmp1, 1, argvalue2)
_db.Qr(_point) (a structure field) var tmp9 = _point; … _db.set_Qr(tmp9, argvalue13)
ReplaceDbAndSetValue(_db.Qr(1, 21)) (the called method assigns _db) var tmp = _db; … tmp.set_Qr(1, 21, argvalue): written back to the original object, like VB
Qr((i), 2), Qr(i + 1, -i) (local i, implicit Me) get_Qr(i, 2) … set_Qr(i, 2, argvalue), set_Qr(i + 1, -i, argvalue)
Qr(o + 1, 2) (o As Object), Qr(m + m, 2) (user-defined operator), Qs(d & ""), Qs(CStr(d)) (d As Double) copied into a tmp, e.g. var tmp = Conversions.ToInteger(Operators.AddObject(o, 1));
Qr(_Idx, 1) (auto-property backing field), Qr(index, 1) (Static index) copied into a tmp
other.Qr(_index, NextIndex()) var tmp = NextIndex(); … other.set_Qr(_index, tmp, argvalue1)
GetC().Qr(1, 2), GetC().Plain, Inc(GetH(New H().Q).Q) var tmp = GetC(); … tmp.set_Qr(1, 2, arg), tmp.Plain = arg, var tmp = GetH(new H().Q); … tmp.Q = argv1;
other(NextIndex()), Me(i, 5) (default property / indexer) var tmp3 = NextIndex(); … other[tmp3] = argvalue4, this[i, 5] = argvalue
SetValueAndIndex(other.Qr(i, 2), i), or i assigned by a lambda in the method var tmp4 = i; … other.set_Qr(tmp4, 2, argvalue5)
db.Qr(fieldNumber:=21, tableBuffer:=x), db.WithDefault() the setter's value is passed as value: when an index argument is named or omitted, e.g. db.set_WithDefault(value: argvalue)
cells(NextIndex()).Text, GetHolder(h).Cell.Text (Cell a structure) the index or GetHolder(h) goes in a tmp; cells[tmp].Text = arg / tmp.Cell.Text = arg, written in place
Return SetValue(db.Qr(...)), If SetValue(db.Qr(...)) = ... Then, index = F(db.Qr(index, 21)), db = F(db.Qr(1, 21)) the write-back placement: the setter is called before the return, before the block, or before the assignment stores
In a Structure: If SetValue(Qr(NextIndex(), 2)), If SetValue(Me(i)); With s (ByRef structure) / With F (structure field) the local function above, with self.set_Qr(tmp, …), self[i] = argv, s.set_Qr(…) / withBlock.set_Qr(…)

CodeConverter/CSharp/ByRefArguments/README.md has a "What the write-back writes to" section. It maps each rule to its code and source, explains why the field rule is sound, and describes the call-graph refinement.

Decisions

  1. Resolved (option 1, sound): a field is reused only if FieldWriteAnalysis proves the call can't change it. In the issue's exact repro the module is now declared without a modifier (Module Euro_Str, Friend, VB's default), since the issue doesn't show its declaration. That keeps the issue's expected output. With a Public Module, its Public fields could be written by other assemblies, so they'd be copied (var tmp = Euro_Str.Db;).
  2. Locals and parameters are now sound too. Lambdas in the same method (with any kind of write), ByRef parameter aliases and Static locals are accounted for.
  3. Temporaries are all named tmp (as the converter's existing container copy was) and typed var.
  4. Changed expectations, both for the better:
    • BinaryExpressionRefParameterAsync no longer copies the local array wideArray into tmp, since nothing can change it during the call. Issue567ExtendedAsync still copies its fields, because the callee reassigns them. This PR's own VB -> C#: Property Getter is used instead of Setter for ref argument #909 test now declares its module Friend.
    • The follow-ups' TypeNamedLikeAByRefParameterIsNotPassedAsync: Inc(GetH(New H().Q).Q) now evaluates GetH(...) once into tmp and writes back to that object, as VB does, instead of calling GetH again for the write-back.
    • MethodStatementTests.WithBlockWithNullConditionalAccessAsync (from the follow-ups, above).

#909: tests

  • Conversion tests (ByRefTests):
    • the issue's exact repro;
    • each output shape above;
    • which fields are reused (ReadOnly, Private never written, written only in a constructor or initializer, Friend without InternalsVisibleTo) and which are copied (written elsewhere, Public, structure);
    • each kind of write: For, For Each, ReDim, Erase, Mid, a late-bound argument, a lambda in a constructor, another instance's field written in a constructor, a shared field written in an instance constructor or another type's constructor;
    • Friend fields with InternalsVisibleTo;
    • intrinsic operators reused; late-bound and user-defined ones copied;
    • a Module's parameterized property (a static setter call);
    • a default property on Me and on MyBase, and a local array, used directly as the container;
    • a parameterized property and Me(i) in a Structure's local function, and in With over a ByRef structure parameter and a structure field.
  • Self-verifying ByRefParameterizedPropertyTests.vb (38 facts, which log getter, setter, index and receiver calls):
    • the issue repro;
    • index arguments, receivers, plain property receivers and default property indexes are each evaluated once;
    • named and omitted optional index arguments;
    • implicit Me and Me.;
    • a local or field index written by another ByRef argument, by a lambda in the expression, or by a lambda the called method runs;
    • a local index changed by a For loop in a lambda the call runs, a Static local index changed by a recursive call, and an auto-property backing field index changed through the property;
    • a ByRef parameter index the call changes through its alias;
    • a Shared parameterized property, a target in a field initializer, and a local in a field initializer's lambda changed by another lambda;
    • a Double formatted for an index (d & "", CStr(d)) by a call that changes the current culture;
    • a property passed as a ByRef extension method receiver;
    • a field receiver, or a field index, that the called method reassigns;
    • a ReadOnly parameterized property, which isn't written back;
    • two setters written back in reverse order;
    • Return, If, and an assignment to the index or the receiver;
    • a default property written back through MyBase;
    • a structure's ReadOnly and constructor-only fields used as indexes while the call replaces the whole structure;
    • structure receivers in an array, in a field, in a Shared field, in a written local, as a field receiver of a parameterized property, and returned by a function (copied, like VB).
  • Self-verifying ByRefParameterizedPropertyInStructureTests.vb (9 facts): a parameterized or default property in a Structure's If/While condition and operand, With Me, and With over a structure field, a ByRef structure parameter and a class local.
  • ByRefParameterizedPropertyOptionStrictOffTests.vb: an Object index and an Integer property passed to a ByRef String.

Suite

  • Full suite on net10.0 (with --blame-hang) at this PR's tip 7c244dd: 2019 passed, 5 skipped, 0 failed, with no hang.
  • Baseline master (cd6dd93), measured the same way: 1926 passed, 5 skipped, 0 failed. That's +93 tests (Always use project context for conversion #9's follow-ups, VB -> C#: Property Getter is used instead of Setter for ref argument #909 and review rounds 5 and 6), and no other differences except the changed expectations listed under Decisions.
  • Every commit builds. The merge commit b22e784 builds but fails the one test whose expectation the next commit updates (TypeNamedLikeAByRefParameterIsNotPassedAsync; see Decisions).
  • The intermittent test-host crash/hang in MultiFileSolutionAndProjectTests.ConvertVbLibraryOnlyAsync reported earlier on this PR was an unrelated MSBuild node-reuse issue, now fixed on master. It didn't recur on this branch after merging master.

Review round 5

No new bugs. Declined: the nitpick that the field analysis's Lazy caches an exception and its scan doesn't observe cancellation.

Round 4 review fixes

  • A structure's instance fields are always copied, including ReadOnly and constructor-only ones (the bug repro is a self-verifying test).
  • The element-access container follows the receiver rules instead of always being copied, so Me(i, 5) no longer gives var tmp = this, and MyBase.Item(i) no longer gives var tmp = base; (CS0175). Both are pinned by tests. A late-bound element access still copies its container.
  • Not changed (nitpick): the analysis's Lazy caches an exception, and its scan doesn't observe cancellation.

Round 3 review fixes

  • FieldWriteAnalysis is built once per project. Before, it was cached per compilation, and each document has its own: a 7-document project built it 7 times and scanned the whole project 6 times. Now it's 1 and 1 (measured with a temporary counter, not committed). This is a pure refactor (no output change). There's no test pinning it, because the seam would need a production counter.
  • Operators and conversions reused only between culture-free types (the culture repro above).
  • A local in a lambda in a field or property initializer is checked against the other lambdas there.
  • VariableWrites: an argument without a known parameter counts as a write on purpose.
  • The setter call renames the getter call's last identifier, which removed unreachable arms. IsSharedDeclaration lost a dead arm too.
  • The ByRef extension receiver path is tested with a plain property. A parameterized property there is a gap (below).

Coverage of changed lines

Uncovered lines, all defensive or rare:

  • ByRefTargetTemporaries.IsReusable(IArgumentOperation): DefaultValue (the converter only fills in an omitted argument when the property is overloaded) and the fallback (ParamArray or unmapped argument, which is copied).
  • FieldWriteAnalysis: the ancestor loop's fall-through return false.

#909: known gaps / out of scope

  • Late-bound SetValue(o.Qr(1)) with o As Object converts to ((dynamic)o).Qr(1), which throws RuntimeBinderException and isn't written back. This already happened before this PR; review found it. A fix needs NewLateBinding.LateGet/LateSet for both the read and the write-back, which isn't small. It's documented in the README.
  • A ParamArray parameterized property's declaration converts to invalid set_PA(params int[] idx, string value) (CS0231). That's in the declaration converter, which this PR doesn't touch, and it's documented.
  • BumpLong(GetArr()(Next1())) with an Integer array and a ByRef Long parameter isn't written back, because IsRefArrayAcces only treats an element as one when its array is passed inline. This already happened before this PR. Fixing it changes how every array element argument is classified, so it's documented rather than fixed here.
  • The receiver of an extension method that takes it ByRef has an empty NoneOperation in Roslyn's VB operation tree. So a parameterized property there still converts to this.Qr(2) (CS1061), and a receiver like GetC().Plain is evaluated twice. A fix would rebuild the target from symbols and syntax. Documented.
  • A parameterized property named [Optional] converts to invalid C#. That's unrelated to ByRef and in code this PR doesn't touch.

🤖 Generated with Claude Code

https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg

A pure refactor so the next commit can add a parameter before the
captured ByRef parameters, and generate another name that can't clash
with the result's. IsInStructAndUsesThis now takes any VB node, as
HoistAndCallLocalFunctionAsync does, and a duplicated summary is
dropped.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
In a Structure, a local function can't use `this` (CS1673). Where a
ByRef write-back needed one (operands, If/ElseIf and loop conditions,
block headers, Dim declarators, compound or receiver-target
assignments) and the call used an instance member, the write-back was
moved after the statement instead: compiling, but late. Loop conditions
still used the local function and gave CS1673.

The local function now takes `ref S self`, is called with `ref this`,
and its body uses `self` for `this`. The converted body qualifies every
instance member with `this` (including generic and extension calls), so
replacing `this` covers them; nested local functions get `ref self`.
C# allows `ref this` wherever VB allows `Me` in a structure: methods,
accessors, constructors, iterators and async methods. Its only illegal
context, a readonly member (CS1605), can't come from VB, and VB doesn't
allow `Me` in a structure's lambdas (BC36638), so no case is left that
needs a conversion error.

The two struct conversion tests pinned the late write-back; their
expectations now pin the local function, which self-verifying tests show
has VB's timing. They're renamed, since they no longer keep the
statement placement.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
A With block's implicit receiver is an IInstanceReferenceOperation too,
so a call on a local's members inside With in a Structure got an unused
ref S self parameter. Only ContainingTypeInstance references count now.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
A local function can't use a ref local (CS8175). `With Inner`, where
Inner is a structure field, declares `ref var withBlock = ref Inner;`,
so a ByRef write-back in the block that took the local function didn't
compile, in a class as well as (since the previous commits) in a
Structure.

References to a ref local made for a side-effect-free expression are now
annotated with its type. The local function takes each one in its body
as a ref parameter of the same name, as it already does for the
enclosing method's ByRef parameters, and is called with `ref withBlock`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
VB passes a copy of a Structure's Me to a ByRef parameter, taken when
the call evaluates its arguments. In `Return Inc(P) + ValueOf(Me)`, the
copy (`var args = this;`) was hoisted before the statement, so it
missed Inc's write-back: VB returned 2 and C# 1. The same happened
after AndAlso. This existed before this PR.

Me was never considered to need the local function, which is right for
a class (its copy is the same reference whenever it's taken) but not for
a structure. A structure's Me now takes the local function like any
other temporary, so the copy is made in place (`var args = self;`).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
7a2e552 counted only ContainingTypeInstance references, so the implicit
receiver of With Me (which is this) no longer counted and the local
function used this (CS1673). Decide from the converted body instead:
it qualifies every instance member with this, so it contains a this
exactly when the local function needs ref self.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
74c5ded passed every ref local the local function's body referenced,
including a With block's withBlock declared inside a lambda argument,
which doesn't exist at the call (CS0103). Skip names declared within
the body: they're already in scope there.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
With b, where b is a ByRef parameter, reuses b directly as the receiver,
but the parameter reference is in the With header, so the local
function didn't take it as a ref parameter and used it (CS1628). This
existed before; the CS8175 fix for ref locals is its sibling. Resolve a
With block's implicit receiver to the With expression's operations when
collecting the enclosing method's ByRef parameters.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
Pure refactor. An annotation's data can only be a string, so the type
was stored as text and parsed again. The annotation instance stays on
every copy of the node, so key the type by it instead.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
Pure refactor, so the ByRef write-back for icsharpcode#909 can build the same setter call.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
…code#909)

A parameterized property (not the default one) becomes get_X/set_X methods
in C#, and the ByRef argument converted to the getter call. The write-back
reused that call as the assignment target, giving `get_X(...) = arg` (CS0131).
Like VB (LocalRewriter_Call.vb sets the second use's access kind to Set),
write back by calling the setter with the same index arguments and the value.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
VB reads a ByRef property argument before the call and writes it after,
evaluating its receiver and index arguments only once (UseTwiceRewriter.vb).
The C# read and write-back each evaluated them, so e.g. `db.Qr(NextIndex())`
called NextIndex twice, and `GetC().Plain` called GetC twice.

Hoist a part into a temporary only where its second value could differ:
anything but a constant, Me, or a local, parameter or field that the
enclosing expression doesn't write. Existing simple output is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
Copying a structure receiver such as `cells(NextIndex())` into a temporary
made the write-back set the property on the copy, losing it. Like VB's
UseTwiceRewriter, keep a structure variable in place and copy only the parts
that locate it: the array and indexes, or the reference holding the field.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
Cover the cases coverage showed untested: a structure local written by
another argument, an index local assigned in a lambda, an omitted optional
index before a given one, and a parenthesized index.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
A ParamArray parameterized property can't be written back (its C# setter
would need params before the value), and ParamArray elements don't map one
to one onto C# arguments, so copy them like any other non-constant. ByRef
arguments and assignment targets are never parenthesized or converted.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
Pure refactor: ByRefTargetTemporaries asks IFieldMutationOracle whether a
field read for a ByRef target can change while the call runs. The first
implementation keeps the current assumption (it can't), so the next commit
can replace it with a whole-compilation analysis, and later a call graph.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
VB evaluates a ByRef property target's receiver and index arguments once,
so a field the called method reassigns keeps its old value for the
write-back. The converter read such a field again, so e.g. a callee that
replaced `_db` made the write-back go to the new object.

FieldWriteAnalysis answers IFieldMutationOracle soundly for the whole
compilation, once: a field can't change during any call if it's Const or
ReadOnly, or if only this compilation can write it and nothing does outside
construction of what holds it. Otherwise it's copied to a temporary.

The icsharpcode#909 repro's module is now declared as in VB's default (Friend), like
the issue's code, which doesn't show it. With a Public module its Public
fields could be written by other assemblies, so they'd be copied.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
Like a field, a local or parameter used as a ByRef target's index was only
copied when the enclosing expression wrote it. The call can also change one
by running a lambda from the same method that assigns it, or through a
ByRef parameter's alias. Copy those too, so the rule is sound.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
Found in review: a late-bound `o.Qr(1)` passed ByRef converts to a dynamic
method call that throws at runtime, and isn't written back. A fix needs the
late-binding helpers for both the read and the write-back, so it's left out.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
Pins each kind of write FieldWriteAnalysis looks for, and each kind of
construction it allows, found untested by coverage.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
`index = F(db.Qr(index, 21))` and `db = F(db.Qr(1, 21))`: VB writes back
through the index and receiver as they were before the assignment.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
Pure move, next to ByRefArgumentHoister, which is their only user. Their
README section already lives in ByRefArguments/README.md.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
Pure refactor: FieldWriteAnalysis's list of VB constructs that store to a
variable moves to VariableWrites, so ByRefTargetTemporaries can use the same
one for locals.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
A Shared parameterized property, a structure field receiver of a
parameterized property, a structure returned by a function (copied, like
VB), a target in a field initializer, Friend fields with InternalsVisibleTo,
and a shared field written by another type's constructor.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
ByRefTargetTemporaries only saw ByRef arguments and assignments, so a lambda
the call runs could change an index local with a For loop (or For Each,
ReDim, Erase, Mid) and the write-back used the new value. Use the same
VariableWrites as FieldWriteAnalysis.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
Static locals, auto-property backing fields, every kind of write and
intrinsic operators. #9's gap about re-evaluating a receiver is fixed here,
and two pre-existing gaps are added.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
Pure refactor: the getter call always arrives qualified (the simplifier
reduces it later), so the bare-name and unsupported-shape arms were
unreachable. Renaming the rightmost identifier handles any shape without
them. Pins a Module's parameterized property, whose converted call is static.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
Pure refactor: an argument without a known parameter counts as a write on
purpose, not by `null is not RefKind.None`. IsSharedDeclaration only gets
field declarations and property statements, so drop its dead default arm.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
`db.Qs(d & "")` and `db.Qs(CStr(d))` were reused, but formatting a number
reads the current culture, which the call can change: VB's setter got "1.5"
and the C# one "1,5" after the call switched to de-DE. The same goes for
Date conversions, string comparison and Like.

Reuse an intrinsic operator or conversion only between numeric, Boolean,
Char and enum types (or their nullables), plus identity, widening reference
and boxing conversions, which only change the static type.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
A ByRef target inside a lambda in a field initializer has no enclosing
method block, so no lambda was searched for writes, and a local the call
could change through another lambda was reused. Search the outermost
enclosing method or lambda, which holds every scope a local can be written in.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
Covers the write-back hoisted outside any argument list. A parameterized
property, or a receiver with side effects, as a ByRef extension receiver
can't be handled the same way: Roslyn gives that receiver an empty
NoneOperation. Documented as a gap.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
Pure refactor (no output change). Each document is converted with its own
compilation after expanding its root, so caching per compilation scanned the
whole project once per document that asked about a field: measured 7
analyses and 6 scans converting a 7-document project, now 1 and 1.
VBToCSProjectContentsConverter creates it, like typeToInheritors, and fields
are matched by documentation ID across the documents' compilations.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg

# Conflicts:
#	CodeConverter/CSharp/ExpressionNodeVisitor.cs
A structure's instance field was reused when it was ReadOnly or only written
in a constructor, but assigning the whole structure (`gs = New S(9)`)
overwrites every field, so a call that replaced the structure made the
write-back use the new value. Treat any instance field of a value type as
changeable.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
`SetValue(Me(i, 5))` gave `var tmp = this; ... tmp[i, 5] = arg`, because the
container of every ByRef element access was copied before
ByRefTargetTemporaries could see it was reusable. Apply the receiver rules to
the container too, so Me, and a local array or object that the call can't
change, are used directly. Without a write-back the container is evaluated
once anyway, so it isn't copied.

BinaryExpressionRefParameterAsync: `wideArray` is a local the call can't
change, so its write-back uses it directly instead of a `tmp` copy.
Issue567ExtendedAsync is unchanged: the callee reassigns those fields, so
they're still copied.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
Copying an element access's container unconditionally gave
`var tmp = base;` for `SetValue(MyBase.Item(i))` (CS0175). Since the
container follows the receiver rules (fae13b0), MyBase is used directly:
`base[i] = argvalue`. Pins it with a conversion and a self-verifying test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
067bc7f resolved a With block's implicit receiver to the whole With
expression, so a ByRef parameter that only the With header used (With
arr(i), With GetBox(b)) became an unused ref parameter whenever the
header was evaluated into withBlock. Decide from the converted body
instead, as for this: a parent ByRef parameter is passed when its name
is used there. This also removes a null-operation precedence slip.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
Every annotation comes from Mark, which records the type, so a miss is
a bug; a null type would only surface later as broken output.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
Brings in #9's struct `ref this` local functions, With ref locals and
ByRef parameters passed as ref parameters, and their tests.

Conflicts:
- ByRefTests.cs: both sides added tests at the end; kept both sets, and
  #10's BinaryExpressionRefParameterAsync expectation.
- ByRefArguments/README.md: kept #10's gaps, dropped the Structure CS1673
  gap that #9 fixed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
Conflicts: master's On Error Resume work threads an ErrUsage from
VBToCSProjectContentsConverter through VisualBasicConverter and
DeclarationNodeVisitor to CommonConversions, where this branch threads
the once-per-project FieldWriteAnalysis to ExpressionNodeVisitor. Kept
both: each is created once per project and passed alongside the other.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
VB evaluates a With expression once. For a structure variable it then
works on the variable in place, but for a class it keeps the reference,
so reassigning the variable inside the block doesn't change the object
the block uses. ref var withBlock = ref b followed the reassignment
(VB "1,0", C# "0,1"). This existed before this branch.

Only a value (or unconstrained) type now gets a ref local. Changed
expectations, both class types:
- MethodStatementTests.WithBlockWithNullConditionalAccessAsync:
  ref var withBlock = ref _Data; -> var withBlock = _Data;
- ByRefTests.ByRefParameterOnlyInAWithHeaderIsNotPassedAsync:
  var withBlock = arr[i]; so the local function takes no withBlock.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
The suggested gap, MyBase.GetHashCode() in a hoisted argument in a
Structure, isn't valid VB: the source gives BC30044 ('MyBase' is not
valid within a structure), so there's no conversion to get wrong.
Record that in the README rather than listing it as a gap.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
#9 now passes `ref this`, With ref locals and ByRef parameters to the
write-back local function. Pin that a parameterized property's setter
write-back and its index temporaries go through those: `self.set_Qr(tmp,
...)`, `self[i] = ...` for `Me(i)`, and `withBlock`/`s` for a With over a
structure field or ByRef parameter, in If and While conditions and in an
operand. No converter change was needed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
Brings in passing only the ByRef parameters the local function uses, and
copying a With block's class reference instead of taking a ref to it.
No conflicts; #10's expectations are unchanged by them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
879fd38 matched a parent ByRef parameter by name in the converted body,
case-insensitively, so a type named like the parameter counted as a use:
H.S beside <Out> ByRef h As H passed ref h (CS0269, unassigned out
parameter), and New H() beside ByRef h As Integer passed an unused ref h.

The candidates now come from the parameters the VB operations reference,
with a With block's implicit receiver resolved to its With expression, as
before 879fd38. The converted body is then used only to drop candidates
it no longer mentions, i.e. a header evaluated into withBlock. Names
compare ordinally, since the converter writes a parameter reference with
its declared casing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
Brings in taking the local function's ByRef parameter candidates from the
VB operations, filtered by the names in the C# body, and #9's merge of
master. No conflicts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
…assed test

#9's new test expected `GetH(new H().Q).Q` read and then written back by
calling `GetH` again. This branch's receiver temporaries evaluate it once,
as VB does (UseTwiceRewriter), and write back to the same object:
`var tmp = GetH(new H().Q); ... tmp.Q = argv1;`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
`ByRef [class] As Box` converts to `@class`, and CsEscapedIdentifier's
token keeps the `@` in its ValueText. RefParametersUsedIn compared the
body's names with the unescaped `p.Name`, so the parameter wasn't passed
and the local function used it directly (CS1628). Compare against the
escaped name, and declare and pass the parameter with the same escaped
identifier, so the tree binds as its text does (`ref @params`).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
In `With arr(i)`, `Inc(Take(New With {.i = 1}, .Inner).P)` with a ByRef
`i` gave `localInc(ref int i)`: the body's `new { i = 1 }` counted as a
use of `i`. A NameEquals name is a member name, like a NameColon one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
In `With arr(i)`, `Inc(Take(New Box With {.i = 1}, .Inner).P)` with a
ByRef `i` gave `localInc(ref int i)`: the body's `new Box() { i = 1 }`
counted as a use of `i`. The left side of an object initializer's
assignment is a member name, like a NameEquals one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
@GrahamTheCoder
GrahamTheCoder merged commit c130098 into icsharpcode:master Nov 18, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

VB -> C#: Property Getter is used instead of Setter for ref argument VB -> C#: out param is set after return

2 participants