Repository navigation
Write back ByRef parameterized properties through the setter, evaluating receiver and indexes once - #1326
Merged
GrahamTheCoder merged 61 commits intoNov 18, 2026
Conversation
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
Pure refactor, from review. 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
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
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
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
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
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
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
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
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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) andmasterwith merge commits. The only conflicts were master'sErrUsageand this PR'sFieldWriteAnalysisbeing threaded through the same constructors; both are kept.ByRef write-back follow-ups (from #9, after
c8c3931)ref this. A local function in a struct can't usethis(CS1673). Where the call uses an instance member, the local function takesref S self, is called withref this, and its body usesself:int localInc(ref S self) { int argv = self.P; var ret = Inc(ref argv); self.P = argv; return ret; }thenif (b && localInc(ref this) > x).If/ElseIf, block headers,Dimdeclarators and compound or receiver-target assignments. It also fixes struct loop conditions, which gave CS1673.selfis needed is decided from the converted body: it qualifies every instance member withthisbefore simplification, soWith Meis covered too, and aWithon a local isn't.ref thisis legal in every context VB can reach. VB has no read-only members (CS1605), noMyBasein a structure (BC30044) and noMein a structure's lambdas (BC36638). Shared members keep a parameterless local function.Withref locals and ByRef parameters are passed asrefparameters.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 arefparameter of the same name. Ref locals declared inside the body (e.g. inside a lambda argument) aren't passed.Withreceiver (With b : Inc(.X)).Withblock's implicit receiver resolved to theWithexpression. The converted body then drops any it no longer mentions (e.g. a header evaluated intowithBlock), 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.Sbeside<Out> ByRef h As H, which gave CS0269) isn't passed, and neither is an unusedref h.Withover a class-typed variable copies the reference:var withBlock = b;instead ofref var withBlock = ref b;, which followed a reassignment ofbinside the block (VB keeps the original object). Only a value type or unconstrained type parameter gets a ref local. Changed expectation:MethodStatementTests.WithBlockWithNullConditionalAccessAsync.Mepassed ByRef after a write-back (Return Inc(P) + ValueOf(Me)) takes the local function, so the copy ofMeis taken at the call: VB returns 2, and C# returned 1 before.ByRefWriteBackPlacementTests.vb(struct evaluation order,Withover structure fields,With Me,Withinside a lambda argument,Withover ByRef parameters and a reassigned class variable, anOutparameter named like its type, ByRef parameters with keyword names, a struct'sMepassed ByRef). Conversion tests inByRefTests:Structure…PassThisToTheLocalFunctionAsync(3),StructureWithBlockOnALocalDoesNotPassThisAsync,StructureWithMePassesThisToTheLocalFunctionAsync,StructureSharedMemberDoesNotPassThisAsync,WithBlockRefLocalIsPassedToTheLocalFunctionAsync,RefLocalDeclaredInsideTheLocalFunctionIsNotPassedAsync,WithByRefParameterIsPassedToTheLocalFunctionAsync,ByRefParameterOnlyInAWithHeaderIsNotPassedAsync,TypeNamedLikeAByRefParameterIsNotPassedAsync,KeywordNamedByRefParametersArePassedToTheLocalFunctionAsync,AnonymousTypeMemberNamedLikeAByRefParameterIsNotPassedAsync,ObjectInitializerMemberNamedLikeAByRefParameterIsNotPassedAsync,StructureMePassedByRefAfterAWriteBackTakesTheLocalFunctionAsync.CodeConverter/CSharp/ByRefArguments/README.md):h1.P = F(h2.P)withh1 Is h2);Newargument in an assignment (WF = New W(WF.Name)), and ByRef arguments ofNewin a block header, which write back after the block;For … Step, re-evaluated each iteration (not ByRef-specific);ReadOnlyauto-property passed ByRef in a constructor or initializer isn't written back;ph…placeholder, CS0103);Inc(InnerProp.P)with a structure-returning property (CS1612), andSelect Case Inc(P)withCase Inc(P)(CS0825).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 testKeywordNamedByRefParametersArePassedToTheLocalFunctionAsyncand the self-verifyingByRefParametersWithKeywordNamesArePassedToTheLocalFunction; both were red with CS1628 first.bcdfa5f(ugly output): an anonymous-type memberNew With {.i = 1}counted as a use of a ByRefi, which gave an unusedref int i.NameEqualsnames are now member names, likeNameColonones. 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 memberNew Box With {.i = 1}counted as a use of a ByRefi, which gave an unusedref int i. The left side of an assignment in an object initializer is now a member name. Test:ObjectInitializerMemberNamedLikeAByRefParameterIsNotPassedAsync, red first.nameofis still passed asref.7c244dd: 2019 passed, 5 skipped, 0 failed, no hang.#909: root cause
A parameterized property (not the default one) converts to
get_Qr/set_Qrmethods. A ByRef argumentDb.Qr(CourseBuffer, 21)converts to the getter call.HoistByRefDeclaration(nowByRefArguments/ByRefArgumentHoister) used that converted target as the write-back's assignment target, which gaveDb.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 fromRewriteByRefArgumentWithCopyBackinLocalRewriter_Call.vb). The C# read and the write-back each evaluated them. Sodb.Qr(NextIndex(), 1),GetC().Plainandother(NextIndex())ranNextIndex()/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 toCommonConversions.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, inCSharp/ByRefArguments/with the other ByRef pieces): when there is a write-back, it hoists into atmponly the parts whose second evaluation could give a different value. Simple output is unchanged.Me, and intrinsic unary or binary operators or conversions on parts that aren't copied (i + 1), when everything involved is numeric,Boolean,Charor 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 involvingStringorDatecan read the current culture, which the call can change (d & ""gives1.5before a call that switches to de-DE and1,5after it); an operator onObjectis late bound; a user-defined one runs user code. Those are copied.ByValparameter 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 inVariableWrites, whichFieldWriteAnalysisuses too: an assignment, compound assignment, ByRef or late-bound argument,For/For Eachcontrol variable,ReDim,EraseorMidstatement.ByRefparameter is always copied, since it aliases a variable the call might reach. AStaticlocal is always copied, since it outlives the call like a field.IFieldMutationOracle.MayChangeDuringCall(field, call)says the call could change it (see below).Me(i, 5)staysthis[i, 5]andMyBase.Item(i)staysbase[i](it used to givevar tmp = base;, CS0175).ReadOnlyproperty (VB doesn't copy back) is already evaluated once.FieldWriteAnalysis : IFieldMutationOracleanswers once per project:VBToCSProjectContentsConvertercreates it (liketypeToInheritors) and passes it down toByRefArgumentHoister. Each document is converted with its own compilation (afterWithExpandedRootAsync), 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:Const, orReadOnlyand not an instance field of a structure; orPrivate, orFriendwith noInternalsVisibleTo), 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, evenReadOnlyor only set in its constructor, because assigning the whole structure (s = New S(9)) overwrites it.The
callparameter 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
refparameter: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] = argvforMe(i), andwithBlock.set_Qr(…)/s.set_Qr(…)in aWithover a structure field or ByRef structure parameter. No extra code was needed for this; tests pin it.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;_dband_readOnlyIndexReadOnly)_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)(aPublicfield)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 VBQr((i), 2),Qr(i + 1, -i)(locali, implicitMe)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)tmp, e.g.var tmp = Conversions.ToInteger(Operators.AddObject(o, 1));Qr(_Idx, 1)(auto-property backing field),Qr(index, 1)(Static index)tmpother.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] = argvalueSetValueAndIndex(other.Qr(i, 2), i), oriassigned by a lambda in the methodvar tmp4 = i;…other.set_Qr(tmp4, 2, argvalue5)db.Qr(fieldNumber:=21, tableBuffer:=x),db.WithDefault()value:when an index argument is named or omitted, e.g.db.set_WithDefault(value: argvalue)cells(NextIndex()).Text,GetHolder(h).Cell.Text(Cella structure)GetHolder(h)goes in atmp;cells[tmp].Text = arg/tmp.Cell.Text = arg, written in placeReturn SetValue(db.Qr(...)),If SetValue(db.Qr(...)) = ... Then,index = F(db.Qr(index, 21)),db = F(db.Qr(1, 21))If SetValue(Qr(NextIndex(), 2)),If SetValue(Me(i));With s(ByRef structure) /With F(structure field)self.set_Qr(tmp, …),self[i] = argv,s.set_Qr(…)/withBlock.set_Qr(…)CodeConverter/CSharp/ByRefArguments/README.mdhas 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
FieldWriteAnalysisproves 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 aPublic Module, itsPublicfields could be written by other assemblies, so they'd be copied (var tmp = Euro_Str.Db;).ByRefparameter aliases andStaticlocals are accounted for.tmp(as the converter's existing container copy was) and typedvar.BinaryExpressionRefParameterAsyncno longer copies the local arraywideArrayintotmp, since nothing can change it during the call.Issue567ExtendedAsyncstill 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.TypeNamedLikeAByRefParameterIsNotPassedAsync:Inc(GetH(New H().Q).Q)now evaluatesGetH(...)once intotmpand writes back to that object, as VB does, instead of callingGetHagain for the write-back.MethodStatementTests.WithBlockWithNullConditionalAccessAsync(from the follow-ups, above).#909: tests
ByRefTests):ReadOnly,Privatenever written, written only in a constructor or initializer,FriendwithoutInternalsVisibleTo) and which are copied (written elsewhere,Public, structure);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;Friendfields withInternalsVisibleTo;Module's parameterized property (a static setter call);Meand onMyBase, and a local array, used directly as the container;Me(i)in a Structure's local function, and inWithover a ByRef structure parameter and a structure field.ByRefParameterizedPropertyTests.vb(38 facts, which log getter, setter, index and receiver calls):MeandMe.;Forloop in a lambda the call runs, aStaticlocal index changed by a recursive call, and an auto-property backing field index changed through the property;ByRefparameter index the call changes through its alias;Sharedparameterized property, a target in a field initializer, and a local in a field initializer's lambda changed by another lambda;Doubleformatted for an index (d & "",CStr(d)) by a call that changes the current culture;ReadOnlyparameterized property, which isn't written back;Return,If, and an assignment to the index or the receiver;MyBase;ReadOnlyand constructor-only fields used as indexes while the call replaces the whole structure;Sharedfield, in a written local, as a field receiver of a parameterized property, and returned by a function (copied, like VB).ByRefParameterizedPropertyInStructureTests.vb(9 facts): a parameterized or default property in a Structure'sIf/Whilecondition and operand,With Me, andWithover a structure field, a ByRef structure parameter and a class local.ByRefParameterizedPropertyOptionStrictOffTests.vb: anObjectindex and anIntegerproperty passed to a ByRefString.Suite
net10.0(with--blame-hang) at this PR's tip7c244dd: 2019 passed, 5 skipped, 0 failed, with no hang.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.b22e784builds but fails the one test whose expectation the next commit updates (TypeNamedLikeAByRefParameterIsNotPassedAsync; see Decisions).MultiFileSolutionAndProjectTests.ConvertVbLibraryOnlyAsyncreported 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
Lazycaches an exception and its scan doesn't observe cancellation.Round 4 review fixes
ReadOnlyand constructor-only ones (the bug repro is a self-verifying test).Me(i, 5)no longer givesvar tmp = this, andMyBase.Item(i)no longer givesvar tmp = base;(CS0175). Both are pinned by tests. A late-bound element access still copies its container.Lazycaches an exception, and its scan doesn't observe cancellation.Round 3 review fixes
FieldWriteAnalysisis 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.VariableWrites: an argument without a known parameter counts as a write on purpose.IsSharedDeclarationlost a dead arm too.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-throughreturn false.#909: known gaps / out of scope
SetValue(o.Qr(1))witho As Objectconverts to((dynamic)o).Qr(1), which throwsRuntimeBinderExceptionand isn't written back. This already happened before this PR; review found it. A fix needsNewLateBinding.LateGet/LateSetfor both the read and the write-back, which isn't small. It's documented in the README.ParamArrayparameterized property's declaration converts to invalidset_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 anIntegerarray and aByRef Longparameter isn't written back, becauseIsRefArrayAccesonly 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.NoneOperationin Roslyn's VB operation tree. So a parameterized property there still converts tothis.Qr(2)(CS1061), and a receiver likeGetC().Plainis evaluated twice. A fix would rebuild the target from symbols and syntax. Documented.[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