From a2ea3dd7dd06cd98cb18de9e4a02a947dafeacd4 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 00:27:20 +0000 Subject: [PATCH 01/47] Add design for converting On Error and Resume statements Design only, no behaviour change. Covers the VB lowering rules, the C# constraints, per-statement guard output shapes, and the decisions on Err usage, loop headers and secondary errors. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_019FEr8GzCY8KvPQb6eDtmhX --- CodeConverter/CSharp/OnError/README.md | 209 +++++++++++++++++++++++++ 1 file changed, 209 insertions(+) create mode 100644 CodeConverter/CSharp/OnError/README.md diff --git a/CodeConverter/CSharp/OnError/README.md b/CodeConverter/CSharp/OnError/README.md new file mode 100644 index 000000000..7eb57a0e0 --- /dev/null +++ b/CodeConverter/CSharp/OnError/README.md @@ -0,0 +1,209 @@ +# VB → C# unstructured error handling (`On Error`, `Resume`) — design + +Status: **design only, nothing here is implemented yet.** Tracks [icsharpcode/CodeConverter#426](https://github.com/icsharpcode/CodeConverter/issues/426). +Today only one shape is converted (`LambdaConverter.GetWithConvertedGotosOrNull`); everything else is converted statement by statement and marked with `#error`. + +Sources: +* VB: [`LocalRewriter_UnstructuredExceptionHandling.vb`](https://github.com/dotnet/roslyn/blob/main/src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_UnstructuredExceptionHandling.vb) (the lowering, with pseudo-code of the emitted method), the `RegisterUnstructuredExceptionHandlingResumeTarget` calls in the sibling `LocalRewriter_*.vb` files (which statements are resume points), and the [On Error](https://learn.microsoft.com/dotnet/visual-basic/language-reference/statements/on-error-statement) / [Resume](https://learn.microsoft.com/dotnet/visual-basic/language-reference/statements/resume-statement) docs. +* C#: [the `goto` statement](https://learn.microsoft.com/dotnet/csharp/language-reference/language-specification/statements#13104-the-goto-statement) (a label is only in scope within its block, so no jumping into a block or a `try`) and [exception filters](https://learn.microsoft.com/dotnet/csharp/language-reference/statements/exception-handling-statements#exception-filters). +* Every behaviour in "Requirements" was checked by compiling and running VB (.NET 10). Every C# shape in "Output shapes" was hand-written, run, and compared with the VB output, except where marked *not spiked*. + +## Requirements + +### VB + +A method containing `On Error` or `Resume` is compiled as one `Try` around the whole body, with three hidden locals: + +| Local | Meaning | +|---|---| +| active handler | none, resume-next, or one of the method's handler labels. Set by each `On Error` statement **when it executes**. | +| resume target | non-zero while "in a handler", i.e. from an error being caught until `Resume*` or `On Error GoTo -1`. | +| current statement | index of the statement being executed, only tracked if the method contains `Resume` / `Resume Next` / `On Error Resume Next`. | + +The single catch is `Catch ex As Exception When activeHandler <> 0 And resumeTarget = 0`. Consequences: + +* The active handler is runtime state, not lexical: `If flag Then On Error Resume Next` changes how every later statement behaves. +* Any exception is caught, including ones thrown deep inside callees. +* An error while in a handler fails the filter and propagates to the caller. As it is a filter, nothing is unwound first. +* The resume point is the innermost statement. Each declarator of `Dim a = F(), b = G()` is its own resume point. After `If c Then Boom()` fails, `Resume` re-runs `Boom()` without re-testing `c`. +* A failing condition resumes at the next resume point in source order, which is usually **inside** the block: + + | Failing expression | `Resume Next` continues at | + |---|---| + | `If` / `ElseIf` condition | first statement of that branch | + | `While` / `Do While` condition (tested at the top) | first statement of the body | + | `Loop Until` / `Loop While` condition (tested at the bottom) | after the loop | + | `Select Case` expression | after `End Select` | + | `Case` expression | first statement of that case | + | `For` start value, `For Each` collection | the body, once, with a default loop variable; then after the loop | + +* `Using`, `SyncLock` and any other statement lowered to a compiler-generated `Try` is a single resume point: an error inside resumes after the block, and the dispose/unlock runs. `On Error` can't appear inside them, in a method with `Try`, or in lambdas, iterators and async methods. +* `Err`: + * set on every caught error; + * cleared by every `On Error` statement and every `Resume*` statement; + * cleared on leaving the method only if it is still in a handler. So after `On Error Resume Next` swallows an error, `Err` stays set, even after the method returns. +* Code that runs into a handler label without an error is ordinary code: an error in it is caught and enters the handler from the top. This includes cleanup code reached by `Resume Cleanup` while the same handler is still active: if the cleanup fails, the handler runs again, resumes to the cleanup again, and can loop forever. + +### C# + +* `goto` can leave a block, a `try` or a `catch`, but can't enter one. So a method-level catch can never resume in the middle of a loop or `If`. +* Iterators and async methods are compiled to state machines that can re-enter nested blocks, but not after an exception: an exception leaving `MoveNext` finishes the iterator, and `yield` isn't allowed in a `try` that has a `catch`. +* `catch (Exception ex) when (flag)` matches VB's filter, including not unwinding when it's false. +* Local functions can capture locals, but not `ref`/`out` parameters. +* Locals are block scoped and must be definitely assigned. VB locals are method-lifetime and zero-initialised, so declaring them earlier as `= default` is exact. + +## Approach + +Every idea that catches at method level needs to jump back in, which needs the whole body flattened to a `switch` in a loop. Instead, **catch at the statement that fails**. Then nothing needs to jump inwards: + +| VB | C#, inside the failing statement's own `catch` | +|---|---| +| `Resume Next` | leave the catch | +| `Resume` | `goto` a label directly before that `try` (same block) | +| `Resume L` / `GoTo L`, `L` at method level | `goto L` (out of a catch is legal) | +| handler code | a local function called from the catch. An exception in it propagates, like VB's "in a handler". | +| `Exit Sub` / `Return` in the handler | the local function returns "exit", the catch returns | + +The method keeps its structure, loops stay loops, and the cost is proportional to how much of the method is covered by a resuming handler. + +### Model + +A pass over the method body builds a model before any statement is converted, so the statement visitors don't each need to know the rules: + +* **Active handler per statement**: none, resume-next, or a handler label. Static when every `On Error` statement is a direct child of the method body and no label/`GoTo` crosses the regions between them. Otherwise *dynamic*: a local records the handler and the catches filter on it. +* **Handler regions**: for each handler label, the statements from the label to where control leaves, and the set of ways it leaves: `Resume Next`, `Resume`, `Resume L`, `GoTo L`, exit, falls off the end. +* **Guards**: the resume points that have an active handler (per the table in "VB" above). +* **Hoisted locals**: locals declared within a guard and used outside it. +* **`Err` is used**: see below. + +### Output shapes + +Chosen per method, simplest first. `…` is where the `Err` calls go when `Err` is used. + +1. **Structured.** One `On Error GoTo H` covering a run of method-level statements, `H` at method level, and the handler never resumes into the covered statements (it exits, falls off the end, or does `Resume L`/`GoTo L` to a method-level label after the covered statements). + + ```csharp + try + { + // covered statements + } + catch (Exception ex) + { + // handler + } + // statements from L onwards + ``` + This is the existing conversion, generalised, with locals hoisted (fixes the existing `RemainingScopeIssueCharacterizationAsync` output). + +2. **Resume next.** The active handler is resume-next. Each guard becomes + + ```csharp + try { Statement(); } catch { } + ``` + * `If` condition: `bool cond = true; try { cond = …; } catch { }` then `if (cond)`. `ElseIf` chains become nested `if`/`else` so each condition has somewhere to go. + * Loop condition: a local function, so the loop stays a loop: `bool Cond() { try { return …; } catch { return true; } }` and `while (Cond())`. Bottom-tested conditions return whichever value leaves the loop. + * `Using`, `SyncLock`, `Select Case` and `For`/`For Each`: one guard around the whole statement, with the statements inside guarded individually where VB makes them resume points (not inside `Using`/`SyncLock`). A failing header skips the block. + * `Case` expressions: *not spiked*. Only matters when the case expressions aren't constants, where the converter already emits `when` clauses or an `if` chain. + +3. **Handler function.** `On Error GoTo H` where the handler resumes into the covered statements. The handler becomes a local function and each guard calls it: + + ```csharp + void H() { /* handler */ } + try { Statement(); } catch { H(); } + ``` + If the handler leaves in more than one way, it returns which: + + ```csharp + s3: try { Statement(); } catch { switch (H()) { case OnErrorAction.Resume: goto s3; case OnErrorAction.Exit: return; } } + ``` + Labels are only emitted for `Resume`. A method that reaches the handler label without an error calls `H()` there as an ordinary statement. + +4. **Dynamic.** The active handler isn't statically known. Same guards, filtered: `catch (Exception) when (resumeNext)`, with `resumeNext` (or an `int` when there are several handlers) assigned where the `On Error` statements were. + +5. **Fallback.** Anything else keeps today's behaviour, statement-by-statement conversion plus `#error`: + * the handler jumps to a label inside a nested block; + * `On Error GoTo -1`; + * a handler local function would need to capture a `ref`/`out` parameter. + + A flattened `switch`-in-a-loop state machine would cover these, but the output is something nobody would keep. + +Alternatives considered: +* *Iterator of thunks*: `IEnumerable Steps() { …; yield return () => Statement(); … }` driven by `foreach (var step in Steps()) try { step(); } catch { }`. It works (the iterator survives because the exception is thrown by the driver, not inside `MoveNext`) and is one line per statement, but lambdas can't capture `ref`/`out` parameters, `Return`/`Exit`/`GoTo` need extra plumbing, it allocates per statement, and stepping through it is unpleasant. +* *`Guard(() => Statement())` helper* (issue comment 6): same capture limits. Not factored out to start with; the inline `try`/`catch` is the only form. +* *Filter that inspects the stack trace* (issue comment 6): not needed, VB catches errors from callees too. + +## Decisions + +### `Err` is only maintained when it seems to be used + +`ProjectData.SetProjectError(ex)` / `ClearProjectError()` are emitted only in methods that reference `Err` (`Microsoft.VisualBasic.Information.Err`). Then: + +* each catch starts with `SetProjectError(ex)`; +* `ClearProjectError()` goes where an `On Error` or `Resume*` statement was, and on leaving a handler by exit. + +Otherwise catches are bare `catch { }` and need no `Microsoft.VisualBasic` reference. + +Known difference: a caller or callee that reads `Err` set by a method which doesn't itself mention `Err` will see it unset. The check could be widened to the containing type or the project if this turns out to matter. + +The existing structured conversion emits `catch { }` followed by `Information.Err().Number`, which reads 0 at runtime (see `BasicGotoAsync`); under this rule it gets the `SetProjectError` call. + +### Throwing loop headers skip the loop + +VB runs the body once with a default loop variable. C# output skips the loop (one guard around the whole statement). Not worth lowering loops for. + +### Secondary errors propagate + +A *secondary error* is one raised in code that runs after the handler has finished but while that same handler is still the active one: + +```vb + On Error GoTo H + Work() +Cleanup: + conn.Close() ' a failure here is a secondary error + Exit Sub +H: + Log(Err.Description) + Resume Cleanup +``` + +The same applies to handler code reached without an error (no `Exit Sub` before the label). + +VB re-enters `H`, which here means log, close, fail, log, close … forever. The structured shape puts the cleanup after the `try`, so in C# the secondary error propagates to the caller. This is a deliberate difference: looping forever is never what was meant. + +Where the author did deal with it in the usual ways, the model already has it right and there's no difference: +* `On Error Resume Next` or `On Error GoTo 0` at the start of the cleanup: the cleanup has a different active handler, so it gets resume-next guards or none. +* cleanup that can't fail (only exits, jumps and assignments of locals/constants). + +### Warn when the handler looks written for re-entry + +The remaining case is a handler that relies on being entered a second time. That can't be decided in general, but, like the `Err` check, a cheap test catches what people actually write. Emit `#warning` on the `catch` when both hold: + +1. a secondary error is possible: the code after the resume label (or the handler code, when it can be reached without an error) is still covered by the handler and contains something that can throw; +2. the handler has a **re-entry guard**: a condition (`If`, `Select Case`, loop condition, `If(…)`) reading a local, field or property that is assigned in the handler or in the code from 1. For example `attempts += 1 : If attempts > 3 Then Exit Sub`, or `If cleaningUp Then Exit Sub` with `cleaningUp = True` in the cleanup. + +Conditions on `Err.Number` alone don't count: they nearly always distinguish kinds of first error, and warning on them would be noise. `Erl` could be added as a signal if it turns up in practice. + +Suggested text: `#warning Conversion: in VB an error in the code after 'Cleanup' re-enters this handler; here it propagates to the caller`. + +When the warning would fire, the handler-function shape is the exact alternative (guard each cleanup statement with a call to the handler). Whether to switch to it automatically instead of warning is open, see below. + +## Open questions + +* `#warning` vs a comment: `#warning` matches the existing `#error` convention and is visible in the build, but breaks builds that treat warnings as errors. +* On a detected re-entry guard: warn (proposed), or emit the exact handler-function shape? +* Scope of the `Err` check: method (proposed), containing type, or project. +* Formatting: the guards rely on `try { … } catch { }` staying on one line. If the formatter expands them, shape 2 is four lines per statement. + +## Where each part will live + +To be filled in as it's implemented. Intended split, all in this directory: + +| Requirement | Class | +|---|---| +| Active handler per statement, handler regions, exits | `OnErrorModel` (analysis only, no C# syntax) | +| Which statements are resume points, and where a failing condition resumes | `ResumePoints` | +| `Err` usage, re-entry guard detection | `OnErrorModel` | +| Choosing a shape | `OnErrorShapeSelector` | +| Guards, handler local function, hoisting | one emitter per shape, called from `MethodBodyExecutableStatementVisitor` | + +Tests: a conversion test per shape in `Tests/CSharp/StatementTests/OnErrorStatementTests.cs`, and self-verifying tests in `Tests/TestData/SelfVerifyingTests/VBToCS/` that log each step and compare the VB and C# logs (the scenarios used to check this design: failing `If`/`ElseIf`/`While`/`Loop Until` conditions, `Select`, `Using`, multiple declarators, `Return`, `On Error GoTo 0`, handler with `Resume Next` inside a loop, `Resume` retry with a counter, fall-through into a handler, handler that throws, cleanup idiom, conditional `On Error`). From d428cc675c0b96eed461fecae4e595c4de363d80 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 00:34:52 +0000 Subject: [PATCH 02/47] On Error design: exact form for re-entrant handlers, widen Err detection Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_019FEr8GzCY8KvPQb6eDtmhX --- CodeConverter/CSharp/OnError/README.md | 49 +++++++++++++++----------- 1 file changed, 29 insertions(+), 20 deletions(-) diff --git a/CodeConverter/CSharp/OnError/README.md b/CodeConverter/CSharp/OnError/README.md index 7eb57a0e0..0de5fd187 100644 --- a/CodeConverter/CSharp/OnError/README.md +++ b/CodeConverter/CSharp/OnError/README.md @@ -93,7 +93,7 @@ Chosen per method, simplest first. `…` is where the `Err` calls go when `Err` } // statements from L onwards ``` - This is the existing conversion, generalised, with locals hoisted (fixes the existing `RemainingScopeIssueCharacterizationAsync` output). + This is the existing conversion, generalised, with locals hoisted (fixes the existing `RemainingScopeIssueCharacterizationAsync` output). When the handler is written for re-entry, the statements after `L` get their own `try` too (see "Secondary errors"). 2. **Resume next.** The active handler is resume-next. Each guard becomes @@ -136,14 +136,21 @@ Alternatives considered: ### `Err` is only maintained when it seems to be used -`ProjectData.SetProjectError(ex)` / `ClearProjectError()` are emitted only in methods that reference `Err` (`Microsoft.VisualBasic.Information.Err`). Then: +`ProjectData.SetProjectError(ex)` / `ClearProjectError()` are emitted in a converted method when either holds: + +* its containing type (all partial parts) references `Err` (`Microsoft.VisualBasic.Information.Err`); +* the project contains an **`Err` helper**: a method that references `Err` but has no `On Error` statement of its own, so it can only be reading an error that some other method caught (typically a shared `LogError()` called from handlers anywhere). + +The helper search is one pass per compilation, cached: find identifiers named `Err`, bind only those, and check the containing method for `On Error` statements. + +When `Err` is maintained: * each catch starts with `SetProjectError(ex)`; * `ClearProjectError()` goes where an `On Error` or `Resume*` statement was, and on leaving a handler by exit. Otherwise catches are bare `catch { }` and need no `Microsoft.VisualBasic` reference. -Known difference: a caller or callee that reads `Err` set by a method which doesn't itself mention `Err` will see it unset. The check could be widened to the containing type or the project if this turns out to matter. +Known difference: `Err` read through reflection, late binding, or from another project isn't seen. The existing structured conversion emits `catch { }` followed by `Information.Err().Number`, which reads 0 at runtime (see `BasicGotoAsync`); under this rule it gets the `SetProjectError` call. @@ -151,7 +158,7 @@ The existing structured conversion emits `catch { }` followed by `Information.Er VB runs the body once with a default loop variable. C# output skips the loop (one guard around the whole statement). Not worth lowering loops for. -### Secondary errors propagate +### Secondary errors: propagate, unless the handler is written for re-entry A *secondary error* is one raised in code that runs after the handler has finished but while that same handler is still the active one: @@ -168,30 +175,31 @@ H: The same applies to handler code reached without an error (no `Exit Sub` before the label). -VB re-enters `H`, which here means log, close, fail, log, close … forever. The structured shape puts the cleanup after the `try`, so in C# the secondary error propagates to the caller. This is a deliberate difference: looping forever is never what was meant. - -Where the author did deal with it in the usual ways, the model already has it right and there's no difference: -* `On Error Resume Next` or `On Error GoTo 0` at the start of the cleanup: the cleanup has a different active handler, so it gets resume-next guards or none. -* cleanup that can't fail (only exits, jumps and assignments of locals/constants). +VB re-enters `H`, which here means log, close, fail, log, close … forever. Looping forever is never what was meant, so by default only the code before the first resume label is in the `try`, and a secondary error propagates to the caller. -### Warn when the handler looks written for re-entry +The exact form is cheap, because the handler never resumes into the middle of the cleanup: split the covered statements into **segments** at the labels the handler resumes to, and give each segment its own `try` calling the handler: -The remaining case is a handler that relies on being entered a second time. That can't be decided in general, but, like the `Err` check, a cheap test catches what people actually write. Emit `#warning` on the `catch` when both hold: +```csharp +OnErrorAction H() { /* handler */ } +try { Work(); } catch { if (H() == OnErrorAction.Exit) return; } +Cleanup: +try { conn.Close(); return; } catch { if (H() == OnErrorAction.Exit) return; goto Cleanup; } +``` -1. a secondary error is possible: the code after the resume label (or the handler code, when it can be reached without an error) is still covered by the handler and contains something that can throw; -2. the handler has a **re-entry guard**: a condition (`If`, `Select Case`, loop condition, `If(…)`) reading a local, field or property that is assigned in the handler or in the code from 1. For example `attempts += 1 : If attempts > 3 Then Exit Sub`, or `If cleaningUp Then Exit Sub` with `cleaningUp = True` in the cleanup. +Which form is used: -Conditions on `Err.Number` alone don't count: they nearly always distinguish kinds of first error, and warning on them would be noise. `Erl` could be added as a signal if it turns up in practice. +| Situation | Output | +|---|---| +| No secondary error possible: the code after the resume label can't throw (only exits, jumps, assignments of locals/constants), or starts with its own `On Error` statement | plain structured (they're the same thing) | +| Secondary error possible and the handler has a **re-entry guard** | exact, segmented form | +| Secondary error possible, no re-entry guard | plain structured: the secondary error propagates | -Suggested text: `#warning Conversion: in VB an error in the code after 'Cleanup' re-enters this handler; here it propagates to the caller`. +A re-entry guard is a condition in the handler (`If`, `Select Case`, loop condition, `If(…)`) that reads a local, field or property which is assigned in the handler or in the code after the resume label. For example `attempts += 1 : If attempts > 3 Then Exit Sub`, or `If cleaningUp Then Exit Sub` with `cleaningUp = True` in the cleanup. Without one, a second pass through the handler does exactly what the first did, so re-entry can't have been relied on to terminate. -When the warning would fire, the handler-function shape is the exact alternative (guard each cleanup statement with a call to the handler). Whether to switch to it automatically instead of warning is open, see below. +Conditions on `Err.Number` alone don't count: they distinguish kinds of first error. No warnings are emitted in any of these cases. ## Open questions -* `#warning` vs a comment: `#warning` matches the existing `#error` convention and is visible in the build, but breaks builds that treat warnings as errors. -* On a detected re-entry guard: warn (proposed), or emit the exact handler-function shape? -* Scope of the `Err` check: method (proposed), containing type, or project. * Formatting: the guards rely on `try { … } catch { }` staying on one line. If the formatter expands them, shape 2 is four lines per statement. ## Where each part will live @@ -202,7 +210,8 @@ To be filled in as it's implemented. Intended split, all in this directory: |---|---| | Active handler per statement, handler regions, exits | `OnErrorModel` (analysis only, no C# syntax) | | Which statements are resume points, and where a failing condition resumes | `ResumePoints` | -| `Err` usage, re-entry guard detection | `OnErrorModel` | +| `Err` usage in the type, `Err` helpers in the project (cached) | `ErrUsage` | +| Re-entry guard detection, segments | `OnErrorModel` | | Choosing a shape | `OnErrorShapeSelector` | | Guards, handler local function, hoisting | one emitter per shape, called from `MethodBodyExecutableStatementVisitor` | From e7be0f255f73d4945524c6a64ef28d356766480d Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 04:46:58 +0000 Subject: [PATCH 03/47] Move On Error conversion out of LambdaConverter Pure refactor, no output change. The existing single try/catch conversion now lives in CSharp/OnError behind OnErrorMethodBodyConverter, ready for the model and shape emitters described in the README there. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_019FEr8GzCY8KvPQb6eDtmhX --- CodeConverter/CSharp/LambdaConverter.cs | 42 ++---------------- .../OnError/OnErrorMethodBodyConverter.cs | 14 ++++++ .../CSharp/OnError/PendingShapeFallback.cs | 44 +++++++++++++++++++ 3 files changed, 62 insertions(+), 38 deletions(-) create mode 100644 CodeConverter/CSharp/OnError/OnErrorMethodBodyConverter.cs create mode 100644 CodeConverter/CSharp/OnError/PendingShapeFallback.cs diff --git a/CodeConverter/CSharp/LambdaConverter.cs b/CodeConverter/CSharp/LambdaConverter.cs index 12f520017..0dd1ba7c6 100644 --- a/CodeConverter/CSharp/LambdaConverter.cs +++ b/CodeConverter/CSharp/LambdaConverter.cs @@ -1,6 +1,7 @@ using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Operations; +using ICSharpCode.CodeConverter.CSharp.OnError; namespace ICSharpCode.CodeConverter.CSharp; @@ -200,46 +201,11 @@ public async Task> ConvertMethodBodyStateme { var innerMethodBodyVisitor = await MethodBodyExecutableStatementVisitor.CreateAsync(node, _semanticModel, CommonConversions.TriviaConvertingExpressionVisitor, CommonConversions, CommonConversions.VisualBasicEqualityComparison, _withBlockLhs, _extraUsingDirectives, _typeContext, isIterator, csReturnVariable); - return await GetWithConvertedGotosOrNull(statements) ?? await ConvertStatements(statements); + return await OnErrorMethodBodyConverter.ConvertOrNullAsync(statements, ConvertStatementsAsync) ?? await ConvertStatementsAsync(statements); - async Task> ConvertStatements(IEnumerable readOnlyCollection) + async Task> ConvertStatementsAsync(IEnumerable vbStatements) { - return (await readOnlyCollection.SelectManyAsync(async s => (IEnumerable)await s.Accept(innerMethodBodyVisitor.CommentConvertingVisitor))).ToList(); - } - - async Task> GetWithConvertedGotosOrNull(IReadOnlyCollection statements) - { - var onlyIdentifierLabel = statements.OnlyOrDefault(s => s.IsKind(VBasic.SyntaxKind.LabelStatement)); - var onlyOnErrorGotoStatement = statements.OnlyOrDefault(s => s.IsKind(VBasic.SyntaxKind.OnErrorGoToLabelStatement)); - - // See https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/on-error-statement - if (onlyIdentifierLabel != null && onlyOnErrorGotoStatement != null) { - var statementsList = statements.ToList(); - var onlyIdentifierLabelIndex = statementsList.IndexOf(onlyIdentifierLabel); - var onlyOnErrorGotoStatementIndex = statementsList.IndexOf(onlyOnErrorGotoStatement); - - // Even this very simple case can generate compile errors if the error handling uses statements declared in the scope of the try block - // For now, the user will have to fix these manually, in future it'd be possible to hoist any used declarations out of the try block - if (onlyOnErrorGotoStatementIndex < onlyIdentifierLabelIndex) { - var beforeStatements = await ConvertStatements(statements.Take(onlyOnErrorGotoStatementIndex)); - var tryBlockStatements = await ConvertStatements(statements.Take(onlyIdentifierLabelIndex).Skip(onlyOnErrorGotoStatementIndex + 1)); - var tryBlock = SyntaxFactory.Block(tryBlockStatements); - var afterStatements = await ConvertStatements(statements.Skip(onlyIdentifierLabelIndex + 1)); - - var catchClauseSyntax = SyntaxFactory.CatchClause(); - - // Default to putting the statements after the catch block in case logic falls through, but if the last statement is a return, put them inside the catch block for neatness. - if (tryBlockStatements.LastOrDefault().IsKind(SyntaxKind.ReturnStatement)) { - catchClauseSyntax = catchClauseSyntax.WithBlock(SyntaxFactory.Block(afterStatements)); - afterStatements = new List(); - } - - var tryStatement = SyntaxFactory.TryStatement(SyntaxFactory.SingletonList(catchClauseSyntax)).WithBlock(tryBlock); - return beforeStatements.Append(tryStatement).Concat(afterStatements).ToList(); - } - } - - return null; + return (await vbStatements.SelectManyAsync(async s => (IEnumerable)await s.Accept(innerMethodBodyVisitor.CommentConvertingVisitor))).ToList(); } } diff --git a/CodeConverter/CSharp/OnError/OnErrorMethodBodyConverter.cs b/CodeConverter/CSharp/OnError/OnErrorMethodBodyConverter.cs new file mode 100644 index 000000000..dbc013ee9 --- /dev/null +++ b/CodeConverter/CSharp/OnError/OnErrorMethodBodyConverter.cs @@ -0,0 +1,14 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +/// +/// Entry point for converting a method body that contains On Error or Resume. See README.md in this directory. +/// +internal static class OnErrorMethodBodyConverter +{ + /// The converted body, or null when the statements should be converted one by one as usual. + public static Task> ConvertOrNullAsync(IReadOnlyCollection statements, + Func, Task>> convertStatementsAsync) => + PendingShapeFallback.ConvertOrNullAsync(statements, convertStatementsAsync); +} diff --git a/CodeConverter/CSharp/OnError/PendingShapeFallback.cs b/CodeConverter/CSharp/OnError/PendingShapeFallback.cs new file mode 100644 index 000000000..cfce3c86f --- /dev/null +++ b/CodeConverter/CSharp/OnError/PendingShapeFallback.cs @@ -0,0 +1,44 @@ +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +/// +/// Output for methods whose shape has no emitter yet: one try/catch when the method has exactly one label and one On Error GoTo, +/// otherwise null so the statements are converted one by one (each unconvertible statement gets an #error). +/// +/// +/// The try/catch ignores how the handler leaves, so it's only right for some methods. It's kept so methods that aren't handled by a shape emitter yet don't change output. +/// See https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/on-error-statement +/// +internal static class PendingShapeFallback +{ + public static async Task> ConvertOrNullAsync(IReadOnlyCollection statements, + Func, Task>> convertStatementsAsync) + { + var onlyIdentifierLabel = statements.OnlyOrDefault(s => s.IsKind(VBasic.SyntaxKind.LabelStatement)); + var onlyOnErrorGotoStatement = statements.OnlyOrDefault(s => s.IsKind(VBasic.SyntaxKind.OnErrorGoToLabelStatement)); + if (onlyIdentifierLabel == null || onlyOnErrorGotoStatement == null) return null; + + var statementsList = statements.ToList(); + var onlyIdentifierLabelIndex = statementsList.IndexOf(onlyIdentifierLabel); + var onlyOnErrorGotoStatementIndex = statementsList.IndexOf(onlyOnErrorGotoStatement); + if (onlyOnErrorGotoStatementIndex >= onlyIdentifierLabelIndex) return null; + + var beforeStatements = await convertStatementsAsync(statements.Take(onlyOnErrorGotoStatementIndex)); + var tryBlockStatements = await convertStatementsAsync(statements.Take(onlyIdentifierLabelIndex).Skip(onlyOnErrorGotoStatementIndex + 1)); + var tryBlock = SyntaxFactory.Block(tryBlockStatements); + var afterStatements = await convertStatementsAsync(statements.Skip(onlyIdentifierLabelIndex + 1)); + + var catchClauseSyntax = SyntaxFactory.CatchClause(); + + // Default to putting the statements after the catch block in case logic falls through, but if the last statement is a return, put them inside the catch block for neatness. + if (tryBlockStatements.LastOrDefault().IsKind(SyntaxKind.ReturnStatement)) { + catchClauseSyntax = catchClauseSyntax.WithBlock(SyntaxFactory.Block(afterStatements)); + afterStatements = new List(); + } + + var tryStatement = SyntaxFactory.TryStatement(SyntaxFactory.SingletonList(catchClauseSyntax)).WithBlock(tryBlock); + return beforeStatements.Append(tryStatement).Concat(afterStatements).ToList(); + } +} From 990559be9baa652a2d8c6dfa803a190aa3a5902b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 04:54:41 +0000 Subject: [PATCH 04/47] Extract the implicit method exit from VisitExitStatement Pure refactor, no output change. The On Error conversion needs the statement VB's "leave the method" means when a handler falls off the end of the method but C# would otherwise carry on after its catch. Also lets it name generated locals uniquely. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_019FEr8GzCY8KvPQb6eDtmhX --- .../MethodBodyExecutableStatementVisitor.cs | 46 +++++++++++-------- 1 file changed, 27 insertions(+), 19 deletions(-) diff --git a/CodeConverter/CSharp/MethodBodyExecutableStatementVisitor.cs b/CodeConverter/CSharp/MethodBodyExecutableStatementVisitor.cs index 6e9720622..c143965b6 100644 --- a/CodeConverter/CSharp/MethodBodyExecutableStatementVisitor.cs +++ b/CodeConverter/CSharp/MethodBodyExecutableStatementVisitor.cs @@ -525,29 +525,37 @@ public override async Task> VisitExitStatement(VBSyn return SingleStatement(SyntaxFactory.ReturnStatement()); case VBasic.SyntaxKind.FunctionKeyword: case VBasic.SyntaxKind.PropertyKeyword when node.GetAncestor()?.IsKind(VBasic.SyntaxKind.GetAccessorBlock) == true: - VBasic.VisualBasicSyntaxNode typeContainer = node.GetAncestor() - ?? (VBasic.VisualBasicSyntaxNode)node.GetAncestor() - ?? node.GetAncestor(); - var enclosingMethodInfo = typeContainer switch { - VBSyntax.LambdaExpressionSyntax e => _semanticModel.GetSymbolInfo(e).Symbol, - VBSyntax.MethodBlockSyntax e => _semanticModel.GetDeclaredSymbol(e.SubOrFunctionStatement), - VBSyntax.AccessorBlockSyntax e => _semanticModel.GetDeclaredSymbol(e.AccessorStatement), - _ => null - } as IMethodSymbol; - - if (IsIterator) return SingleStatement(SyntaxFactory.YieldStatement(SyntaxKind.YieldBreakStatement)); - - if (!enclosingMethodInfo.ReturnsVoidOrAsyncTask()) { - ExpressionSyntax expr = HasReturnVariable ? ReturnVariable : SyntaxFactory.LiteralExpression(SyntaxKind.DefaultLiteralExpression); - return SingleStatement(SyntaxFactory.ReturnStatement(expr)); - } - - return SingleStatement(SyntaxFactory.ReturnStatement()); + return SingleStatement(CreateMethodExitStatement(node)); default: return SyntaxFactory.List(_perScopeState.ConvertExit(vbBlockKeywordKind)); } } + /// + /// What leaving the method containing without a Return statement does: for a function, return its return variable or the default value. + /// + public StatementSyntax CreateMethodExitStatement(VBasic.VisualBasicSyntaxNode node) + { + VBasic.VisualBasicSyntaxNode typeContainer = node.GetAncestor() + ?? (VBasic.VisualBasicSyntaxNode)node.GetAncestor() + ?? node.GetAncestor(); + var enclosingMethodInfo = typeContainer switch { + VBSyntax.LambdaExpressionSyntax e => _semanticModel.GetSymbolInfo(e).Symbol, + VBSyntax.MethodBlockSyntax e => _semanticModel.GetDeclaredSymbol(e.SubOrFunctionStatement), + VBSyntax.AccessorBlockSyntax e => _semanticModel.GetDeclaredSymbol(e.AccessorStatement), + _ => null + } as IMethodSymbol; + + if (IsIterator) return SyntaxFactory.YieldStatement(SyntaxKind.YieldBreakStatement); + + if (!enclosingMethodInfo.ReturnsVoidOrAsyncTask()) { + ExpressionSyntax expr = HasReturnVariable ? ReturnVariable : SyntaxFactory.LiteralExpression(SyntaxKind.DefaultLiteralExpression); + return SyntaxFactory.ReturnStatement(expr); + } + + return SyntaxFactory.ReturnStatement(); + } + public override async Task> VisitRaiseEventStatement(VBSyntax.RaiseEventStatementSyntax node) { var argumentListSyntax = await node.ArgumentList.AcceptAsync(_expressionVisitor) ?? SyntaxFactory.ArgumentList(); @@ -1098,7 +1106,7 @@ public override async Task> VisitWithBlock(VBSyntax. } } - private string GetUniqueVariableNameInScope(VBasic.VisualBasicSyntaxNode node, string variableNameBase) + public string GetUniqueVariableNameInScope(VBasic.VisualBasicSyntaxNode node, string variableNameBase) { return NameGenerator.CS.GetUniqueVariableNameInScope(_semanticModel, _generatedNames, node, variableNameBase); } From 7e1aff538641b1437caa3e7c329950d1af14d9d4 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 05:21:00 +0000 Subject: [PATCH 05/47] Add the On Error model, shape selection and Err usage analysis Analysis only, nothing uses it yet, so no output change. * OnErrorModel: method-level statements, the active handler per statement (or "dynamic" when an On Error is nested or a jump crosses regions), and each handler's region and ways out. * OnErrorShapeSelector recognises every shape in the README; StructuredPlanner works out the structured layout, including the segmented form for re-entrant handlers (ThrowAnalysis, ReEntryGuard). * ErrUsage: one lazy pass per project for types that read Err and for Err helpers, threaded through to CommonConversions. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_019FEr8GzCY8KvPQb6eDtmhX --- CodeConverter/CSharp/CommonConversions.cs | 5 +- .../CSharp/DeclarationNodeVisitor.cs | 7 +- CodeConverter/CSharp/OnError/ActiveHandler.cs | 18 ++ CodeConverter/CSharp/OnError/ErrUsage.cs | 67 +++++++ CodeConverter/CSharp/OnError/HandlerExit.cs | 20 ++ CodeConverter/CSharp/OnError/HandlerRegion.cs | 15 ++ CodeConverter/CSharp/OnError/LabelName.cs | 12 ++ CodeConverter/CSharp/OnError/OnErrorModel.cs | 176 ++++++++++++++++++ CodeConverter/CSharp/OnError/OnErrorShape.cs | 21 +++ .../CSharp/OnError/OnErrorShapeSelector.cs | 37 ++++ CodeConverter/CSharp/OnError/ReEntryGuard.cs | 40 ++++ .../CSharp/OnError/StructuredPlan.cs | 26 +++ .../CSharp/OnError/StructuredPlanner.cs | 79 ++++++++ CodeConverter/CSharp/OnError/ThrowAnalysis.cs | 32 ++++ .../CSharp/VBToCSProjectContentsConverter.cs | 5 +- CodeConverter/CSharp/VisualBasicConverter.cs | 5 +- 16 files changed, 558 insertions(+), 7 deletions(-) create mode 100644 CodeConverter/CSharp/OnError/ActiveHandler.cs create mode 100644 CodeConverter/CSharp/OnError/ErrUsage.cs create mode 100644 CodeConverter/CSharp/OnError/HandlerExit.cs create mode 100644 CodeConverter/CSharp/OnError/HandlerRegion.cs create mode 100644 CodeConverter/CSharp/OnError/LabelName.cs create mode 100644 CodeConverter/CSharp/OnError/OnErrorModel.cs create mode 100644 CodeConverter/CSharp/OnError/OnErrorShape.cs create mode 100644 CodeConverter/CSharp/OnError/OnErrorShapeSelector.cs create mode 100644 CodeConverter/CSharp/OnError/ReEntryGuard.cs create mode 100644 CodeConverter/CSharp/OnError/StructuredPlan.cs create mode 100644 CodeConverter/CSharp/OnError/StructuredPlanner.cs create mode 100644 CodeConverter/CSharp/OnError/ThrowAnalysis.cs diff --git a/CodeConverter/CSharp/CommonConversions.cs b/CodeConverter/CSharp/CommonConversions.cs index 3f37f1985..b42a2bf52 100644 --- a/CodeConverter/CSharp/CommonConversions.cs +++ b/CodeConverter/CSharp/CommonConversions.cs @@ -2,6 +2,7 @@ using System.Linq.Expressions; using System.Runtime.CompilerServices; using ICSharpCode.CodeConverter.Util.FromRoslyn; +using ICSharpCode.CodeConverter.CSharp.OnError; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Editing; @@ -40,8 +41,9 @@ internal class CommonConversions public CommonConversions(Document document, SemanticModel semanticModel, TypeConversionAnalyzer typeConversionAnalyzer, SyntaxGenerator csSyntaxGenerator, Compilation compilation, - CSharpCompilation csCompilation, ITypeContext typeContext, VisualBasicEqualityComparison visualBasicEqualityComparison) + CSharpCompilation csCompilation, ITypeContext typeContext, VisualBasicEqualityComparison visualBasicEqualityComparison, ErrUsage errUsage) { + ErrUsage = errUsage; TypeConversionAnalyzer = typeConversionAnalyzer; Document = document; SemanticModel = semanticModel; @@ -55,6 +57,7 @@ public CommonConversions(Document document, SemanticModel semanticModel, } public KnownNamedTypes KnownTypes { get; } + public ErrUsage ErrUsage { get; } public record VariablePair(CSSyntax.VariableDeclaratorSyntax CsVar, VBSyntax.ModifiedIdentifierSyntax VbVar); public record VariablesDeclaration(CSSyntax.VariableDeclarationSyntax Decl, ITypeSymbol Type, List Variables); diff --git a/CodeConverter/CSharp/DeclarationNodeVisitor.cs b/CodeConverter/CSharp/DeclarationNodeVisitor.cs index 74a905a13..2392c8bd8 100644 --- a/CodeConverter/CSharp/DeclarationNodeVisitor.cs +++ b/CodeConverter/CSharp/DeclarationNodeVisitor.cs @@ -1,4 +1,4 @@ -using System.Collections.Immutable; +using System.Collections.Immutable; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.CSharp; @@ -6,6 +6,7 @@ using Microsoft.CodeAnalysis.Editing; using static Microsoft.CodeAnalysis.VisualBasic.VisualBasicExtensions; using ICSharpCode.CodeConverter.Util.FromRoslyn; +using ICSharpCode.CodeConverter.CSharp.OnError; using ISymbolExtensions = ICSharpCode.CodeConverter.Util.ISymbolExtensions; namespace ICSharpCode.CodeConverter.CSharp; @@ -42,7 +43,7 @@ internal class DeclarationNodeVisitor : VBasic.VisualBasicSyntaxVisitor _typeContext.PerScopeState; public DeclarationNodeVisitor(Document document, Compilation compilation, SemanticModel semanticModel, - CSharpCompilation csCompilation, SyntaxGenerator csSyntaxGenerator, ILookup typeToInheritors) + CSharpCompilation csCompilation, SyntaxGenerator csSyntaxGenerator, ILookup typeToInheritors, ErrUsage errUsage) { _vbCompilation = compilation; _csSyntaxGenerator = csSyntaxGenerator; @@ -54,7 +55,7 @@ public DeclarationNodeVisitor(Document document, Compilation compilation, Semant var expressionEvaluator = new ExpressionEvaluator(semanticModel, _visualBasicEqualityComparison); var nullableExpressionsConverter = new VisualBasicNullableExpressionsConverter(_semanticModel); var typeConversionAnalyzer = new TypeConversionAnalyzer(semanticModel, csCompilation, _extraUsingDirectives, _csSyntaxGenerator, expressionEvaluator, nullableExpressionsConverter); - CommonConversions = new CommonConversions(document, semanticModel, typeConversionAnalyzer, csSyntaxGenerator, compilation, csCompilation, _typeContext, _visualBasicEqualityComparison); + CommonConversions = new CommonConversions(document, semanticModel, typeConversionAnalyzer, csSyntaxGenerator, compilation, csCompilation, _typeContext, _visualBasicEqualityComparison, errUsage); var expressionNodeVisitor = new ExpressionNodeVisitor(semanticModel, _visualBasicEqualityComparison, _typeContext, CommonConversions, _extraUsingDirectives, _xmlImportContext, nullableExpressionsConverter); _accessorDeclarationNodeConverter = new AccessorDeclarationNodeConverter(semanticModel, CommonConversions, TriviaConvertingDeclarationVisitor, _additionalDeclarations, expressionNodeVisitor.ConvertMethodBodyStatementsAsync); _triviaConvertingExpressionVisitor = CommonConversions.TriviaConvertingExpressionVisitor; diff --git a/CodeConverter/CSharp/OnError/ActiveHandler.cs b/CodeConverter/CSharp/OnError/ActiveHandler.cs new file mode 100644 index 000000000..8a89d5497 --- /dev/null +++ b/CodeConverter/CSharp/OnError/ActiveHandler.cs @@ -0,0 +1,18 @@ +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +internal enum ActiveHandlerKind +{ + None, + ResumeNext, + Label +} + +/// +/// What VB does with an error raised by a statement: the value of the lowered method's "active handler" local, set by the last On Error statement executed. +/// +internal sealed record ActiveHandler(ActiveHandlerKind Kind, string Label = null) +{ + public static ActiveHandler None { get; } = new(ActiveHandlerKind.None); + public static ActiveHandler ResumeNext { get; } = new(ActiveHandlerKind.ResumeNext); + public static ActiveHandler ForLabel(string label) => new(ActiveHandlerKind.Label, LabelName.Normalize(label)); +} diff --git a/CodeConverter/CSharp/OnError/ErrUsage.cs b/CodeConverter/CSharp/OnError/ErrUsage.cs new file mode 100644 index 000000000..e0091a793 --- /dev/null +++ b/CodeConverter/CSharp/OnError/ErrUsage.cs @@ -0,0 +1,67 @@ +using Microsoft.VisualStudio.Threading; + +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +/// +/// Decides whether a converted handler must maintain Err (ProjectData.SetProjectError/ClearProjectError). +/// VB's lowering always does, but in C# it's noise unless something reads Err: the handler's own type, or an "Err helper", +/// a method with no On Error of its own that reads Err, so can only be reading an error that some other method caught. +/// +/// +/// One pass per project, done the first time a method with On Error asks, and shared by every document converted from that project. +/// Only reads count: Err.Raise and Err.Clear don't depend on an earlier error. A read in a Catch block reads that block's own error, so doesn't make an Err helper. +/// Reads through reflection, late binding or from another project aren't seen. +/// +internal sealed class ErrUsage +{ + private static readonly string[] NonReadingMembers = { "Raise", "Clear" }; + + private readonly AsyncLazy _projectErrReads; + + public ErrUsage(Project project) => + _projectErrReads = new AsyncLazy(() => FindErrReadsAsync(project), JoinableTaskFactorySingleton.Instance); + + public async Task IsMaintainedInAsync(INamedTypeSymbol containingType) + { + var reads = await _projectErrReads.GetValueAsync(); + return reads.ProjectHasErrHelper || containingType != null && reads.TypesReadingErr.Contains(containingType.GetFullMetadataName()); + } + + private record ProjectErrReads(bool ProjectHasErrHelper, HashSet TypesReadingErr); + + private static async Task FindErrReadsAsync(Project project) + { + var compilation = await project.GetCompilationAsync(); + var typesReadingErr = new HashSet(StringComparer.Ordinal); + var hasErrHelper = false; + foreach (var tree in compilation.SyntaxTrees) { + var root = await tree.GetRootAsync(); + var candidates = root.DescendantNodes().OfType() + .Where(n => string.Equals(n.Identifier.ValueText, "Err", StringComparison.OrdinalIgnoreCase) && !IsNonReadingMemberAccess(n)) + .ToArray(); + if (!candidates.Any()) continue; + var semanticModel = compilation.GetSemanticModel(tree, true); + foreach (var errRead in candidates.Where(n => IsInformationErr(semanticModel.GetSymbolInfo(n).Symbol))) { + if (semanticModel.GetEnclosingSymbol(errRead.SpanStart)?.ContainingType is { } type) { + typesReadingErr.Add(type.GetFullMetadataName()); + } + hasErrHelper |= IsErrHelperRead(errRead); + } + } + return new ProjectErrReads(hasErrHelper, typesReadingErr); + } + + private static bool IsNonReadingMemberAccess(VBSyntax.IdentifierNameSyntax errName) => + errName.Parent is VBSyntax.MemberAccessExpressionSyntax memberAccess && memberAccess.Expression == errName && + NonReadingMembers.Contains(memberAccess.Name.Identifier.ValueText, StringComparer.OrdinalIgnoreCase); + + private static bool IsInformationErr(ISymbol symbol) => + symbol is IMethodSymbol { Name: "Err" } method && method.ContainingType?.GetFullMetadataName() == "Microsoft.VisualBasic.Information"; + + private static bool IsErrHelperRead(VBSyntax.IdentifierNameSyntax errRead) + { + if (errRead.GetAncestor() != null) return false; + var method = errRead.GetAncestor(); + return method == null || !OnErrorModel.ContainsOnErrorOrResume(method); + } +} diff --git a/CodeConverter/CSharp/OnError/HandlerExit.cs b/CodeConverter/CSharp/OnError/HandlerExit.cs new file mode 100644 index 000000000..3da936836 --- /dev/null +++ b/CodeConverter/CSharp/OnError/HandlerExit.cs @@ -0,0 +1,20 @@ +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +internal enum HandlerExitKind +{ + ResumeNext, + Resume, + ResumeLabel, + GoToLabel, + ExitMethod, + FallsOffEnd, + FallsIntoLabel +} + +/// +/// A way control leaves a handler. Resume* also leaves VB's "in a handler" state and clears Err; GoTo and falling into a label do neither. +/// +internal sealed record HandlerExit(HandlerExitKind Kind, string TargetLabel = null) +{ + public bool IsJumpToLabel => Kind is HandlerExitKind.ResumeLabel or HandlerExitKind.GoToLabel or HandlerExitKind.FallsIntoLabel; +} diff --git a/CodeConverter/CSharp/OnError/HandlerRegion.cs b/CodeConverter/CSharp/OnError/HandlerRegion.cs new file mode 100644 index 000000000..c90fbfaa1 --- /dev/null +++ b/CodeConverter/CSharp/OnError/HandlerRegion.cs @@ -0,0 +1,15 @@ +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +/// +/// The statements of an On Error GoTo handler: from its label to the next method-level label or the end of the method. +/// +/// Index of the handler's label among the method-level statements, or -1 when the label is inside a block. +/// Exclusive end of the handler's statements. +internal sealed record HandlerRegion(string Label, int LabelIndex, int EndIndex, IReadOnlyList Exits) +{ + public bool IsMethodLevel => LabelIndex >= 0; + + public bool Contains(int statementIndex) => IsMethodLevel && LabelIndex <= statementIndex && statementIndex < EndIndex; + + public IEnumerable ExitLabels => Exits.Where(e => e.IsJumpToLabel).Select(e => e.TargetLabel).Distinct(); +} diff --git a/CodeConverter/CSharp/OnError/LabelName.cs b/CodeConverter/CSharp/OnError/LabelName.cs new file mode 100644 index 000000000..f5bc0bd8d --- /dev/null +++ b/CodeConverter/CSharp/OnError/LabelName.cs @@ -0,0 +1,12 @@ +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +/// +/// VB label names are case insensitive, so they're compared in a normalized form. +/// +internal static class LabelName +{ + public static string Normalize(string label) => label.ToLowerInvariant(); + + public static string Of(VBSyntax.LabelStatementSyntax label) => Normalize(label.LabelToken.Text); + public static string Of(VBSyntax.LabelSyntax label) => Normalize(label.LabelToken.Text); +} diff --git a/CodeConverter/CSharp/OnError/OnErrorModel.cs b/CodeConverter/CSharp/OnError/OnErrorModel.cs new file mode 100644 index 000000000..4f6da1912 --- /dev/null +++ b/CodeConverter/CSharp/OnError/OnErrorModel.cs @@ -0,0 +1,176 @@ +using VBasicSyntaxKind = Microsoft.CodeAnalysis.VisualBasic.SyntaxKind; + +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +/// +/// Analysis of a method body's unstructured error handling, made before any statement is converted. Produces no C# syntax. +/// +/// +/// Follows VB's lowering, where an On Error statement sets the active handler when it executes: +/// https://github.com/dotnet/roslyn/blob/main/src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_UnstructuredExceptionHandling.vb +/// The active handler is only known per statement when every On Error statement is at method level and no jump crosses between the regions they start. +/// +internal sealed class OnErrorModel +{ + private readonly Dictionary _methodLevelIndexes; + private readonly IReadOnlyDictionary _labels; + + private OnErrorModel(IReadOnlyList statements, SemanticModel semanticModel) + { + Statements = statements; + _methodLevelIndexes = statements.Select((s, i) => (s, i)).ToDictionary(x => (SyntaxNode)x.s, x => x.i); + var descendants = statements.SelectMany(s => s.DescendantNodesAndSelf(n => n is not VBSyntax.LambdaExpressionSyntax)).ToArray(); + OnErrorStatements = descendants.Where(IsOnErrorStatement).Cast().ToArray(); + ResumeStatements = descendants.OfType().ToArray(); + _labels = descendants.OfType().GroupBy(LabelName.Of).ToDictionary(g => g.Key, g => g.First()); + Jumps = descendants.Select(AsJumpOrNull).Where(j => j != null).ToArray(); + ActiveHandlers = GetStaticActiveHandlers(); + Handlers = OnErrorStatements.OfType() + .Where(s => s.IsKind(VBasicSyntaxKind.OnErrorGoToLabelStatement)) + .Select(s => LabelName.Of(s.Label)).Distinct() + .Select(label => CreateHandlerRegion(label, semanticModel)) + .ToArray(); + IsDynamic = !AreActiveHandlersStatic(); + } + + public static OnErrorModel Create(IReadOnlyCollection statements, SemanticModel semanticModel) => + new(statements.ToArray(), semanticModel); + + public static bool ContainsOnErrorOrResume(SyntaxNode node) => + node.DescendantNodes(n => n is not VBSyntax.LambdaExpressionSyntax).Any(n => IsOnErrorStatement(n) || n is VBSyntax.ResumeStatementSyntax); + + /// The method-level statements. + public IReadOnlyList Statements { get; } + + /// On Error GoTo and On Error Resume Next statements at any depth. + public IReadOnlyList OnErrorStatements { get; } + + public IReadOnlyList ResumeStatements { get; } + + /// GoTo L and Resume L at any depth. + public IReadOnlyList Jumps { get; } + + /// The handler in effect while each method-level statement runs, assuming is false. + public IReadOnlyList ActiveHandlers { get; } + + /// One region per label named by an On Error GoTo. + public IReadOnlyList Handlers { get; } + + /// The active handler can't be known per statement, so it needs recording at runtime. + public bool IsDynamic { get; } + + public bool HasOnErrorOrResume => OnErrorStatements.Any() || ResumeStatements.Any(); + + /// Index of the method-level statement that is or contains , or -1. + public int MethodLevelIndexOf(SyntaxNode node) => + node.AncestorsAndSelf().Select(a => _methodLevelIndexes.TryGetValue(a, out var i) ? i : -1).Where(i => i >= 0).DefaultIfEmpty(-1).First(); + + /// Index of the label's statement when it's at method level, otherwise -1. + public int MethodLevelIndexOfLabel(string label) => + _labels.TryGetValue(label, out var statement) && _methodLevelIndexes.TryGetValue(statement, out var i) ? i : -1; + + /// Index of the method-level statement containing the label, or -1 if there's no such label. + public int IndexContainingLabel(string label) => _labels.TryGetValue(label, out var statement) ? MethodLevelIndexOf(statement) : -1; + + /// The label as declared: C# labels are case sensitive. + public string LabelText(string label) => _labels.TryGetValue(label, out var statement) ? statement.LabelToken.Text : label; + + public HandlerRegion HandlerContaining(int statementIndex) => Handlers.FirstOrDefault(h => h.Contains(statementIndex)); + + public static bool IsOnErrorStatement(SyntaxNode node) => node is VBSyntax.OnErrorGoToStatementSyntax or VBSyntax.OnErrorResumeNextStatementSyntax; + + /// + /// Whether execution can continue past the statement, if it starts. Jumps and exits are decided by their kind, VB's flow analysis decides the rest. + /// Flow analysis doesn't know that On Error GoTo H can reach H, so for a handler's statements it can only say they're unreachable: assume they can complete. + /// + public static bool EndPointIsReachable(VBSyntax.StatementSyntax statement, SemanticModel semanticModel) + { + switch (statement) { + case VBSyntax.GoToStatementSyntax or VBSyntax.ResumeStatementSyntax or VBSyntax.ReturnStatementSyntax or VBSyntax.ThrowStatementSyntax: + case VBSyntax.ExitStatementSyntax exit when IsMethodExit(exit): + case VBSyntax.StopOrEndStatementSyntax { StopOrEndKeyword.RawKind: (int)VBasicSyntaxKind.EndKeyword }: + return false; + case VBSyntax.LabelStatementSyntax or VBSyntax.ExitStatementSyntax or VBSyntax.OnErrorGoToStatementSyntax or VBSyntax.OnErrorResumeNextStatementSyntax: + return true; + default: + var flow = semanticModel.AnalyzeControlFlow(statement); + return !flow.StartPointIsReachable || flow.EndPointIsReachable; + } + } + + public static bool IsMethodExit(VBSyntax.ExitStatementSyntax exit) => + VBasic.VisualBasicExtensions.Kind(exit.BlockKeyword) is VBasicSyntaxKind.SubKeyword or VBasicSyntaxKind.FunctionKeyword or VBasicSyntaxKind.PropertyKeyword; + + private Jump AsJumpOrNull(SyntaxNode node) => node switch { + VBSyntax.GoToStatementSyntax goTo => new Jump(goTo, LabelName.Of(goTo.Label)), + VBSyntax.ResumeStatementSyntax { Label: { } label } resume when resume.IsKind(VBasicSyntaxKind.ResumeLabelStatement) => new Jump(resume, LabelName.Of(label)), + _ => null + }; + + private IReadOnlyList GetStaticActiveHandlers() + { + var activeHandlers = new List(); + var current = ActiveHandler.None; + foreach (var statement in Statements) { + activeHandlers.Add(current); + current = statement switch { + VBSyntax.OnErrorResumeNextStatementSyntax => ActiveHandler.ResumeNext, + VBSyntax.OnErrorGoToStatementSyntax s when s.IsKind(VBasicSyntaxKind.OnErrorGoToLabelStatement) => ActiveHandler.ForLabel(s.Label.LabelToken.Text), + VBSyntax.OnErrorGoToStatementSyntax s when s.IsKind(VBasicSyntaxKind.OnErrorGoToZeroStatement) => ActiveHandler.None, + _ => current + }; + } + return activeHandlers; + } + + /// + /// A handler's statements run with that handler still active, whatever their position. On Error inside one changes what's active wherever it resumes to. + /// + private bool AreActiveHandlersStatic() + { + if (OnErrorStatements.Any(s => !_methodLevelIndexes.ContainsKey(s))) return false; + if (OnErrorStatements.Any(s => HandlerContaining(_methodLevelIndexes[s]) != null)) return false; + return Jumps.All(j => { + var sourceIndex = MethodLevelIndexOf(j.Statement); + var targetIndex = IndexContainingLabel(j.TargetLabel); + if (targetIndex < 0) return true; + var sourceHandler = HandlerContaining(sourceIndex) is { } handler ? ActiveHandler.ForLabel(handler.Label) : ActiveHandlers[sourceIndex]; + return sourceHandler == ActiveHandlers[targetIndex]; + }); + } + + private HandlerRegion CreateHandlerRegion(string label, SemanticModel semanticModel) + { + var labelIndex = MethodLevelIndexOfLabel(label); + if (labelIndex < 0) return new HandlerRegion(label, -1, -1, Array.Empty()); + + var endIndex = Enumerable.Range(labelIndex + 1, Statements.Count - labelIndex - 1) + .Where(i => Statements[i] is VBSyntax.LabelStatementSyntax).DefaultIfEmpty(Statements.Count).First(); + var regionStatements = Statements.Skip(labelIndex + 1).Take(endIndex - labelIndex - 1).ToArray(); + var regionLabels = new HashSet(regionStatements + .SelectMany(s => s.DescendantNodesAndSelf().OfType()).Select(LabelName.Of)); + + var exits = regionStatements.SelectMany(s => s.DescendantNodesAndSelf(n => n is not VBSyntax.LambdaExpressionSyntax)) + .Select(n => AsExitOrNull(n, regionLabels)) + .Where(e => e != null) + .ToList(); + if (!regionStatements.Any() || EndPointIsReachable(regionStatements.Last(), semanticModel)) { + exits.Add(endIndex == Statements.Count + ? new HandlerExit(HandlerExitKind.FallsOffEnd) + : new HandlerExit(HandlerExitKind.FallsIntoLabel, LabelName.Of((VBSyntax.LabelStatementSyntax)Statements[endIndex]))); + } + return new HandlerRegion(label, labelIndex, endIndex, exits.Distinct().ToArray()); + } + + private static HandlerExit AsExitOrNull(SyntaxNode node, HashSet regionLabels) => node switch { + VBSyntax.ResumeStatementSyntax r when r.IsKind(VBasicSyntaxKind.ResumeNextStatement) => new HandlerExit(HandlerExitKind.ResumeNext), + VBSyntax.ResumeStatementSyntax r when r.IsKind(VBasicSyntaxKind.ResumeLabelStatement) => new HandlerExit(HandlerExitKind.ResumeLabel, LabelName.Of(r.Label)), + VBSyntax.ResumeStatementSyntax => new HandlerExit(HandlerExitKind.Resume), + VBSyntax.GoToStatementSyntax g when !regionLabels.Contains(LabelName.Of(g.Label)) => new HandlerExit(HandlerExitKind.GoToLabel, LabelName.Of(g.Label)), + VBSyntax.ExitStatementSyntax e when IsMethodExit(e) => new HandlerExit(HandlerExitKind.ExitMethod), + VBSyntax.ReturnStatementSyntax => new HandlerExit(HandlerExitKind.ExitMethod), + _ => null + }; + + public sealed record Jump(VBSyntax.StatementSyntax Statement, string TargetLabel); +} diff --git a/CodeConverter/CSharp/OnError/OnErrorShape.cs b/CodeConverter/CSharp/OnError/OnErrorShape.cs new file mode 100644 index 000000000..6fba4b382 --- /dev/null +++ b/CodeConverter/CSharp/OnError/OnErrorShape.cs @@ -0,0 +1,21 @@ +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +/// +/// The output shapes from README.md, simplest first. +/// +internal enum OnErrorShapeKind +{ + /// No On Error or Resume: convert statements as usual. + None, + Structured, + ResumeNext, + HandlerFunction, + Dynamic, + Fallback +} + +/// Set when is . +internal sealed record OnErrorShape(OnErrorShapeKind Kind, StructuredPlan Structured = null) +{ + public static OnErrorShape Of(OnErrorShapeKind kind) => new(kind); +} diff --git a/CodeConverter/CSharp/OnError/OnErrorShapeSelector.cs b/CodeConverter/CSharp/OnError/OnErrorShapeSelector.cs new file mode 100644 index 000000000..01a5167db --- /dev/null +++ b/CodeConverter/CSharp/OnError/OnErrorShapeSelector.cs @@ -0,0 +1,37 @@ +using VBasicSyntaxKind = Microsoft.CodeAnalysis.VisualBasic.SyntaxKind; + +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +/// +/// Chooses the simplest output shape (README.md "Output shapes") that is right for the method. +/// +internal static class OnErrorShapeSelector +{ + public static OnErrorShape Select(OnErrorModel model, SemanticModel semanticModel) + { + if (!model.HasOnErrorOrResume) return OnErrorShape.Of(OnErrorShapeKind.None); + if (model.OnErrorStatements.Any(s => s.IsKind(VBasicSyntaxKind.OnErrorGoToMinusOneStatement))) return OnErrorShape.Of(OnErrorShapeKind.Fallback); + if (model.IsDynamic) return OnErrorShape.Of(OnErrorShapeKind.Dynamic); + if (model.Handlers.Any(h => !h.IsMethodLevel) || model.ResumeStatements.Any(r => model.HandlerContaining(model.MethodLevelIndexOf(r)) == null)) { + return OnErrorShape.Of(OnErrorShapeKind.Fallback); + } + if (model.ActiveHandlers.Contains(ActiveHandler.ResumeNext) || model.OnErrorStatements.Any(s => s is VBSyntax.OnErrorResumeNextStatementSyntax)) { + return OnErrorShape.Of(OnErrorShapeKind.ResumeNext); + } + if (StructuredPlanner.TryPlan(model, semanticModel) is { } plan) return new OnErrorShape(OnErrorShapeKind.Structured, plan); + return model.Handlers.Any(h => ResumesIntoCoveredStatements(model, h)) ? OnErrorShape.Of(OnErrorShapeKind.HandlerFunction) : OnErrorShape.Of(OnErrorShapeKind.Fallback); + } + + /// + /// Resuming into the statements a handler covers needs a way back into the middle of them, which only a handler called from each statement's catch gives. + /// Several handlers or On Error GoTo statements are also left to that shape. + /// + private static bool ResumesIntoCoveredStatements(OnErrorModel model, HandlerRegion handler) + { + var onErrorIndexes = model.OnErrorStatements.Select(model.MethodLevelIndexOf).ToArray(); + return model.Handlers.Count > 1 || handler.Exits.Any(e => + e.Kind is HandlerExitKind.Resume or HandlerExitKind.ResumeNext || + e.Kind is HandlerExitKind.ResumeLabel or HandlerExitKind.GoToLabel && model.MethodLevelIndexOfLabel(e.TargetLabel) is var target && target >= 0 && + target <= onErrorIndexes.Max()); + } +} diff --git a/CodeConverter/CSharp/OnError/ReEntryGuard.cs b/CodeConverter/CSharp/OnError/ReEntryGuard.cs new file mode 100644 index 000000000..1fc66afaa --- /dev/null +++ b/CodeConverter/CSharp/OnError/ReEntryGuard.cs @@ -0,0 +1,40 @@ +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +/// +/// Detects a handler written to cope with running again: a condition in it reads something that the handler, or the code it resumes to, assigns. +/// Without one, a second pass through the handler does exactly what the first did, so VB's re-entry would loop forever and can't have been relied on. +/// +/// Conditions on Err alone don't count: they tell kinds of first error apart. +internal static class ReEntryGuard +{ + public static bool IsPresent(IEnumerable handlerStatements, IEnumerable resumedToStatements, SemanticModel semanticModel) + { + var handlerNodes = handlerStatements.SelectMany(s => s.DescendantNodesAndSelf()).ToArray(); + var conditionReads = handlerNodes.SelectMany(GetConditions) + .SelectMany(c => c.DescendantNodesAndSelf().OfType()) + .Select(i => semanticModel.GetSymbolInfo(i).Symbol) + .Where(IsGuardStateSymbol) + .ToArray(); + if (!conditionReads.Any()) return false; + + var assigned = handlerNodes.Concat(resumedToStatements.SelectMany(s => s.DescendantNodesAndSelf())) + .OfType() + .Select(a => semanticModel.GetSymbolInfo(a.Left).Symbol) + .Where(s => s != null); + return conditionReads.Intersect(assigned, SymbolEqualityComparer.Default).Any(); + } + + private static IEnumerable GetConditions(SyntaxNode node) => node switch { + VBSyntax.IfStatementSyntax s => new[] { s.Condition }, + VBSyntax.ElseIfStatementSyntax s => new[] { s.Condition }, + VBSyntax.SingleLineIfStatementSyntax s => new[] { s.Condition }, + VBSyntax.SelectStatementSyntax s => new[] { s.Expression }, + VBSyntax.WhileStatementSyntax s => new[] { s.Condition }, + VBSyntax.WhileOrUntilClauseSyntax s => new[] { s.Condition }, + VBSyntax.TernaryConditionalExpressionSyntax s => new[] { s.Condition }, + _ => Array.Empty() + }; + + private static bool IsGuardStateSymbol(ISymbol symbol) => + symbol is ILocalSymbol or IFieldSymbol or IPropertySymbol && symbol.ContainingType?.GetFullMetadataName() != "Microsoft.VisualBasic.ErrObject"; +} diff --git a/CodeConverter/CSharp/OnError/StructuredPlan.cs b/CodeConverter/CSharp/OnError/StructuredPlan.cs new file mode 100644 index 000000000..33c0b299c --- /dev/null +++ b/CodeConverter/CSharp/OnError/StructuredPlan.cs @@ -0,0 +1,26 @@ +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +/// +/// Where the parts of a structured method are, as indexes into its method-level statements. +/// +/// +/// Layout: statements before ; the protected ; statements up to the handler's label that no segment protects; the handler. +/// Plain form: a single segment, the covered statements from the On Error GoTo to the first label the handler leaves to. +/// Segmented form: also one segment per label the handler resumes to, so an error after resuming enters the handler again as in VB. +/// +/// The statement before the handler's label can run into it, making it ordinary code too. +/// The ranges that each go in their own try. +internal sealed record StructuredPlan(int OnErrorIndex, HandlerRegion Handler, IReadOnlyList Segments, bool HandlerReachedWithoutError) +{ + public bool IsSegmented => Segments.Count > 1; + public StatementRange Covered => Segments[0]; + + /// The statements between the last segment and the handler's label. + public int UnprotectedStart => Segments.Last().End; +} + +/// Method-level statements [, ), preceded by the label at (-1 for none). +internal sealed record StatementRange(int LabelIndex, int Start, int End) +{ + public bool Contains(int statementIndex) => Start <= statementIndex && statementIndex < End; +} diff --git a/CodeConverter/CSharp/OnError/StructuredPlanner.cs b/CodeConverter/CSharp/OnError/StructuredPlanner.cs new file mode 100644 index 000000000..58b363e97 --- /dev/null +++ b/CodeConverter/CSharp/OnError/StructuredPlanner.cs @@ -0,0 +1,79 @@ +using VBasicSyntaxKind = Microsoft.CodeAnalysis.VisualBasic.SyntaxKind; + +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +/// +/// Recognises the structured shape: one method-level On Error GoTo H whose handler never resumes into the statements it covers, +/// so a try around them with the handler in the catch behaves the same. +/// +/// +/// C# can't jump into a try or catch, so nothing outside a protected segment may jump into it, nor into the handler. +/// See README.md "Secondary errors" for when the statements the handler resumes to are protected too. +/// +internal static class StructuredPlanner +{ + public static StructuredPlan TryPlan(OnErrorModel model, SemanticModel semanticModel) + { + var onErrorGoTos = model.OnErrorStatements.Where(s => s.IsKind(VBasicSyntaxKind.OnErrorGoToLabelStatement)).ToArray(); + if (onErrorGoTos.Length != 1 || model.Handlers.Count != 1) return null; + var handler = model.Handlers.Single(); + var onErrorIndex = model.MethodLevelIndexOf(onErrorGoTos.Single()); + if (handler.LabelIndex < onErrorIndex) return null; + + var coverageEnd = model.OnErrorStatements.Select(model.MethodLevelIndexOf) + .Where(i => onErrorIndex < i && i < handler.LabelIndex).DefaultIfEmpty(handler.LabelIndex).Min(); + var exitLabelIndexes = handler.ExitLabels.Select(model.MethodLevelIndexOfLabel).ToArray(); + if (!handler.Exits.All(IsStructuredExit) || exitLabelIndexes.Any(i => i <= onErrorIndex || i >= handler.LabelIndex)) return null; + + var handlerReachedWithoutError = OnErrorModel.EndPointIsReachable(model.Statements[handler.LabelIndex - 1], semanticModel); + if (handlerReachedWithoutError && exitLabelIndexes.Any()) return null; + + var coveredEnd = exitLabelIndexes.Where(i => i < coverageEnd).DefaultIfEmpty(coverageEnd).Min(); + var covered = new StatementRange(-1, onErrorIndex + 1, coveredEnd); + if (!CanOnlyBeEnteredFromTheTop(model, covered) || IsJumpedIntoFromOutside(model, handler)) return null; + + var segmented = TrySegment(model, handler, covered, coverageEnd, semanticModel); + return new StructuredPlan(onErrorIndex, handler, segmented ?? new[] { covered }, handlerReachedWithoutError); + } + + private static bool IsStructuredExit(HandlerExit exit) => + exit.Kind is HandlerExitKind.ExitMethod or HandlerExitKind.FallsOffEnd or HandlerExitKind.ResumeLabel or HandlerExitKind.GoToLabel; + + /// + /// Segments only when a secondary error is possible and the handler is written for re-entry; otherwise secondary errors propagate (README.md "Secondary errors"). + /// + private static IReadOnlyList TrySegment(OnErrorModel model, HandlerRegion handler, StatementRange covered, int coverageEnd, SemanticModel semanticModel) + { + if (handler.Exits.Any(e => e.Kind == HandlerExitKind.GoToLabel)) return null; + var resumeLabelIndexes = handler.ExitLabels.Select(model.MethodLevelIndexOfLabel).Where(i => i < coverageEnd).OrderBy(i => i).ToArray(); + if (!resumeLabelIndexes.Any()) return null; + + var segments = resumeLabelIndexes + .Select((labelIndex, n) => new StatementRange(labelIndex, labelIndex + 1, n + 1 < resumeLabelIndexes.Length ? resumeLabelIndexes[n + 1] : coverageEnd)) + .ToArray(); + var resumedToStatements = segments.SelectMany(s => StatementsIn(model, s)).ToArray(); + var handlerStatements = model.Statements.Skip(handler.LabelIndex + 1).Take(handler.EndIndex - handler.LabelIndex - 1); + if (!segments.Any(s => SecondaryErrorIsPossible(StatementsIn(model, s), semanticModel)) || + !ReEntryGuard.IsPresent(handlerStatements, resumedToStatements, semanticModel) || + !segments.All(s => CanOnlyBeEnteredFromTheTop(model, s))) { + return null; + } + return new[] { covered }.Concat(segments).ToArray(); + } + + /// + /// Code that starts with its own On Error statement no longer has this handler active. + /// + private static bool SecondaryErrorIsPossible(IReadOnlyCollection statements, SemanticModel semanticModel) => + !OnErrorModel.IsOnErrorStatement(statements.FirstOrDefault(s => s is not VBSyntax.LabelStatementSyntax)) && + statements.Any(s => ThrowAnalysis.CanThrow(s, semanticModel)); + + private static IReadOnlyCollection StatementsIn(OnErrorModel model, StatementRange segment) => + model.Statements.Skip(segment.Start).Take(segment.End - segment.Start).ToArray(); + + private static bool CanOnlyBeEnteredFromTheTop(OnErrorModel model, StatementRange segment) => + model.Jumps.All(j => !segment.Contains(model.IndexContainingLabel(j.TargetLabel)) || segment.Contains(model.MethodLevelIndexOf(j.Statement))); + + private static bool IsJumpedIntoFromOutside(OnErrorModel model, HandlerRegion handler) => + model.Jumps.Any(j => handler.Contains(model.IndexContainingLabel(j.TargetLabel)) && !handler.Contains(model.MethodLevelIndexOf(j.Statement))); +} diff --git a/CodeConverter/CSharp/OnError/ThrowAnalysis.cs b/CodeConverter/CSharp/OnError/ThrowAnalysis.cs new file mode 100644 index 000000000..40325bf0a --- /dev/null +++ b/CodeConverter/CSharp/OnError/ThrowAnalysis.cs @@ -0,0 +1,32 @@ +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +/// +/// A conservative "can this statement raise an error" check, used to tell when a secondary error is impossible. +/// +/// +/// Only exits, jumps, labels and copies of constants, locals and parameters without a conversion are treated as safe. +/// Compound assignment isn't: x += 1 can overflow. +/// +internal static class ThrowAnalysis +{ + public static bool CanThrow(VBSyntax.StatementSyntax statement, SemanticModel semanticModel) => statement switch { + VBSyntax.LabelStatementSyntax or VBSyntax.GoToStatementSyntax or VBSyntax.ResumeStatementSyntax or VBSyntax.ExitStatementSyntax => false, + VBSyntax.ReturnStatementSyntax r => r.Expression != null && !IsSafeValue(r.Expression, semanticModel), + VBSyntax.AssignmentStatementSyntax a when a.IsKind(VBasic.SyntaxKind.SimpleAssignmentStatement) => + !IsLocal(a.Left, semanticModel) || !IsSafeValue(a.Right, semanticModel), + VBSyntax.LocalDeclarationStatementSyntax d => d.Declarators.Any(v => v.AsClause is VBSyntax.AsNewClauseSyntax || v.Names.Any(n => n.ArrayBounds != null) || + v.Initializer != null && !IsSafeValue(v.Initializer.Value, semanticModel)), + _ => true + }; + + private static bool IsLocal(VBSyntax.ExpressionSyntax expression, SemanticModel semanticModel) => + semanticModel.GetSymbolInfo(expression).Symbol is ILocalSymbol; + + private static bool IsSafeValue(VBSyntax.ExpressionSyntax expression, SemanticModel semanticModel) + { + if (semanticModel.GetConstantValue(expression).HasValue) return true; + var typeInfo = semanticModel.GetTypeInfo(expression); + return semanticModel.GetSymbolInfo(expression).Symbol is ILocalSymbol or IParameterSymbol && + SymbolEqualityComparer.Default.Equals(typeInfo.Type, typeInfo.ConvertedType); + } +} diff --git a/CodeConverter/CSharp/VBToCSProjectContentsConverter.cs b/CodeConverter/CSharp/VBToCSProjectContentsConverter.cs index f42879716..a3148373e 100644 --- a/CodeConverter/CSharp/VBToCSProjectContentsConverter.cs +++ b/CodeConverter/CSharp/VBToCSProjectContentsConverter.cs @@ -2,6 +2,7 @@ using System.Xml.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.VisualBasic; +using ICSharpCode.CodeConverter.CSharp.OnError; using LangVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion; namespace ICSharpCode.CodeConverter.CSharp; @@ -21,6 +22,7 @@ internal class VBToCSProjectContentsConverter : IProjectContentsConverter private readonly IProgress _progress; private readonly CancellationToken _cancellationToken; private ILookup _typeToInheritors; + private ErrUsage _errUsage; public VBToCSProjectContentsConverter(ConversionOptions conversionOptions, bool useProjectLevelWinformsAdjustments, @@ -47,6 +49,7 @@ public async Task InitializeSourceAsync(Project project) _csharpViewOfVbSymbols = (CSharpCompilation)await _csharpReferenceProject.GetCompilationAsync(_cancellationToken); _designerToResxRelativePath = project.ReadVbEmbeddedResources().ToDictionary(r => r.LastGenOutput, r => r.RelativePath); SourceProject = await WithProjectLevelWinformsAdjustmentsAsync(project); + _errUsage = new ErrUsage(SourceProject); var compilation = await project.GetCompilationAsync(_cancellationToken); #pragma warning disable RS1024 // Compare symbols correctly - analzyer bug, I'm intentionally using my own comparer, not the default ambiguous one. The default comparer wouldn't manage with cross-compilation comparison in all cases @@ -76,7 +79,7 @@ private async Task WithProjectLevelWinformsAdjustmentsAsync(Project pro public async Task SingleFirstPassAsync(Document document) { - return await VisualBasicConverter.ConvertCompilationTreeAsync(document, _csharpViewOfVbSymbols, _csharpReferenceProject, OptionalOperations, _typeToInheritors, _cancellationToken); + return await VisualBasicConverter.ConvertCompilationTreeAsync(document, _csharpViewOfVbSymbols, _csharpReferenceProject, OptionalOperations, _typeToInheritors, _errUsage, _cancellationToken); } public async Task<(Project project, List> firstPassDocIds)> GetConvertedProjectAsync(WipFileConversion[] firstPassResults) diff --git a/CodeConverter/CSharp/VisualBasicConverter.cs b/CodeConverter/CSharp/VisualBasicConverter.cs index 017c4e37b..cd93592f1 100644 --- a/CodeConverter/CSharp/VisualBasicConverter.cs +++ b/CodeConverter/CSharp/VisualBasicConverter.cs @@ -1,5 +1,6 @@ using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Editing; +using ICSharpCode.CodeConverter.CSharp.OnError; namespace ICSharpCode.CodeConverter.CSharp; @@ -7,7 +8,7 @@ internal static class VisualBasicConverter { public static async Task ConvertCompilationTreeAsync(Document document, CSharpCompilation csharpViewOfVbSymbols, Project csharpReferenceProject, - OptionalOperations optionalOperations, ILookup typeToInheritors, CancellationToken cancellationToken) + OptionalOperations optionalOperations, ILookup typeToInheritors, ErrUsage errUsage, CancellationToken cancellationToken) { document = await document.WithExpandedRootAsync(cancellationToken); var root = await document.GetSyntaxRootAsync(cancellationToken) as VBSyntax.CompilationUnitSyntax ?? @@ -20,7 +21,7 @@ public static async Task ConvertCompilationTreeAsync(Document docume var csSyntaxGenerator = SyntaxGenerator.GetGenerator(csharpReferenceProject); var semanticModel = compilation.GetSemanticModel(tree, true); var visualBasicSyntaxVisitor = new - DeclarationNodeVisitor(document, compilation, semanticModel, csharpViewOfVbSymbols, csSyntaxGenerator, typeToInheritors); + DeclarationNodeVisitor(document, compilation, semanticModel, csharpViewOfVbSymbols, csSyntaxGenerator, typeToInheritors, errUsage); var converted = await root.AcceptAsync(visualBasicSyntaxVisitor.TriviaConvertingDeclarationVisitor); return optionalOperations.MapSourceTriviaToTargetHandled(root, converted, document); From 3022b7050352cff29b31c0491248848421e2e817 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 05:21:10 +0000 Subject: [PATCH 06/47] Convert structured On Error GoTo handlers to try/catch Emits README shape 1 for one method-level On Error GoTo whose handler exits, falls off the end, or resumes/goes to a label after the covered statements (On Error GoTo 0 ends the covered statements too). Other shapes are recognised but keep their previous output for now. * Err is maintained (catch (Exception ex) + SetProjectError, and ClearProjectError at On Error/Resume statements and when the method is left from the handler) only when ErrUsage says it's read. * Locals declared in a try and used outside it are declared before it as "= default", which is exact for VB. * By default only the statements before the first resume label are protected, so an error in cleanup code propagates. When the handler has a re-entry guard and the cleanup can throw, each segment gets its own try whose catch jumps to the handler, matching VB exactly. Changed expectations: * BasicGotoAsync: the bare catch made Err.Number read 0 at runtime; the catch now records the exception, and Err is cleared after the return value is evaluated, as VB does. * RemainingScopeIssueCharacterizationAsync: "i" is hoisted, fixing the CS0103 compile error. The automated comment-order check is skipped for tests where the shape moves code (handler before cleanup, hoisted declarations). Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_019FEr8GzCY8KvPQb6eDtmhX --- CodeConverter/CSharp/LambdaConverter.cs | 8 +- .../MethodBodyExecutableStatementVisitor.cs | 13 + .../OnError/ClearErrOnReturnRewriter.cs | 54 ++ CodeConverter/CSharp/OnError/ErrStatements.cs | 43 + .../OnError/IOnErrorStatementConverter.cs | 12 + CodeConverter/CSharp/OnError/LocalHoisting.cs | 121 +++ .../OnError/OnErrorConversionContext.cs | 17 + .../OnError/OnErrorMethodBodyConverter.cs | 20 +- .../CSharp/OnError/StructuredShapeEmitter.cs | 137 ++++ .../OnError/StructuredStatementConverter.cs | 32 + .../StatementTests/OnErrorStatementTests.cs | 752 +++++++++++++++++- .../VBToCS/OnErrorStructuredTests.vb | 228 ++++++ .../VBToCS/OnErrorWithoutErrTests.vb | 48 ++ 13 files changed, 1471 insertions(+), 14 deletions(-) create mode 100644 CodeConverter/CSharp/OnError/ClearErrOnReturnRewriter.cs create mode 100644 CodeConverter/CSharp/OnError/ErrStatements.cs create mode 100644 CodeConverter/CSharp/OnError/IOnErrorStatementConverter.cs create mode 100644 CodeConverter/CSharp/OnError/LocalHoisting.cs create mode 100644 CodeConverter/CSharp/OnError/OnErrorConversionContext.cs create mode 100644 CodeConverter/CSharp/OnError/StructuredShapeEmitter.cs create mode 100644 CodeConverter/CSharp/OnError/StructuredStatementConverter.cs create mode 100644 Tests/TestData/SelfVerifyingTests/VBToCS/OnErrorStructuredTests.vb create mode 100644 Tests/TestData/SelfVerifyingTests/VBToCS/OnErrorWithoutErrTests.vb diff --git a/CodeConverter/CSharp/LambdaConverter.cs b/CodeConverter/CSharp/LambdaConverter.cs index 0dd1ba7c6..2c720f4a5 100644 --- a/CodeConverter/CSharp/LambdaConverter.cs +++ b/CodeConverter/CSharp/LambdaConverter.cs @@ -201,12 +201,8 @@ public async Task> ConvertMethodBodyStateme { var innerMethodBodyVisitor = await MethodBodyExecutableStatementVisitor.CreateAsync(node, _semanticModel, CommonConversions.TriviaConvertingExpressionVisitor, CommonConversions, CommonConversions.VisualBasicEqualityComparison, _withBlockLhs, _extraUsingDirectives, _typeContext, isIterator, csReturnVariable); - return await OnErrorMethodBodyConverter.ConvertOrNullAsync(statements, ConvertStatementsAsync) ?? await ConvertStatementsAsync(statements); - - async Task> ConvertStatementsAsync(IEnumerable vbStatements) - { - return (await vbStatements.SelectManyAsync(async s => (IEnumerable)await s.Accept(innerMethodBodyVisitor.CommentConvertingVisitor))).ToList(); - } + var onErrorContext = new OnErrorConversionContext(node, _semanticModel, CommonConversions, innerMethodBodyVisitor, _extraUsingDirectives); + return await OnErrorMethodBodyConverter.ConvertOrNullAsync(onErrorContext, statements) ?? await onErrorContext.ConvertAsync(statements); } /// diff --git a/CodeConverter/CSharp/MethodBodyExecutableStatementVisitor.cs b/CodeConverter/CSharp/MethodBodyExecutableStatementVisitor.cs index c143965b6..7cc2dfbaf 100644 --- a/CodeConverter/CSharp/MethodBodyExecutableStatementVisitor.cs +++ b/CodeConverter/CSharp/MethodBodyExecutableStatementVisitor.cs @@ -8,6 +8,7 @@ using Microsoft.CodeAnalysis.Text; using ICSharpCode.CodeConverter.Util.FromRoslyn; using ICSharpCode.CodeConverter.VB; +using ICSharpCode.CodeConverter.CSharp.OnError; using ComparisonKind = ICSharpCode.CodeConverter.CSharp.VisualBasicEqualityComparison.ComparisonKind; namespace ICSharpCode.CodeConverter.CSharp; @@ -34,6 +35,9 @@ internal class MethodBodyExecutableStatementVisitor : VBasic.VisualBasicSyntaxVi public bool HasReturnVariable => ReturnVariable != null; public VBasic.VisualBasicSyntaxVisitor>> CommentConvertingVisitor { get; } + /// Set by the On Error conversion for the shape it emits. Until then, On Error and Resume statements can't be converted. + public IOnErrorStatementConverter OnErrorStatementConverter { get; set; } + private CommonConversions CommonConversions { get; } public static async Task CreateAsync(VisualBasicSyntaxNode node, SemanticModel semanticModel, @@ -75,6 +79,15 @@ public override async Task> DefaultVisit(SyntaxNode .WithNodeInformation(node); } + public override Task> VisitOnErrorGoToStatement(VBSyntax.OnErrorGoToStatementSyntax node) => + OnErrorStatementConverter is { } converter ? Task.FromResult(converter.ConvertOnError(node)) : DefaultVisit(node); + + public override Task> VisitOnErrorResumeNextStatement(VBSyntax.OnErrorResumeNextStatementSyntax node) => + OnErrorStatementConverter is { } converter ? Task.FromResult(converter.ConvertOnError(node)) : DefaultVisit(node); + + public override Task> VisitResumeStatement(VBSyntax.ResumeStatementSyntax node) => + OnErrorStatementConverter is { } converter ? Task.FromResult(converter.ConvertResume(node)) : DefaultVisit(node); + public override async Task> VisitStopOrEndStatement(VBSyntax.StopOrEndStatementSyntax node) { return SingleStatement(SyntaxFactory.ParseStatement(ConvertStopOrEndToCSharpStatementText(node))); diff --git a/CodeConverter/CSharp/OnError/ClearErrOnReturnRewriter.cs b/CodeConverter/CSharp/OnError/ClearErrOnReturnRewriter.cs new file mode 100644 index 000000000..1c4ade844 --- /dev/null +++ b/CodeConverter/CSharp/OnError/ClearErrOnReturnRewriter.cs @@ -0,0 +1,54 @@ +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +/// +/// Clears Err at each return from a handler, since VB clears it when the method is left while in a handler. +/// +/// +/// VB evaluates the returned value first, which may read Err, so a returned value that isn't obviously independent of it +/// is returned from a try with the clear in its finally. +/// Returns inside lambdas and local functions leave those, not the method, so are left alone. +/// +internal sealed class ClearErrOnReturnRewriter : CSharpSyntaxRewriter +{ + private static readonly SyntaxAnnotation SpliceAnnotation = new(); + private readonly ErrStatements _err; + private readonly IdentifierNameSyntax _returnVariable; + + private ClearErrOnReturnRewriter(ErrStatements err, IdentifierNameSyntax returnVariable) + { + _err = err; + _returnVariable = returnVariable; + } + + public static IEnumerable Rewrite(IEnumerable statements, ErrStatements err, IdentifierNameSyntax returnVariable) + { + var rewriter = new ClearErrOnReturnRewriter(err, returnVariable); + return Splice(statements.Select(s => (StatementSyntax)rewriter.Visit(s))); + } + + public override SyntaxNode VisitReturnStatement(ReturnStatementSyntax node) + { + if (node.Expression == null || IsIndependentOfErr(node.Expression)) { + return SyntaxFactory.Block(_err.Clear().Add(node)).WithAdditionalAnnotations(SpliceAnnotation); + } + return SyntaxFactory.TryStatement(SyntaxFactory.Block(node), default, SyntaxFactory.FinallyClause(SyntaxFactory.Block(_err.Clear()))); + } + + public override SyntaxNode VisitBlock(BlockSyntax node) => + node.WithStatements(SyntaxFactory.List(Splice(node.Statements.Select(s => (StatementSyntax)Visit(s))))); + + public override SyntaxNode VisitLocalFunctionStatement(LocalFunctionStatementSyntax node) => node; + public override SyntaxNode VisitParenthesizedLambdaExpression(ParenthesizedLambdaExpressionSyntax node) => node; + public override SyntaxNode VisitSimpleLambdaExpression(SimpleLambdaExpressionSyntax node) => node; + public override SyntaxNode VisitAnonymousMethodExpression(AnonymousMethodExpressionSyntax node) => node; + + private bool IsIndependentOfErr(ExpressionSyntax expression) => + expression is LiteralExpressionSyntax or DefaultExpressionSyntax || + _returnVariable != null && expression is IdentifierNameSyntax identifier && identifier.Identifier.ValueText == _returnVariable.Identifier.ValueText; + + private static IEnumerable Splice(IEnumerable statements) => + statements.SelectMany(s => s is BlockSyntax block && block.HasAnnotation(SpliceAnnotation) ? block.Statements : (IEnumerable)new[] { s }); +} diff --git a/CodeConverter/CSharp/OnError/ErrStatements.cs b/CodeConverter/CSharp/OnError/ErrStatements.cs new file mode 100644 index 000000000..e65107f2d --- /dev/null +++ b/CodeConverter/CSharp/OnError/ErrStatements.cs @@ -0,0 +1,43 @@ +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +/// +/// The calls VB's lowering makes to keep Err up to date, or nothing when says nobody reads it. +/// +internal sealed class ErrStatements +{ + private const string CompilerServicesNamespace = "Microsoft.VisualBasic.CompilerServices"; + private readonly HashSet _extraUsingDirectives; + + public ErrStatements(bool isMaintained, HashSet extraUsingDirectives) + { + IsMaintained = isMaintained; + _extraUsingDirectives = extraUsingDirectives; + } + + public bool IsMaintained { get; } + + /// Where VB clears Err: each On Error and Resume statement, and leaving the method while in a handler. + public SyntaxList Clear() => + IsMaintained ? SyntaxFactory.SingletonList(ProjectDataCall("ClearProjectError")) : default; + + /// A catch-all, as VB catches any exception, recording it in Err first as VB's catch does. + public CatchClauseSyntax CatchClause(string exceptionVariableName, IEnumerable statements) + { + if (!IsMaintained) return SyntaxFactory.CatchClause().WithBlock(SyntaxFactory.Block(statements)); + _extraUsingDirectives.Add("System"); + var declaration = SyntaxFactory.CatchDeclaration(SyntaxFactory.IdentifierName(nameof(Exception)), SyntaxFactory.Identifier(exceptionVariableName)); + var setError = ProjectDataCall("SetProjectError", SyntaxFactory.IdentifierName(exceptionVariableName)); + return SyntaxFactory.CatchClause(declaration, null, SyntaxFactory.Block(statements.Prepend(setError))); + } + + private StatementSyntax ProjectDataCall(string methodName, params ExpressionSyntax[] arguments) + { + _extraUsingDirectives.Add(CompilerServicesNamespace); + var method = SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.IdentifierName("ProjectData"), SyntaxFactory.IdentifierName(methodName)); + return SyntaxFactory.ExpressionStatement(SyntaxFactory.InvocationExpression(method, + SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(arguments.Select(SyntaxFactory.Argument))))); + } +} diff --git a/CodeConverter/CSharp/OnError/IOnErrorStatementConverter.cs b/CodeConverter/CSharp/OnError/IOnErrorStatementConverter.cs new file mode 100644 index 000000000..d95389e53 --- /dev/null +++ b/CodeConverter/CSharp/OnError/IOnErrorStatementConverter.cs @@ -0,0 +1,12 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +/// +/// Converts the On Error and Resume statements the method body visitor meets, for the shape being emitted. +/// +internal interface IOnErrorStatementConverter +{ + SyntaxList ConvertOnError(VBSyntax.StatementSyntax onErrorStatement); + SyntaxList ConvertResume(VBSyntax.ResumeStatementSyntax resumeStatement); +} diff --git a/CodeConverter/CSharp/OnError/LocalHoisting.cs b/CodeConverter/CSharp/OnError/LocalHoisting.cs new file mode 100644 index 000000000..ec2f73363 --- /dev/null +++ b/CodeConverter/CSharp/OnError/LocalHoisting.cs @@ -0,0 +1,121 @@ +using static Microsoft.CodeAnalysis.VisualBasic.VisualBasicExtensions; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +/// +/// Declares before a try the locals that are declared in it but used after it or in the handler. +/// +/// +/// A C# local is scoped to its block, but a VB local lives for the whole method and starts zeroed, so declaring it earlier as = default is exact. +/// The declaration in the try becomes an assignment, or nothing when VB had no initializer. +/// Constants move whole. Static locals already become fields. +/// +internal sealed class LocalHoisting +{ + private readonly OnErrorConversionContext _context; + private readonly HashSet _hoisted; + + public LocalHoisting(OnErrorConversionContext context, OnErrorModel model, IEnumerable segments) + { + _context = context; + _hoisted = new HashSet(segments.SelectMany(s => FindUsedOutside(model, s)), SymbolEqualityComparer.Default); + } + + /// The declarations that go before the first try, in order. + public List Declarations { get; } = new(); + + /// + /// Converts statements that will be in a try, adding to what must be declared before it. + /// + public async Task> ConvertAsync(IEnumerable statements) + { + var converted = new List(); + foreach (var statement in statements) { + var csStatements = await _context.ConvertAsync(new[] { statement }); + converted.AddRange(statement is VBSyntax.LocalDeclarationStatementSyntax declaration ? Split(declaration, csStatements) : csStatements); + } + return converted; + } + + private IEnumerable FindUsedOutside(OnErrorModel model, StatementRange segment) + { + var declared = model.Statements.Skip(segment.Start).Take(segment.End - segment.Start) + .OfType() + .Where(d => !d.Modifiers.Any(m => m.IsKind(VBasic.SyntaxKind.StaticKeyword))) + .SelectMany(d => d.Declarators.SelectMany(v => v.Names)) + .Select(n => _context.SemanticModel.GetDeclaredSymbol(n) as ILocalSymbol) + .Where(l => l != null) + .ToArray(); + if (!declared.Any()) return declared; + var names = new HashSet(declared.Select(l => l.Name), StringComparer.OrdinalIgnoreCase); + var referencedOutside = model.Statements.Where((_, i) => !segment.Contains(i)) + .SelectMany(s => s.DescendantNodes().OfType()) + .Where(i => names.Contains(i.Identifier.ValueText)) + .Select(i => _context.SemanticModel.GetSymbolInfo(i).Symbol) + .ToArray(); + return declared.Where(l => referencedOutside.Contains(l, SymbolEqualityComparer.Default)); + } + + private IEnumerable Split(VBSyntax.LocalDeclarationStatementSyntax vbDeclaration, IEnumerable csStatements) + { + var hoistedByName = vbDeclaration.Declarators + .SelectMany(v => v.Names.Select(n => (Symbol: _context.SemanticModel.GetDeclaredSymbol(n) as ILocalSymbol, NeedsAssignment: NeedsAssignment(v, n)))) + .Where(x => x.Symbol != null && _hoisted.Contains(x.Symbol)) + .ToDictionary(x => x.Symbol.Name, x => x, StringComparer.OrdinalIgnoreCase); + if (!hoistedByName.Any()) return csStatements; + + var inPlace = new List(); + foreach (var csStatement in csStatements) { + if (csStatement is not LocalDeclarationStatementSyntax csDeclaration || + !csDeclaration.Declaration.Variables.Any(v => hoistedByName.ContainsKey(v.Identifier.ValueText))) { + inPlace.Add(csStatement); + } else if (csDeclaration.IsConst) { + Declarations.Add(csDeclaration); + } else { + inPlace.AddRange(SplitDeclaration(csDeclaration, hoistedByName)); + } + } + return inPlace; + } + + private IEnumerable SplitDeclaration(LocalDeclarationStatementSyntax csDeclaration, + Dictionary hoistedByName) + { + var inOrder = new List(); + var kept = new List(); + foreach (var variable in csDeclaration.Declaration.Variables) { + if (!hoistedByName.TryGetValue(variable.Identifier.ValueText, out var hoisted)) { + kept.Add(variable); + continue; + } + AddKept(); + Declarations.Add(DeclareDefault(variable.Identifier, hoisted.Symbol)); + if (hoisted.NeedsAssignment && variable.Initializer != null) { + inOrder.Add(SyntaxFactory.ExpressionStatement(SyntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, + SyntaxFactory.IdentifierName(variable.Identifier.WithoutTrivia()), variable.Initializer.Value.WithoutTrivia()))); + } + } + AddKept(); + return inOrder; + + void AddKept() + { + if (!kept.Any()) return; + inOrder.Add(csDeclaration.WithDeclaration(csDeclaration.Declaration.WithVariables(SyntaxFactory.SeparatedList(kept)))); + kept.Clear(); + } + } + + private LocalDeclarationStatementSyntax DeclareDefault(SyntaxToken identifier, ILocalSymbol local) + { + var declarator = SyntaxFactory.VariableDeclarator(identifier.WithoutTrivia()) + .WithInitializer(SyntaxFactory.EqualsValueClause(SyntaxFactory.LiteralExpression(SyntaxKind.DefaultLiteralExpression))); + var type = _context.CommonConversions.GetTypeSyntax(local.Type); + return SyntaxFactory.LocalDeclarationStatement(SyntaxFactory.VariableDeclaration(type, SyntaxFactory.SingletonSeparatedList(declarator))); + } + + private static bool NeedsAssignment(VBSyntax.VariableDeclaratorSyntax declarator, VBSyntax.ModifiedIdentifierSyntax name) => + declarator.Initializer != null || declarator.AsClause is VBSyntax.AsNewClauseSyntax || name.ArrayBounds != null; +} diff --git a/CodeConverter/CSharp/OnError/OnErrorConversionContext.cs b/CodeConverter/CSharp/OnError/OnErrorConversionContext.cs new file mode 100644 index 000000000..31f6593ea --- /dev/null +++ b/CodeConverter/CSharp/OnError/OnErrorConversionContext.cs @@ -0,0 +1,17 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +/// +/// What an emitter needs from the method body conversion. +/// +internal sealed record OnErrorConversionContext(VBasic.VisualBasicSyntaxNode MethodNode, SemanticModel SemanticModel, CommonConversions CommonConversions, + MethodBodyExecutableStatementVisitor Visitor, HashSet ExtraUsingDirectives) +{ + public async Task> ConvertAsync(IEnumerable statements) => + (await statements.SelectManyAsync(async s => (IEnumerable)await s.Accept(Visitor.CommentConvertingVisitor))).ToList(); + + /// The type of the member being converted: the symbol enclosing the end of the method block is the member itself. + public INamedTypeSymbol ContainingType => + SemanticModel.GetEnclosingSymbol(MethodNode.Span.End - 1) is { } symbol ? symbol as INamedTypeSymbol ?? symbol.ContainingType : null; +} diff --git a/CodeConverter/CSharp/OnError/OnErrorMethodBodyConverter.cs b/CodeConverter/CSharp/OnError/OnErrorMethodBodyConverter.cs index dbc013ee9..ad4ae264d 100644 --- a/CodeConverter/CSharp/OnError/OnErrorMethodBodyConverter.cs +++ b/CodeConverter/CSharp/OnError/OnErrorMethodBodyConverter.cs @@ -5,10 +5,24 @@ namespace ICSharpCode.CodeConverter.CSharp.OnError; /// /// Entry point for converting a method body that contains On Error or Resume. See README.md in this directory. /// +/// +/// Each shape in gets an emitter here; until it has one, its methods keep the output of . +/// internal static class OnErrorMethodBodyConverter { /// The converted body, or null when the statements should be converted one by one as usual. - public static Task> ConvertOrNullAsync(IReadOnlyCollection statements, - Func, Task>> convertStatementsAsync) => - PendingShapeFallback.ConvertOrNullAsync(statements, convertStatementsAsync); + public static async Task> ConvertOrNullAsync(OnErrorConversionContext context, IReadOnlyCollection statements) + { + var model = OnErrorModel.Create(statements, context.SemanticModel); + var shape = OnErrorShapeSelector.Select(model, context.SemanticModel); + switch (shape.Kind) { + case OnErrorShapeKind.None: + return null; + case OnErrorShapeKind.Structured: + var err = new ErrStatements(await context.CommonConversions.ErrUsage.IsMaintainedInAsync(context.ContainingType), context.ExtraUsingDirectives); + return await new StructuredShapeEmitter(context, model, shape.Structured, err).EmitAsync(); + default: + return await PendingShapeFallback.ConvertOrNullAsync(statements, context.ConvertAsync); + } + } } diff --git a/CodeConverter/CSharp/OnError/StructuredShapeEmitter.cs b/CodeConverter/CSharp/OnError/StructuredShapeEmitter.cs new file mode 100644 index 000000000..b7dbf9c8f --- /dev/null +++ b/CodeConverter/CSharp/OnError/StructuredShapeEmitter.cs @@ -0,0 +1,137 @@ +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +/// +/// Emits README.md shape 1: the covered statements in a try with the handler in its catch. +/// +/// +/// Where the handler goes depends on how it's reached and left: +/// * Only reached by an error: in the catch. When it falls off the end of the method, the catch must return rather than carry on after the try. +/// * Also reached by running into its label: after the try, as ordinary code, and the catch jumps to it past any statements in between. +/// * Segmented (re-entrant handler): after all the segments, each segment's catch jumping to it, so a secondary error re-enters it as in VB. +/// +internal sealed class StructuredShapeEmitter +{ + private readonly OnErrorConversionContext _context; + private readonly OnErrorModel _model; + private readonly StructuredPlan _plan; + private readonly ErrStatements _err; + private readonly LocalHoisting _hoisting; + private readonly string _exceptionVariableName; + + public StructuredShapeEmitter(OnErrorConversionContext context, OnErrorModel model, StructuredPlan plan, ErrStatements err) + { + _context = context; + _model = model; + _plan = plan; + _err = err; + _hoisting = new LocalHoisting(context, model, plan.Segments.Append(UnprotectedRange(plan))); + _exceptionVariableName = err.IsMaintained ? context.Visitor.GetUniqueVariableNameInScope(model.Statements[plan.OnErrorIndex], "ex") : null; + context.Visitor.OnErrorStatementConverter = new StructuredStatementConverter(err, model); + } + + private VBSyntax.StatementSyntax OnErrorStatement => _model.Statements[_plan.OnErrorIndex]; + private int HandlerLabelIndex => _plan.Handler.LabelIndex; + private string HandlerLabel => _model.LabelText(_plan.Handler.Label); + + public async Task> EmitAsync() + { + var before = WithDefaultInitializers(await ConvertRangeAsync(0, _plan.OnErrorIndex)); + var protectedAndHandler = _plan.IsSegmented ? await EmitSegmentedAsync() : await EmitPlainAsync(); + var statements = before.Concat(_err.Clear()).Concat(_hoisting.Declarations).Concat(protectedAndHandler).ToList(); + return WithoutUnreferencedLabels(statements); + } + + private async Task> EmitPlainAsync() + { + var covered = await _hoisting.ConvertAsync(StatementsIn(_plan.Covered)); + var unprotected = await _hoisting.ConvertAsync(StatementsIn(UnprotectedRange(_plan))); + var handler = await ConvertHandlerAsync(); + + if (_plan.HandlerReachedWithoutError) { + if (!unprotected.Any()) return new[] { Try(covered, Enumerable.Empty()) }.Concat(handler); + return new[] { Try(covered, GoTo(HandlerLabel)) }.Concat(unprotected).Append(Label(HandlerLabel)).Concat(handler); + } + + if (unprotected.Any() && _plan.Handler.Exits.Any(e => e.Kind == HandlerExitKind.FallsOffEnd)) { + handler.Add(_context.Visitor.CreateMethodExitStatement(OnErrorStatement)); + } + if (handler.LastOrDefault() is GotoStatementSyntax { Expression: IdentifierNameSyntax target } && IsLabel(unprotected.FirstOrDefault(), target.Identifier.ValueText)) { + handler.RemoveAt(handler.Count - 1); + } + return new[] { Try(covered, handler) }.Concat(unprotected); + } + + private async Task> EmitSegmentedAsync() + { + var statements = new List(); + foreach (var segment in _plan.Segments) { + if (segment.LabelIndex >= 0) statements.AddRange(await ConvertRangeAsync(segment.LabelIndex, segment.LabelIndex + 1)); + statements.Add(Try(await _hoisting.ConvertAsync(StatementsIn(segment)), GoTo(HandlerLabel))); + } + statements.AddRange(await _hoisting.ConvertAsync(StatementsIn(UnprotectedRange(_plan)))); + statements.Add(Label(HandlerLabel)); + statements.AddRange(await ConvertHandlerAsync()); + return statements; + } + + /// + /// VB clears Err when the method is left while in a handler. + /// + private async Task> ConvertHandlerAsync() + { + var handler = await ConvertRangeAsync(HandlerLabelIndex + 1, _plan.Handler.EndIndex); + if (!_err.IsMaintained) return handler; + var withClearedErr = ClearErrOnReturnRewriter.Rewrite(handler, _err, _context.Visitor.ReturnVariable).ToList(); + if (_plan.Handler.Exits.Any(e => e.Kind == HandlerExitKind.FallsOffEnd)) withClearedErr.AddRange(_err.Clear()); + return withClearedErr; + } + + /// + /// The converter leaves out an initializer that VB's flow analysis says isn't needed, but that analysis doesn't know a handler can run after any statement. + /// VB locals start zeroed, so = default is exact. + /// + private static List WithDefaultInitializers(List statements) => + statements.Select(s => s is LocalDeclarationStatementSyntax { IsConst: false } declaration + ? declaration.WithDeclaration(declaration.Declaration.WithVariables(SyntaxFactory.SeparatedList(declaration.Declaration.Variables.Select(v => + v.Initializer != null ? v : v.WithInitializer(SyntaxFactory.EqualsValueClause(SyntaxFactory.LiteralExpression(SyntaxKind.DefaultLiteralExpression))))))) + : s).ToList(); + + private TryStatementSyntax Try(IEnumerable statements, IEnumerable catchStatements) => + SyntaxFactory.TryStatement(SyntaxFactory.Block(statements), SyntaxFactory.SingletonList(_err.CatchClause(_exceptionVariableName, catchStatements)), null); + + /// + /// Not in a try, but its locals still need hoisting when the handler, emitted before it, uses them. + /// + private static StatementRange UnprotectedRange(StructuredPlan plan) => new(-1, plan.UnprotectedStart, plan.Handler.LabelIndex); + + private Task> ConvertRangeAsync(int start, int end) => + _context.ConvertAsync(_model.Statements.Skip(start).Take(end - start)); + + private IEnumerable StatementsIn(StatementRange segment) => + _model.Statements.Skip(segment.Start).Take(segment.End - segment.Start); + + private static StatementSyntax[] GoTo(string label) => + new StatementSyntax[] { SyntaxFactory.GotoStatement(SyntaxKind.GotoStatement, ValidSyntaxFactory.IdentifierName(label)) }; + + private static StatementSyntax Label(string label) => + SyntaxFactory.LabeledStatement(CommonConversions.CsEscapedIdentifier(label), SyntaxFactory.EmptyStatement()); + + private static bool IsLabel(StatementSyntax statement, string label) => + statement is LabeledStatementSyntax labeled && labeled.Identifier.ValueText == label; + + /// + /// The labels the handler leaves to are only needed when something still jumps to them. + /// + private List WithoutUnreferencedLabels(List statements) + { + var removableLabels = new HashSet(_plan.Handler.ExitLabels.Append(_plan.Handler.Label).Select(_model.LabelText)); + var jumpedTo = new HashSet(statements.SelectMany(s => s.DescendantNodesAndSelf()).OfType() + .Select(g => g.Expression).OfType().Select(i => i.Identifier.ValueText)); + return statements.Where(s => s is not LabeledStatementSyntax { Statement: EmptyStatementSyntax } label || + !removableLabels.Contains(label.Identifier.ValueText) || jumpedTo.Contains(label.Identifier.ValueText)) + .ToList(); + } +} diff --git a/CodeConverter/CSharp/OnError/StructuredStatementConverter.cs b/CodeConverter/CSharp/OnError/StructuredStatementConverter.cs new file mode 100644 index 000000000..0142eeb05 --- /dev/null +++ b/CodeConverter/CSharp/OnError/StructuredStatementConverter.cs @@ -0,0 +1,32 @@ +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using VBasicSyntaxKind = Microsoft.CodeAnalysis.VisualBasic.SyntaxKind; + +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +/// +/// In the structured shape, an On Error statement only clears Err: the try placement does the rest. +/// The handler's Resume L clears Err and jumps out of the catch, which C# allows. +/// +internal sealed class StructuredStatementConverter : IOnErrorStatementConverter +{ + private readonly ErrStatements _err; + private readonly OnErrorModel _model; + + public StructuredStatementConverter(ErrStatements err, OnErrorModel model) + { + _err = err; + _model = model; + } + + public SyntaxList ConvertOnError(VBSyntax.StatementSyntax onErrorStatement) => _err.Clear(); + + public SyntaxList ConvertResume(VBSyntax.ResumeStatementSyntax resumeStatement) + { + if (!resumeStatement.IsKind(VBasicSyntaxKind.ResumeLabelStatement)) { + throw new NotSupportedException("The structured shape is only chosen when the handler resumes to a label"); + } + var label = _model.LabelText(LabelName.Of(resumeStatement.Label)); + return _err.Clear().Add(SyntaxFactory.GotoStatement(SyntaxKind.GotoStatement, ValidSyntaxFactory.IdentifierName(label))); + } +} diff --git a/Tests/CSharp/StatementTests/OnErrorStatementTests.cs b/Tests/CSharp/StatementTests/OnErrorStatementTests.cs index 9641254fb..e37bb46ea 100644 --- a/Tests/CSharp/StatementTests/OnErrorStatementTests.cs +++ b/Tests/CSharp/StatementTests/OnErrorStatementTests.cs @@ -19,20 +19,30 @@ Return True End Function End Class", @"using System; using Microsoft.VisualBasic; // Install-Package Microsoft.VisualBasic +using Microsoft.VisualBasic.CompilerServices; // Install-Package Microsoft.VisualBasic internal partial class TestClass { public bool SelfDivisionPossible(int x) { + ProjectData.ClearProjectError(); try { int i = (int)Math.Round(x / (double)x); return true; } - catch + catch (Exception ex) { + ProjectData.SetProjectError(ex); + try + { - return Information.Err().Number == 6; + return Information.Err().Number == 6; + } + finally + { + ProjectData.ClearProjectError(); + } } } }"); @@ -54,9 +64,10 @@ internal partial class TestClass { public bool SelfDivisionPossible(int x) { + int i = default; try { - int i = (int)Math.Round(x / (double)x); + i = (int)Math.Round(x / (double)x); } catch { @@ -64,8 +75,739 @@ public bool SelfDivisionPossible(int x) return i != 0; } +}"); + } + + [Fact] + public async Task ErrNotUsedGivesBareCatchAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Imports System +Class TestClass + Sub Save() + On Error GoTo Failed + Console.WriteLine(""saving"") + Exit Sub +Failed: + Console.WriteLine(""failed"") + End Sub +End Class", @"using System; + +internal partial class TestClass +{ + public void Save() + { + try + { + Console.WriteLine(""saving""); + return; + } + catch + { + + Console.WriteLine(""failed""); + } + } +}"); + } + + [Fact] + public async Task ErrUsedInAnotherMemberOfTheTypeAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Imports System +Class TestClass + Sub Save() + On Error GoTo Failed + Console.WriteLine(""saving"") + Exit Sub +Failed: + LogError() + End Sub + + Sub LogError() + Console.WriteLine(Err.Description) + End Sub +End Class", @"using System; +using Microsoft.VisualBasic; // Install-Package Microsoft.VisualBasic +using Microsoft.VisualBasic.CompilerServices; // Install-Package Microsoft.VisualBasic + +internal partial class TestClass +{ + public void Save() + { + ProjectData.ClearProjectError(); + try + { + Console.WriteLine(""saving""); + return; + } + catch (Exception ex) + { + ProjectData.SetProjectError(ex); + + LogError(); + ProjectData.ClearProjectError(); + } + } + + public void LogError() + { + Console.WriteLine(Information.Err().Description); + } +}"); + } + + [Fact] + public async Task ErrUsedInAnErrHelperElsewhereInTheProjectAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Imports System +Class TestClass + Sub Save() + On Error GoTo Failed + Console.WriteLine(""saving"") + Exit Sub +Failed: + ErrorLog.Write() + End Sub +End Class + +Module ErrorLog + Sub Write() + Console.WriteLine(Err.Description) + End Sub +End Module", @"using System; +using Microsoft.VisualBasic; // Install-Package Microsoft.VisualBasic +using Microsoft.VisualBasic.CompilerServices; // Install-Package Microsoft.VisualBasic + +internal partial class TestClass +{ + public void Save() + { + ProjectData.ClearProjectError(); + try + { + Console.WriteLine(""saving""); + return; + } + catch (Exception ex) + { + ProjectData.SetProjectError(ex); + + ErrorLog.Write(); + ProjectData.ClearProjectError(); + } + } +} + +internal static partial class ErrorLog +{ + public static void Write() + { + Console.WriteLine(Information.Err().Description); + } +}"); + } + + [Fact] + public async Task ErrReadOnlyInACatchBlockElsewhereIsNotAnErrHelperAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Imports System +Class TestClass + Sub Save() + On Error GoTo Failed + Console.WriteLine(""saving"") + Exit Sub +Failed: + Console.WriteLine(""failed"") + End Sub +End Class + +Module Other + Sub Run() + Try + Console.WriteLine(""run"") + Catch + Console.WriteLine(Err.Description) + End Try + End Sub +End Module", @"using System; +using Microsoft.VisualBasic; // Install-Package Microsoft.VisualBasic + +internal partial class TestClass +{ + public void Save() + { + try + { + Console.WriteLine(""saving""); + return; + } + catch + { + + Console.WriteLine(""failed""); + } + } } -1 target compilation errors: -CS0103: The name 'i' does not exist in the current context"); + +internal static partial class Other +{ + public static void Run() + { + try + { + Console.WriteLine(""run""); + } + catch + { + Console.WriteLine(Information.Err().Description); + } + } +}"); + } + + [Fact] + public async Task HoistsLocalsUsedInTheHandlerAndAfterAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Imports System +Class TestClass + Function Parse(s As String) As Integer + On Error GoTo Failed + Dim stage = ""parse"", unused = 1 + Dim result As Integer = Integer.Parse(s) + Dim items(2) As String + Const Doubled = 2 + Return result * Doubled +Failed: + Console.WriteLine(stage & items.Length & Doubled) + Return result + End Function +End Class", @"using System; + +internal partial class TestClass +{ + public int Parse(string s) + { + string stage = default; + int result = default; + string[] items = default; + const int Doubled = 2; + try + { + stage = ""parse""; + int unused = 1; + result = int.Parse(s); + items = new string[3]; + return result * Doubled; + } + catch + { + + Console.WriteLine(stage + items.Length + Doubled); + return result; + } + } +}", incompatibleWithAutomatedCommentTesting: true); + } + + [Fact] + public async Task HoistsLocalsDeclaredAfterTheTryThatTheHandlerUsesAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Imports System +Class TestClass + Sub Save() + On Error GoTo Failed + Console.WriteLine(""saving"") +Cleanup: + Dim message = ""done"" + Console.WriteLine(message) + Exit Sub +Failed: + message = ""failed"" + Resume Cleanup + End Sub +End Class", @"using System; + +internal partial class TestClass +{ + public void Save() + { + + string message = default; + try + { + Console.WriteLine(""saving""); + } + catch + { + + message = ""failed""; + } + + message = ""done""; + Console.WriteLine(message); + return; + } +}", incompatibleWithAutomatedCommentTesting: true); + } + + [Fact] + public async Task ReturnAndNestedBlocksInsideCoveredCodeAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Class TestClass + Function FirstNegative(values As Integer()) As Integer + On Error GoTo Failed + For Each v In values + If v < 0 Then + Return v + End If + Next + Return 0 +Failed: + Return -1 + End Function +End Class", @" +internal partial class TestClass +{ + public int FirstNegative(int[] values) + { + try + { + foreach (var v in values) + { + if (v < 0) + { + return v; + } + } + return 0; + } + catch + { + + return -1; + } + } +}"); + } + + [Fact] + public async Task HandlerFallsOffTheEndBeforeLaterStatementsAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Imports System +Class TestClass + Sub Save(retry As Boolean) + On Error GoTo Failed + Console.WriteLine(""saving"") +Done: + Console.WriteLine(""done"") + Exit Sub +Failed: + If retry Then Resume Done + Console.WriteLine(""failed"") + End Sub +End Class", @"using System; + +internal partial class TestClass +{ + public void Save(bool retry) + { + try + { + Console.WriteLine(""saving""); + } + catch + { + + if (retry) + goto Done; + Console.WriteLine(""failed""); + return; + } + + Done: + ; + + Console.WriteLine(""done""); + return; + } +}", incompatibleWithAutomatedCommentTesting: true); + } + + [Fact] + public async Task HandlerReachedWithoutErrorAfterOtherStatementsAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Imports System +Class TestClass + Sub Save() + On Error GoTo Finish + Console.WriteLine(""saving"") + On Error GoTo 0 + Console.WriteLine(""saved"") +Finish: + Console.WriteLine(""finished"") + End Sub +End Class", @"using System; + +internal partial class TestClass +{ + public void Save() + { + try + { + Console.WriteLine(""saving""); + } + catch + { + goto Finish; + } + Console.WriteLine(""saved""); + Finish: + ; + + Console.WriteLine(""finished""); + } +}"); + } + + [Fact] + public async Task CleanupIdiomWithoutReentryGuardLetsCleanupErrorsPropagateAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Imports System +Class TestClass + Sub Save() + On Error GoTo Failed + Console.WriteLine(""saving"") +Cleanup: + Console.WriteLine(""cleanup"") + Exit Sub +Failed: + Console.WriteLine(""failed"") + Resume Cleanup + End Sub +End Class", @"using System; + +internal partial class TestClass +{ + public void Save() + { + try + { + Console.WriteLine(""saving""); + } + catch + { + + Console.WriteLine(""failed""); + } + + Console.WriteLine(""cleanup""); + return; + } +}", incompatibleWithAutomatedCommentTesting: true); + } + + [Fact] + public async Task CleanupIdiomWithCounterReentryGuardIsSegmentedAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Imports System +Class TestClass + Sub Save() + Dim attempts = 0 + On Error GoTo Failed + Console.WriteLine(""saving"") +Cleanup: + Console.WriteLine(""cleanup"") + Exit Sub +Failed: + attempts += 1 + If attempts > 3 Then Exit Sub + Console.WriteLine(Err.Description) + Resume Cleanup + End Sub +End Class", @"using System; +using Microsoft.VisualBasic; // Install-Package Microsoft.VisualBasic +using Microsoft.VisualBasic.CompilerServices; // Install-Package Microsoft.VisualBasic + +internal partial class TestClass +{ + public void Save() + { + int attempts = 0; + ProjectData.ClearProjectError(); + try + { + Console.WriteLine(""saving""); + } + catch (Exception ex) + { + ProjectData.SetProjectError(ex); + goto Failed; + } + + Cleanup: + ; + try + { + + Console.WriteLine(""cleanup""); + return; + } + catch (Exception ex) + { + ProjectData.SetProjectError(ex); + goto Failed; + } + + Failed: + ; + + attempts += 1; + if (attempts > 3) + { + ProjectData.ClearProjectError(); + return; + } + Console.WriteLine(Information.Err().Description); + ProjectData.ClearProjectError(); + goto Cleanup; + } +}"); + } + + [Fact] + public async Task CleanupIdiomWithFlagReentryGuardIsSegmentedAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Imports System +Class TestClass + Sub Save() + Dim cleaningUp As Boolean + On Error GoTo Failed + Console.WriteLine(""saving"") +Cleanup: + cleaningUp = True + Console.WriteLine(""cleanup"") + Exit Sub +Failed: + If cleaningUp Then Exit Sub + Resume Cleanup + End Sub +End Class", @"using System; + +internal partial class TestClass +{ + public void Save() + { + bool cleaningUp = default; + try + { + Console.WriteLine(""saving""); + } + catch + { + goto Failed; + } + + Cleanup: + ; + try + { + + cleaningUp = true; + Console.WriteLine(""cleanup""); + return; + } + catch + { + goto Failed; + } + + Failed: + ; + + if (cleaningUp) + return; + goto Cleanup; + } +}"); + } + + [Fact] + public async Task CleanupThatCannotThrowIsNotSegmentedAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Imports System +Class TestClass + Function Save() As Integer + Dim attempts = 0 + Dim result = 0 + On Error GoTo Failed + Console.WriteLine(""saving"") + result = 1 +Cleanup: + attempts = 0 + Return result +Failed: + attempts += 1 + If attempts > 3 Then Return -1 + Resume Cleanup + End Function +End Class", @"using System; + +internal partial class TestClass +{ + public int Save() + { + int attempts = 0; + int result = 0; + try + { + Console.WriteLine(""saving""); + result = 1; + } + catch + { + + attempts += 1; + if (attempts > 3) + return -1; + } + + attempts = 0; + return result; + } +}", incompatibleWithAutomatedCommentTesting: true); + } + + [Fact] + public async Task CleanupStartingWithItsOwnOnErrorStatementIsNotSegmentedAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Imports System +Class TestClass + Sub Save() + Dim attempts = 0 + On Error GoTo Failed + Console.WriteLine(""saving"") +Cleanup: + On Error GoTo 0 + Console.WriteLine(""cleanup"") + Exit Sub +Failed: + attempts += 1 + If attempts > 3 Then Exit Sub + Console.WriteLine(Err.Number) + Resume Cleanup + End Sub +End Class", @"using System; +using Microsoft.VisualBasic; // Install-Package Microsoft.VisualBasic +using Microsoft.VisualBasic.CompilerServices; // Install-Package Microsoft.VisualBasic + +internal partial class TestClass +{ + public void Save() + { + int attempts = 0; + ProjectData.ClearProjectError(); + try + { + Console.WriteLine(""saving""); + } + catch (Exception ex) + { + ProjectData.SetProjectError(ex); + + attempts += 1; + if (attempts > 3) + { + ProjectData.ClearProjectError(); + return; + } + Console.WriteLine(Information.Err().Number); + ProjectData.ClearProjectError(); + } + + ProjectData.ClearProjectError(); + Console.WriteLine(""cleanup""); + return; + } +}", incompatibleWithAutomatedCommentTesting: true); + } + + [Fact] + public async Task HandlerGoToLabelAfterCoveredStatementsAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Imports System +Class TestClass + Sub Save() + On Error GoTo Failed + Console.WriteLine(""saving"") + Exit Sub +Report: + Console.WriteLine(""report"") + Exit Sub +Failed: + Console.WriteLine(""failed"") + GoTo Report + End Sub +End Class", @"using System; + +internal partial class TestClass +{ + public void Save() + { + try + { + Console.WriteLine(""saving""); + return; + } + catch + { + + Console.WriteLine(""failed""); + } + + Console.WriteLine(""report""); + return; + } +}", incompatibleWithAutomatedCommentTesting: true); + } + + [Fact] + public async Task HandlerThatResumesNextKeepsPendingOutputAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Imports System +Class TestClass + Sub Save() + On Error GoTo Failed + Console.WriteLine(""saving"") + Exit Sub +Failed: + Resume Next + End Sub +End Class", @"using System; + +internal partial class TestClass +{ + public void Save() + { + try + { + Console.WriteLine(""saving""); + return; + } + catch + { + ; +#error Cannot convert ResumeStatementSyntax - see comment for details + /* Cannot convert ResumeStatementSyntax, CONVERSION ERROR: Conversion for ResumeNextStatement not implemented, please report this issue in 'Resume Next' at character 172 + + + Input: + + Resume Next + + */ + } + } +}CONVERSION ERROR: Conversion for ResumeNextStatement not implemented, please report this issue in 'Resume Next' at character 172 +", incompatibleWithAutomatedCommentTesting: true); } } \ No newline at end of file diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/OnErrorStructuredTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/OnErrorStructuredTests.vb new file mode 100644 index 000000000..fe6d8ce35 --- /dev/null +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/OnErrorStructuredTests.vb @@ -0,0 +1,228 @@ +Imports System +Imports System.Collections.Generic +Imports Xunit + +Public Class OnErrorStructuredTests + Private ReadOnly _log As New List(Of String) + Private _closeFailuresLeft As Integer + + Private Sub Work(succeed As Boolean) + _log.Add("work") + If Not succeed Then Throw New InvalidOperationException("work failed") + End Sub + + Private Sub Close() + _log.Add("close") + If _closeFailuresLeft > 0 Then + _closeFailuresLeft -= 1 + Throw New InvalidOperationException("close failed") + End If + End Sub + + Private Function Logged() As String + Return String.Join(", ", _log) + End Function + + Private Sub HandlerExits(succeed As Boolean) + On Error GoTo Failed + Work(succeed) + _log.Add("after work") + Exit Sub +Failed: + _log.Add("handler " & Err.Number & " " & Err.Description) + End Sub + + + Sub HandlerSeesErrAndErrIsClearedOnLeaving() + HandlerExits(False) + Assert.Equal("work, handler 5 work failed", Logged()) + Assert.Equal(0, Err.Number) + _log.Clear() + HandlerExits(True) + Assert.Equal("work, after work", Logged()) + End Sub + + Private Function SelfDivisionPossible(x As Integer) As Boolean + On Error GoTo ErrorHandler + Dim i As Integer = x / x + Return True +ErrorHandler: + Return Err.Number = 6 + End Function + + + Sub HandlerReturnsValueReadFromErr() + Assert.True(SelfDivisionPossible(0)) + Assert.Equal(0, Err.Number) + Assert.True(SelfDivisionPossible(3)) + End Sub + + Private Function LastStage(succeed As Boolean) As String + On Error GoTo Failed + Dim stage = "started" + Work(succeed) + stage = "worked" + Dim count As Integer = 1 +Failed: + Return stage & " " & count + End Function + + + Sub LocalsDeclaredInCoveredCodeAreVisibleToTheHandler() + Assert.Equal("started 0", LastStage(False)) + Assert.Equal("worked 1", LastStage(True)) + End Sub + + Private Sub CleanupWithCounterGuard() + Dim attempts = 0 + On Error GoTo Failed + Work(False) +Cleanup: + _log.Add("cleanup") + Close() + _log.Add("closed") + Exit Sub +Failed: + attempts += 1 + _log.Add("handler " & attempts & " " & Err.Description) + If attempts > 3 Then Exit Sub + Resume Cleanup + End Sub + + + Sub CleanupErrorReentersHandlerWithCounterGuard() + _closeFailuresLeft = 1 + CleanupWithCounterGuard() + Assert.Equal("work, handler 1 work failed, cleanup, close, handler 2 close failed, cleanup, close, closed", Logged()) + Assert.Equal(0, Err.Number) + End Sub + + + Sub CounterGuardStopsReentry() + _closeFailuresLeft = 10 + CleanupWithCounterGuard() + Assert.Equal("work, handler 1 work failed, cleanup, close, handler 2 close failed, cleanup, close, handler 3 close failed, cleanup, close, handler 4 close failed", Logged()) + Assert.Equal(0, Err.Number) + End Sub + + Private Sub CleanupWithFlagGuard() + Dim cleaningUp As Boolean + On Error GoTo Failed + Work(False) +Cleanup: + cleaningUp = True + Close() + _log.Add("closed") + Exit Sub +Failed: + _log.Add("handler " & cleaningUp) + If cleaningUp Then Exit Sub + Resume Cleanup + End Sub + + + Sub FlagGuardStopsReentry() + _closeFailuresLeft = 10 + CleanupWithFlagGuard() + Assert.Equal("work, handler False, close, handler True", Logged()) + End Sub + + Private Function Retried(retry As Boolean) As Integer + On Error GoTo Failed + Work(False) +Done: + _log.Add("done") + Retried = 1 + Exit Function +Failed: + If retry Then Resume Done + _log.Add("gave up " & Err.Number) + Retried = -1 + End Function + + + Sub HandlerThatFallsOffTheEndLeavesTheMethod() + Assert.Equal(-1, Retried(False)) + Assert.Equal("work, gave up 5", Logged()) + Assert.Equal(0, Err.Number) + _log.Clear() + Assert.Equal(1, Retried(True)) + Assert.Equal("work, done", Logged()) + End Sub + + Private Sub ReachesHandlerLabel(succeed As Boolean) + On Error GoTo Finish + Work(succeed) + On Error GoTo 0 + _log.Add("worked") +Finish: + _log.Add("finish " & Err.Number) + End Sub + + + Sub HandlerLabelReachedWithAndWithoutError() + ReachesHandlerLabel(True) + Assert.Equal("work, worked, finish 0", Logged()) + _log.Clear() + ReachesHandlerLabel(False) + Assert.Equal("work, finish 5", Logged()) + End Sub + + Private Function FirstNegative(values As Integer()) As Integer + On Error GoTo Failed + For Each v In values + If v < 0 Then + Return v + End If + Next + Return 0 +Failed: + Return -100 + End Function + + + Sub ReturnFromNestedBlocksInCoveredCode() + Assert.Equal(-2, FirstNegative({1, -2, 3})) + Assert.Equal(0, FirstNegative({1})) + Assert.Equal(-100, FirstNegative(Nothing)) + End Sub + + Private Sub GoesToReport() + On Error GoTo Failed + Work(False) + Exit Sub +Report: + _log.Add("report " & Err.Number) + Exit Sub +Failed: + _log.Add("failed") + GoTo Report + End Sub + + + Sub HandlerGoToKeepsErr() + GoesToReport() + Assert.Equal("work, failed, report 5", Logged()) + End Sub + + Private Sub CleanupWithoutHandler() + Dim attempts = 0 + On Error GoTo Failed + Work(False) +Cleanup: + On Error GoTo 0 + _log.Add("cleanup " & Err.Number) + Exit Sub +Failed: + attempts += 1 + If attempts > 3 Then Exit Sub + _log.Add("handler " & Err.Number) + Resume Cleanup + End Sub + + + Sub CleanupStartingWithOnErrorGoToZero() + CleanupWithoutHandler() + Assert.Equal("work, handler 5, cleanup 0", Logged()) + End Sub +End Class diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/OnErrorWithoutErrTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/OnErrorWithoutErrTests.vb new file mode 100644 index 000000000..a58976cf3 --- /dev/null +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/OnErrorWithoutErrTests.vb @@ -0,0 +1,48 @@ +Imports System +Imports System.Collections.Generic +Imports Xunit + +Public Class OnErrorWithoutErrTests + Private ReadOnly _log As New List(Of String) + + Private Sub Work(succeed As Boolean) + _log.Add("work") + If Not succeed Then Throw New InvalidOperationException("work failed") + End Sub + + Private Function Saved(succeed As Boolean) As Boolean + On Error GoTo Failed + Dim attempt = 1 + Work(succeed) + Return True +Failed: + _log.Add("failed attempt " & attempt) + Return False + End Function + + + Sub BareCatchRunsHandler() + Assert.False(Saved(False)) + Assert.True(Saved(True)) + Assert.Equal("work, failed attempt 1, work", String.Join(", ", _log)) + End Sub + + Private Sub WithCleanup(succeed As Boolean) + On Error GoTo Failed + Work(succeed) +Cleanup: + Dim message = "cleanup" + _log.Add(message) + Exit Sub +Failed: + _log.Add("failed " & message) + Resume Cleanup + End Sub + + + Sub ResumeToCleanup() + WithCleanup(False) + WithCleanup(True) + Assert.Equal("work, failed , cleanup, work, cleanup", String.Join(", ", _log)) + End Sub +End Class From 91c8c4f110edf66aaa92594a133fc42fc181cce2 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 05:22:03 +0000 Subject: [PATCH 07/47] Update the On Error README to what is implemented Status, where each part lives (implemented vs planned), the Err read rules, and the segmented form as implemented: the handler sits after the segments at method level and each catch jumps to it, so it needs no local function or action type. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_019FEr8GzCY8KvPQb6eDtmhX --- CodeConverter/CSharp/OnError/README.md | 44 +++++++++++++++----------- 1 file changed, 25 insertions(+), 19 deletions(-) diff --git a/CodeConverter/CSharp/OnError/README.md b/CodeConverter/CSharp/OnError/README.md index 0de5fd187..87e857110 100644 --- a/CodeConverter/CSharp/OnError/README.md +++ b/CodeConverter/CSharp/OnError/README.md @@ -1,7 +1,6 @@ # VB → C# unstructured error handling (`On Error`, `Resume`) — design -Status: **design only, nothing here is implemented yet.** Tracks [icsharpcode/CodeConverter#426](https://github.com/icsharpcode/CodeConverter/issues/426). -Today only one shape is converted (`LambdaConverter.GetWithConvertedGotosOrNull`); everything else is converted statement by statement and marked with `#error`. +Status: the model, shape selection, `Err` usage and shape 1 (structured) are implemented. Shapes 2–4 are recognised but not emitted yet: those methods keep the previous output (`PendingShapeFallback`: one `try`/`catch` when there's exactly one label and one `On Error GoTo`, otherwise statement by statement with `#error`). Tracks [icsharpcode/CodeConverter#426](https://github.com/icsharpcode/CodeConverter/issues/426). Sources: * VB: [`LocalRewriter_UnstructuredExceptionHandling.vb`](https://github.com/dotnet/roslyn/blob/main/src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_UnstructuredExceptionHandling.vb) (the lowering, with pseudo-code of the emitted method), the `RegisterUnstructuredExceptionHandlingResumeTarget` calls in the sibling `LocalRewriter_*.vb` files (which statements are resume points), and the [On Error](https://learn.microsoft.com/dotnet/visual-basic/language-reference/statements/on-error-statement) / [Resume](https://learn.microsoft.com/dotnet/visual-basic/language-reference/statements/resume-statement) docs. @@ -141,18 +140,16 @@ Alternatives considered: * its containing type (all partial parts) references `Err` (`Microsoft.VisualBasic.Information.Err`); * the project contains an **`Err` helper**: a method that references `Err` but has no `On Error` statement of its own, so it can only be reading an error that some other method caught (typically a shared `LogError()` called from handlers anywhere). -The helper search is one pass per compilation, cached: find identifiers named `Err`, bind only those, and check the containing method for `On Error` statements. +The helper search is one pass per project, cached: find identifiers named `Err`, bind only those, and check the containing method for `On Error` statements. Only reads count: `Err.Raise` and `Err.Clear` don't depend on an earlier error. A read inside a `Catch` block reads that block's own error, so doesn't make an `Err` helper. When `Err` is maintained: * each catch starts with `SetProjectError(ex)`; -* `ClearProjectError()` goes where an `On Error` or `Resume*` statement was, and on leaving a handler by exit. +* `ClearProjectError()` goes where an `On Error` or `Resume*` statement was, and on leaving a handler by exit. `Return expr` is wrapped in `try { return expr; } finally { ProjectData.ClearProjectError(); }` unless `expr` is a literal or the return variable, since VB evaluates it (possibly reading `Err`) before clearing. Otherwise catches are bare `catch { }` and need no `Microsoft.VisualBasic` reference. -Known difference: `Err` read through reflection, late binding, or from another project isn't seen. - -The existing structured conversion emits `catch { }` followed by `Information.Err().Number`, which reads 0 at runtime (see `BasicGotoAsync`); under this rule it gets the `SetProjectError` call. +Known differences: `Err` read through reflection, late binding, or from another project isn't seen. After `GoTo L` out of a handler, VB clears `Err` when the method is left; the C# leaves it set. ### Throwing loop headers skip the loop @@ -177,15 +174,20 @@ The same applies to handler code reached without an error (no `Exit Sub` before VB re-enters `H`, which here means log, close, fail, log, close … forever. Looping forever is never what was meant, so by default only the code before the first resume label is in the `try`, and a secondary error propagates to the caller. -The exact form is cheap, because the handler never resumes into the middle of the cleanup: split the covered statements into **segments** at the labels the handler resumes to, and give each segment its own `try` calling the handler: +The exact form is cheap, because the handler never resumes into the middle of the cleanup: split the covered statements into **segments** at the labels the handler resumes to, give each segment its own `try`, and put the handler after them, at method level, where each `catch` jumps to it: ```csharp -OnErrorAction H() { /* handler */ } -try { Work(); } catch { if (H() == OnErrorAction.Exit) return; } +try { Work(); } catch (Exception ex) { ProjectData.SetProjectError(ex); goto H; } Cleanup: -try { conn.Close(); return; } catch { if (H() == OnErrorAction.Exit) return; goto Cleanup; } +try { conn.Close(); return; } catch (Exception ex) { ProjectData.SetProjectError(ex); goto H; } +H: +Log(Information.Err().Description); +ProjectData.ClearProjectError(); +goto Cleanup; ``` +All its ways out are method-level jumps or exits, so it needs no local function and no action value to say how it left (C# has no local enums, and a nested one would clash between partial parts). The segmented form isn't used when the handler leaves by `GoTo L` (the code at `L` would still be "in a handler" in VB, so isn't protected) or is also reached without an error. + Which form is used: | Situation | Output | @@ -202,17 +204,21 @@ Conditions on `Err.Number` alone don't count: they distinguish kinds of first er * Formatting: the guards rely on `try { … } catch { }` staying on one line. If the formatter expands them, shape 2 is four lines per statement. -## Where each part will live +## Where each part lives -To be filled in as it's implemented. Intended split, all in this directory: +All in this directory unless stated. Planned parts are in italics. | Requirement | Class | |---|---| -| Active handler per statement, handler regions, exits | `OnErrorModel` (analysis only, no C# syntax) | -| Which statements are resume points, and where a failing condition resumes | `ResumePoints` | -| `Err` usage in the type, `Err` helpers in the project (cached) | `ErrUsage` | -| Re-entry guard detection, segments | `OnErrorModel` | +| Entry point, one emitter per shape | `OnErrorMethodBodyConverter`, called from `LambdaConverter.ConvertMethodBodyStatementsAsync` | +| Active handler per statement, dynamic detection, handler regions and exits | `OnErrorModel`, `ActiveHandler`, `HandlerRegion`, `HandlerExit` (analysis only, no C# syntax) | +| Which statements are resume points, and where a failing condition resumes | *`ResumePoints`* | +| `Err` usage in the type, `Err` helpers in the project (one cached pass per project) | `ErrUsage`, created in `VBToCSProjectContentsConverter`, reached through `CommonConversions.ErrUsage` | | Choosing a shape | `OnErrorShapeSelector` | -| Guards, handler local function, hoisting | one emitter per shape, called from `MethodBodyExecutableStatementVisitor` | +| Structured layout, segments | `StructuredPlanner`, `StructuredPlan` | +| Secondary errors: can the resumed-to code throw, re-entry guard | `ThrowAnalysis`, `ReEntryGuard` | +| `On Error` / `Resume` statements met by the method body visitor | `IOnErrorStatementConverter`, set on `MethodBodyExecutableStatementVisitor.OnErrorStatementConverter`; `StructuredStatementConverter` | +| Shape 1 output, hoisting, `Err` calls | `StructuredShapeEmitter`, `LocalHoisting`, `ErrStatements`, `ClearErrOnReturnRewriter` | +| Shapes 2–4 output | *one emitter each*; until then `PendingShapeFallback` | -Tests: a conversion test per shape in `Tests/CSharp/StatementTests/OnErrorStatementTests.cs`, and self-verifying tests in `Tests/TestData/SelfVerifyingTests/VBToCS/` that log each step and compare the VB and C# logs (the scenarios used to check this design: failing `If`/`ElseIf`/`While`/`Loop Until` conditions, `Select`, `Using`, multiple declarators, `Return`, `On Error GoTo 0`, handler with `Resume Next` inside a loop, `Resume` retry with a counter, fall-through into a handler, handler that throws, cleanup idiom, conditional `On Error`). +Tests: conversion tests in `Tests/CSharp/StatementTests/OnErrorStatementTests.cs`, and self-verifying tests in `Tests/TestData/SelfVerifyingTests/VBToCS/OnError*.vb` that log each step and compare the VB and C# logs (the scenarios used to check this design: failing `If`/`ElseIf`/`While`/`Loop Until` conditions, `Select`, `Using`, multiple declarators, `Return`, `On Error GoTo 0`, handler with `Resume Next` inside a loop, `Resume` retry with a counter, fall-through into a handler, handler that throws, cleanup idiom, conditional `On Error`). From fb3e2063f59f287ef4700b06dcc59e0214ae4356 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 05:47:25 +0000 Subject: [PATCH 08/47] Drop a redundant check from StructuredPlanner Pure refactor, no output change: with exactly one On Error GoTo label statement there is exactly one handler. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_019FEr8GzCY8KvPQb6eDtmhX --- CodeConverter/CSharp/OnError/StructuredPlanner.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CodeConverter/CSharp/OnError/StructuredPlanner.cs b/CodeConverter/CSharp/OnError/StructuredPlanner.cs index 58b363e97..21eb6a210 100644 --- a/CodeConverter/CSharp/OnError/StructuredPlanner.cs +++ b/CodeConverter/CSharp/OnError/StructuredPlanner.cs @@ -15,7 +15,7 @@ internal static class StructuredPlanner public static StructuredPlan TryPlan(OnErrorModel model, SemanticModel semanticModel) { var onErrorGoTos = model.OnErrorStatements.Where(s => s.IsKind(VBasicSyntaxKind.OnErrorGoToLabelStatement)).ToArray(); - if (onErrorGoTos.Length != 1 || model.Handlers.Count != 1) return null; + if (onErrorGoTos.Length != 1) return null; var handler = model.Handlers.Single(); var onErrorIndex = model.MethodLevelIndexOf(onErrorGoTos.Single()); if (handler.LabelIndex < onErrorIndex) return null; From 03db4de16a14a26ffd27e63bb68542e895e34436 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 05:47:25 +0000 Subject: [PATCH 09/47] Test more On Error shapes and re-entry guard conditions Pins the structured output for every condition kind that counts as a re-entry guard (If/ElseIf, Select Case, While, Do Until, If()), two resume labels, Err.Number-only conditions (not a guard), cleanup that can't throw, returns of the function's return variable, local functions in a handler, Err.Raise/Err.Clear not counting as reads, and mixed hoisted declarators. Also pins the unchanged output of shapes that have no emitter yet (conditional On Error, Resume Next, On Error GoTo -1, handler label in a block, Resume, handler before its On Error, running into a handler that resumes, jumps into the handler or covered code). Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_019FEr8GzCY8KvPQb6eDtmhX --- .../StatementTests/OnErrorStatementTests.cs | 818 ++++++++++++++++++ 1 file changed, 818 insertions(+) diff --git a/Tests/CSharp/StatementTests/OnErrorStatementTests.cs b/Tests/CSharp/StatementTests/OnErrorStatementTests.cs index e37bb46ea..841fadb36 100644 --- a/Tests/CSharp/StatementTests/OnErrorStatementTests.cs +++ b/Tests/CSharp/StatementTests/OnErrorStatementTests.cs @@ -770,6 +770,824 @@ public void Save() }", incompatibleWithAutomatedCommentTesting: true); } + [Fact] + public async Task ErrRaiseAndClearAreNotReadsAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Imports System +Class TestClass + Sub Save() + On Error GoTo Failed + Console.WriteLine(""saving"") + Exit Sub +Failed: + Console.WriteLine(""failed"") + End Sub +End Class + +Module Errors + Sub Fail() + Err.Clear() + Err.Raise(5) + End Sub +End Module", @"using System; +using Microsoft.VisualBasic; // Install-Package Microsoft.VisualBasic + +internal partial class TestClass +{ + public void Save() + { + try + { + Console.WriteLine(""saving""); + return; + } + catch + { + + Console.WriteLine(""failed""); + } + } +} + +internal static partial class Errors +{ + public static void Fail() + { + Information.Err().Clear(); + Information.Err().Raise(5); + } +}"); + } + + [Fact] + public async Task HandlerReturnsTheReturnVariableAndIgnoresLambdaReturnsAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Imports System +Class TestClass + Function Code() As Integer + On Error GoTo Failed + Code = 1 + Console.WriteLine(""saving"") + Exit Function +Failed: + Dim describe = Function() + Return Err.Description + End Function + Console.WriteLine(describe()) + Code = Err.Number + Exit Function + End Function +End Class", @"using System; +using Microsoft.VisualBasic; // Install-Package Microsoft.VisualBasic +using Microsoft.VisualBasic.CompilerServices; // Install-Package Microsoft.VisualBasic + +internal partial class TestClass +{ + public int Code() + { + int CodeRet = default; + ProjectData.ClearProjectError(); + try + { + CodeRet = 1; + Console.WriteLine(""saving""); + return CodeRet; + } + catch (Exception ex) + { + ProjectData.SetProjectError(ex); + + string describe() => Information.Err().Description; + Console.WriteLine(describe()); + CodeRet = Information.Err().Number; + ProjectData.ClearProjectError(); + return CodeRet; + } + } +}"); + } + + [Fact] + public async Task HoistingKeepsDeclarationOrderAndLeavesStaticLocalsAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Imports System +Class TestClass + Sub Save() + On Error GoTo Failed + Dim first = 1, second = first + 1, third = second + 1 + Dim kept, used As Integer + Static calls As Integer + calls += 1 + Exit Sub +Failed: + Console.WriteLine(second & used & calls) + End Sub +End Class", @"using System; + +internal partial class TestClass +{ + private int _Save_calls = default; + public void Save() + { + int second = default; + int used = default; + try + { + int first = 1; + second = first + 1; + int third = second + 1; + int kept; + _Save_calls += 1; + return; + } + catch + { + + Console.WriteLine(second.ToString() + used + _Save_calls); + } + } +}"); + } + + [Fact] + public async Task ShapesWithoutAnEmitterYetKeepTheirOutputAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Imports System +Class TestClass + Sub ConditionalOnError(flag As Boolean) + If flag Then On Error GoTo Failed + Console.WriteLine(""work"") + Exit Sub +Failed: + Console.WriteLine(""failed"") + End Sub + + Sub ResumeNextEverywhere() + On Error Resume Next + Console.WriteLine(""work"") + End Sub + + Sub ResetsHandlerState() + On Error GoTo Failed + Console.WriteLine(""work"") + Exit Sub +Failed: + On Error GoTo -1 + Console.WriteLine(""failed"") + End Sub + + Sub HandlerLabelInsideABlock(flag As Boolean) + On Error GoTo Failed + Console.WriteLine(""work"") + If flag Then +Failed: + Console.WriteLine(""failed"") + End If + End Sub + + Sub Retries() + On Error GoTo Failed + Console.WriteLine(""work"") + Exit Sub +Failed: + Resume + End Sub + + Sub HandlerBeforeOnError() + GoTo Start +Failed: + Console.WriteLine(""failed"") + Exit Sub +Start: + On Error GoTo Failed + Console.WriteLine(""work"") + End Sub + + Sub RunsIntoHandlerThatResumes() + On Error GoTo Failed + Console.WriteLine(""work"") +Done: + Console.WriteLine(""done"") +Failed: + Resume Done + End Sub + + Sub JumpsIntoHandler(skip As Boolean) + On Error GoTo Failed + If skip Then GoTo Failed + Console.WriteLine(""work"") + Exit Sub +Failed: + Console.WriteLine(""failed"") + End Sub + + Sub JumpsBackIntoCoveredCode(retry As Boolean) + On Error GoTo Failed +Again: + Console.WriteLine(""work"") +Cleanup: + If retry Then GoTo Again + Exit Sub +Failed: + Resume Cleanup + End Sub +End Class", @"using System; + +internal partial class TestClass +{ + public void ConditionalOnError(bool flag) + { + if (flag) + ; +#error Cannot convert OnErrorGoToStatementSyntax - see comment for details + /* Cannot convert OnErrorGoToStatementSyntax, CONVERSION ERROR: Conversion for OnErrorGoToLabelStatement not implemented, please report this issue in 'On Error GoTo Failed' at character 106 + + + Input: + On Error GoTo Failed + + */ + Console.WriteLine(""work""); + return; + Failed: + ; + + Console.WriteLine(""failed""); + } + + public void ResumeNextEverywhere() + { + ; +#error Cannot convert OnErrorResumeNextStatementSyntax - see comment for details + /* Cannot convert OnErrorResumeNextStatementSyntax, CONVERSION ERROR: Conversion for OnErrorResumeNextStatement not implemented, please report this issue in 'On Error Resume Next' at character 310 + + + Input: + On Error Resume Next + + */ + Console.WriteLine(""work""); + } + + public void ResetsHandlerState() + { + try + { + Console.WriteLine(""work""); + return; + } + catch + { + ; +#error Cannot convert OnErrorGoToStatementSyntax - see comment for details + /* Cannot convert OnErrorGoToStatementSyntax, CONVERSION ERROR: Conversion for OnErrorGoToMinusOneStatement not implemented, please report this issue in 'On Error GoTo -1' at character 540 + + + Input: + + On Error GoTo -1 + + */ + Console.WriteLine(""failed""); + } + } + + public void HandlerLabelInsideABlock(bool flag) + { + ; +#error Cannot convert OnErrorGoToStatementSyntax - see comment for details + /* Cannot convert OnErrorGoToStatementSyntax, CONVERSION ERROR: Conversion for OnErrorGoToLabelStatement not implemented, please report this issue in 'On Error GoTo Failed' at character 683 + + + Input: + On Error GoTo Failed + + */ + Console.WriteLine(""work""); + if (flag) + { + Failed: + ; + + Console.WriteLine(""failed""); + } + } + + public void Retries() + { + try + { + Console.WriteLine(""work""); + return; + } + catch + { + ; +#error Cannot convert ResumeStatementSyntax - see comment for details + /* Cannot convert ResumeStatementSyntax, CONVERSION ERROR: Conversion for ResumeStatement not implemented, please report this issue in 'Resume' at character 1004 + + + Input: + + Resume + + */ + } + } + + public void HandlerBeforeOnError() + { + goto Start; + Failed: + ; + + Console.WriteLine(""failed""); + return; + Start: + ; + ; +#error Cannot convert OnErrorGoToStatementSyntax - see comment for details + /* Cannot convert OnErrorGoToStatementSyntax, CONVERSION ERROR: Conversion for OnErrorGoToLabelStatement not implemented, please report this issue in 'On Error GoTo Failed' at character 1173 + + + Input: + + On Error GoTo Failed + + */ + Console.WriteLine(""work""); + } + + public void RunsIntoHandlerThatResumes() + { + ; +#error Cannot convert OnErrorGoToStatementSyntax - see comment for details + /* Cannot convert OnErrorGoToStatementSyntax, CONVERSION ERROR: Conversion for OnErrorGoToLabelStatement not implemented, please report this issue in 'On Error GoTo Failed' at character 1305 + + + Input: + On Error GoTo Failed + + */ + Console.WriteLine(""work""); + Done: + ; + + Console.WriteLine(""done""); + Failed: + ; + ; +#error Cannot convert ResumeStatementSyntax - see comment for details + /* Cannot convert ResumeStatementSyntax, CONVERSION ERROR: Conversion for ResumeLabelStatement not implemented, please report this issue in 'Resume Done' at character 1449 + + + Input: + + Resume Done + + */ + } + + public void JumpsIntoHandler(bool skip) + { + try + { + if (skip) + goto Failed; + Console.WriteLine(""work""); + return; + } + catch + { + + Console.WriteLine(""failed""); + } + } + + public void JumpsBackIntoCoveredCode(bool retry) + { + ; +#error Cannot convert OnErrorGoToStatementSyntax - see comment for details + /* Cannot convert OnErrorGoToStatementSyntax, CONVERSION ERROR: Conversion for OnErrorGoToLabelStatement not implemented, please report this issue in 'On Error GoTo Failed' at character 1788 + + + Input: + On Error GoTo Failed + + */ + Again: + ; + + Console.WriteLine(""work""); + Cleanup: + ; + + if (retry) + goto Again; + return; + Failed: + ; + ; +#error Cannot convert ResumeStatementSyntax - see comment for details + /* Cannot convert ResumeStatementSyntax, CONVERSION ERROR: Conversion for ResumeLabelStatement not implemented, please report this issue in 'Resume Cleanup' at character 1946 + + + Input: + + Resume Cleanup + + */ + } +}----- Exception 1 of 11 ----- + +1 target compilation errors: +CS0159: No such label 'Failed' within the scope of the goto statement +----- Exception 2 of 11 ----- +CONVERSION ERROR: Conversion for OnErrorGoToLabelStatement not implemented, please report this issue in 'On Error GoTo Failed' at character 106 + +----- Exception 3 of 11 ----- +CONVERSION ERROR: Conversion for OnErrorResumeNextStatement not implemented, please report this issue in 'On Error Resume Next' at character 310 + +----- Exception 4 of 11 ----- +CONVERSION ERROR: Conversion for OnErrorGoToMinusOneStatement not implemented, please report this issue in 'On Error GoTo -1' at character 540 + +----- Exception 5 of 11 ----- +CONVERSION ERROR: Conversion for OnErrorGoToLabelStatement not implemented, please report this issue in 'On Error GoTo Failed' at character 683 + +----- Exception 6 of 11 ----- +CONVERSION ERROR: Conversion for ResumeStatement not implemented, please report this issue in 'Resume' at character 1004 + +----- Exception 7 of 11 ----- +CONVERSION ERROR: Conversion for OnErrorGoToLabelStatement not implemented, please report this issue in 'On Error GoTo Failed' at character 1173 + +----- Exception 8 of 11 ----- +CONVERSION ERROR: Conversion for OnErrorGoToLabelStatement not implemented, please report this issue in 'On Error GoTo Failed' at character 1305 + +----- Exception 9 of 11 ----- +CONVERSION ERROR: Conversion for ResumeLabelStatement not implemented, please report this issue in 'Resume Done' at character 1449 + +----- Exception 10 of 11 ----- +CONVERSION ERROR: Conversion for OnErrorGoToLabelStatement not implemented, please report this issue in 'On Error GoTo Failed' at character 1788 + +----- Exception 11 of 11 ----- +CONVERSION ERROR: Conversion for ResumeLabelStatement not implemented, please report this issue in 'Resume Cleanup' at character 1946", incompatibleWithAutomatedCommentTesting: true); + } + + [Fact] + public async Task ReEntryGuardsAreFoundInAnyConditionAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Imports System +Class TestClass + Private _attempts As Integer + + Sub IfElseIfGuard() + On Error GoTo Failed + Console.WriteLine(""work"") +Cleanup: + Console.WriteLine(""cleanup"") + Exit Sub +Failed: + _attempts += 1 + If _attempts > 3 Then + Exit Sub + ElseIf _attempts > 2 Then + Console.WriteLine(""last try"") + End If + Resume Cleanup + End Sub + + Sub SelectGuard() + Dim attempts = 0 + On Error GoTo Failed + Console.WriteLine(""work"") +Cleanup: + Console.WriteLine(""cleanup"") + Exit Sub +Failed: + attempts += 1 + Select Case attempts + Case Is > 3 + Exit Sub + End Select + Resume Cleanup + End Sub + + Sub LoopGuard() + Dim attempts = 0 + On Error GoTo Failed + Console.WriteLine(""work"") +Cleanup: + Console.WriteLine(""cleanup"") + Exit Sub +Failed: + attempts += 1 + While attempts < 2 + attempts += 1 + End While + Do Until attempts > 0 + Loop + Console.WriteLine(If(attempts > 3, ""giving up"", ""retrying"")) + Resume Cleanup + End Sub + + Sub TwoResumeLabels(early As Boolean) + Dim attempts = 0 + On Error GoTo Failed + Console.WriteLine(""work"") +First: + Console.WriteLine(""first"") +Second: + Console.WriteLine(""second"") + Exit Sub +Failed: + attempts += 1 + If attempts > 3 Then Exit Sub + If early Then Resume First + Resume Second + End Sub + + Sub ErrNumberIsNotAGuard() + On Error GoTo Failed + Console.WriteLine(""work"") +Cleanup: + Console.WriteLine(""cleanup"") + Exit Sub +Failed: + If Err.Number = 5 Then Exit Sub + Resume Cleanup + End Sub +End Class", @"using System; +using Microsoft.VisualBasic; // Install-Package Microsoft.VisualBasic +using Microsoft.VisualBasic.CompilerServices; // Install-Package Microsoft.VisualBasic + +internal partial class TestClass +{ + private int _attempts; + + public void IfElseIfGuard() + { + ProjectData.ClearProjectError(); + try + { + Console.WriteLine(""work""); + } + catch (Exception ex) + { + ProjectData.SetProjectError(ex); + goto Failed; + } + + Cleanup: + ; + try + { + + Console.WriteLine(""cleanup""); + return; + } + catch (Exception ex) + { + ProjectData.SetProjectError(ex); + goto Failed; + } + + Failed: + ; + + _attempts += 1; + if (_attempts > 3) + { + ProjectData.ClearProjectError(); + return; + } + else if (_attempts > 2) + { + Console.WriteLine(""last try""); + } + ProjectData.ClearProjectError(); + goto Cleanup; + } + + public void SelectGuard() + { + int attempts = 0; + ProjectData.ClearProjectError(); + try + { + Console.WriteLine(""work""); + } + catch (Exception ex) + { + ProjectData.SetProjectError(ex); + goto Failed; + } + + Cleanup: + ; + try + { + + Console.WriteLine(""cleanup""); + return; + } + catch (Exception ex) + { + ProjectData.SetProjectError(ex); + goto Failed; + } + + Failed: + ; + + attempts += 1; + switch (attempts) + { + case > 3: + { + ProjectData.ClearProjectError(); + return; + } + } + ProjectData.ClearProjectError(); + goto Cleanup; + } + + public void LoopGuard() + { + int attempts = 0; + ProjectData.ClearProjectError(); + try + { + Console.WriteLine(""work""); + } + catch (Exception ex) + { + ProjectData.SetProjectError(ex); + goto Failed; + } + + Cleanup: + ; + try + { + + Console.WriteLine(""cleanup""); + return; + } + catch (Exception ex) + { + ProjectData.SetProjectError(ex); + goto Failed; + } + + Failed: + ; + + attempts += 1; + while (attempts < 2) + attempts += 1; + while (attempts <= 0) + { + } + Console.WriteLine(attempts > 3 ? ""giving up"" : ""retrying""); + ProjectData.ClearProjectError(); + goto Cleanup; + } + + public void TwoResumeLabels(bool early) + { + int attempts = 0; + ProjectData.ClearProjectError(); + try + { + Console.WriteLine(""work""); + } + catch (Exception ex) + { + ProjectData.SetProjectError(ex); + goto Failed; + } + + First: + ; + try + { + + Console.WriteLine(""first""); + } + catch (Exception ex) + { + ProjectData.SetProjectError(ex); + goto Failed; + } + + Second: + ; + try + { + + Console.WriteLine(""second""); + return; + } + catch (Exception ex) + { + ProjectData.SetProjectError(ex); + goto Failed; + } + + Failed: + ; + + attempts += 1; + if (attempts > 3) + { + ProjectData.ClearProjectError(); + return; + } + if (early) + { + ProjectData.ClearProjectError(); + goto First; + } + ProjectData.ClearProjectError(); + goto Second; + } + + public void ErrNumberIsNotAGuard() + { + ProjectData.ClearProjectError(); + try + { + Console.WriteLine(""work""); + } + catch (Exception ex) + { + ProjectData.SetProjectError(ex); + + if (Information.Err().Number == 5) + { + ProjectData.ClearProjectError(); + return; + } + ProjectData.ClearProjectError(); + } + + Console.WriteLine(""cleanup""); + return; + } +}", incompatibleWithAutomatedCommentTesting: true); + } + + [Fact] + public async Task CleanupOfOnlyJumpsAndConstantsIsNotSegmentedAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Imports System +Class TestClass + Function Save(fallback As Integer) As Integer + Dim attempts = 0 + On Error GoTo Failed + Console.WriteLine(""saving"") +Cleanup: + Dim finished As Boolean = True + Dim result As Integer = fallback + GoTo Done +Done: + Return result +Failed: + attempts += 1 + If attempts > 3 Then Exit Function + Resume Cleanup + End Function +End Class", @"using System; + +internal partial class TestClass +{ + public int Save(int fallback) + { + int attempts = 0; + try + { + Console.WriteLine(""saving""); + } + catch + { + + attempts += 1; + if (attempts > 3) + return default; + } + + bool finished = true; + int result = fallback; + goto Done; + Done: + ; + + return result; + } +}", incompatibleWithAutomatedCommentTesting: true); + } + [Fact] public async Task HandlerThatResumesNextKeepsPendingOutputAsync() { From f7198933e9d174d88a6e38202335feb5df5bb792 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 06:13:08 +0000 Subject: [PATCH 10/47] Extract DeclarationSplitter from LocalHoisting Pure refactor: splitting a declaration into a default declaration and an assignment is needed with other rules for choosing the locals, so it no longer depends on the hoisting set. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_019FEr8GzCY8KvPQb6eDtmhX --- .../CSharp/OnError/DeclarationSplitter.cs | 92 +++++++++++++++++++ CodeConverter/CSharp/OnError/LocalHoisting.cs | 72 ++------------- 2 files changed, 98 insertions(+), 66 deletions(-) create mode 100644 CodeConverter/CSharp/OnError/DeclarationSplitter.cs diff --git a/CodeConverter/CSharp/OnError/DeclarationSplitter.cs b/CodeConverter/CSharp/OnError/DeclarationSplitter.cs new file mode 100644 index 000000000..596e623af --- /dev/null +++ b/CodeConverter/CSharp/OnError/DeclarationSplitter.cs @@ -0,0 +1,92 @@ +using static Microsoft.CodeAnalysis.VisualBasic.VisualBasicExtensions; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +/// +/// Splits a converted local declaration into a declaration of the chosen locals as = default, and the assignment of their initializers. +/// +/// +/// A C# local is scoped to its block, but a VB local lives for the whole method and starts zeroed, so declaring it earlier as = default is exact. +/// The declaration becomes an assignment, or nothing when VB had no initializer. Constants move whole. +/// +internal sealed class DeclarationSplitter +{ + private readonly SemanticModel _semanticModel; + private readonly CommonConversions _commonConversions; + + public DeclarationSplitter(SemanticModel semanticModel, CommonConversions commonConversions) + { + _semanticModel = semanticModel; + _commonConversions = commonConversions; + } + + /// The declaration that were converted from. + /// Which of its locals to split. + /// Receives the declarations to place before the statements that are returned. + /// Replaces the assignment of a split local's initializer, e.g. to guard it. Receives the local and the assignment. + /// The statements that stay where the declaration was. + public IEnumerable Split(VBSyntax.LocalDeclarationStatementSyntax vbDeclaration, IEnumerable csStatements, + Func shouldSplit, List declarations, Func transformAssignment = null) + { + var splitByName = vbDeclaration.Declarators + .SelectMany(v => v.Names.Select(n => (Symbol: _semanticModel.GetDeclaredSymbol(n) as ILocalSymbol, NeedsAssignment: NeedsAssignment(v, n)))) + .Where(x => x.Symbol != null && shouldSplit(x.Symbol)) + .ToDictionary(x => x.Symbol.Name, x => x, StringComparer.OrdinalIgnoreCase); + if (!splitByName.Any()) return csStatements; + + var inPlace = new List(); + foreach (var csStatement in csStatements) { + if (csStatement is not LocalDeclarationStatementSyntax csDeclaration || + !csDeclaration.Declaration.Variables.Any(v => splitByName.ContainsKey(v.Identifier.ValueText))) { + inPlace.Add(csStatement); + } else if (csDeclaration.IsConst) { + declarations.Add(csDeclaration); + } else { + inPlace.AddRange(SplitDeclaration(csDeclaration, splitByName, declarations, transformAssignment ?? ((_, assignment) => assignment))); + } + } + return inPlace; + } + + private IEnumerable SplitDeclaration(LocalDeclarationStatementSyntax csDeclaration, + Dictionary splitByName, List declarations, + Func transformAssignment) + { + var inOrder = new List(); + var kept = new List(); + foreach (var variable in csDeclaration.Declaration.Variables) { + if (!splitByName.TryGetValue(variable.Identifier.ValueText, out var split)) { + kept.Add(variable); + continue; + } + AddKept(); + declarations.Add(DeclareDefault(variable.Identifier, split.Symbol)); + if (split.NeedsAssignment && variable.Initializer != null) { + inOrder.Add(transformAssignment(split.Symbol, SyntaxFactory.ExpressionStatement(SyntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, + SyntaxFactory.IdentifierName(variable.Identifier.WithoutTrivia()), variable.Initializer.Value.WithoutTrivia())))); + } + } + AddKept(); + return inOrder; + + void AddKept() + { + if (!kept.Any()) return; + inOrder.Add(csDeclaration.WithDeclaration(csDeclaration.Declaration.WithVariables(SyntaxFactory.SeparatedList(kept)))); + kept.Clear(); + } + } + + private LocalDeclarationStatementSyntax DeclareDefault(SyntaxToken identifier, ILocalSymbol local) + { + var declarator = SyntaxFactory.VariableDeclarator(identifier.WithoutTrivia()) + .WithInitializer(SyntaxFactory.EqualsValueClause(SyntaxFactory.LiteralExpression(SyntaxKind.DefaultLiteralExpression))); + var type = _commonConversions.GetTypeSyntax(local.Type); + return SyntaxFactory.LocalDeclarationStatement(SyntaxFactory.VariableDeclaration(type, SyntaxFactory.SingletonSeparatedList(declarator))); + } + + private static bool NeedsAssignment(VBSyntax.VariableDeclaratorSyntax declarator, VBSyntax.ModifiedIdentifierSyntax name) => + declarator.Initializer != null || declarator.AsClause is VBSyntax.AsNewClauseSyntax || name.ArrayBounds != null; +} diff --git a/CodeConverter/CSharp/OnError/LocalHoisting.cs b/CodeConverter/CSharp/OnError/LocalHoisting.cs index ec2f73363..fad615993 100644 --- a/CodeConverter/CSharp/OnError/LocalHoisting.cs +++ b/CodeConverter/CSharp/OnError/LocalHoisting.cs @@ -1,5 +1,4 @@ using static Microsoft.CodeAnalysis.VisualBasic.VisualBasicExtensions; -using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace ICSharpCode.CodeConverter.CSharp.OnError; @@ -8,18 +7,18 @@ namespace ICSharpCode.CodeConverter.CSharp.OnError; /// Declares before a try the locals that are declared in it but used after it or in the handler. /// /// -/// A C# local is scoped to its block, but a VB local lives for the whole method and starts zeroed, so declaring it earlier as = default is exact. -/// The declaration in the try becomes an assignment, or nothing when VB had no initializer. -/// Constants move whole. Static locals already become fields. +/// See for how a declaration is split. Static locals already become fields, so are left alone. /// internal sealed class LocalHoisting { private readonly OnErrorConversionContext _context; private readonly HashSet _hoisted; + private readonly DeclarationSplitter _splitter; public LocalHoisting(OnErrorConversionContext context, OnErrorModel model, IEnumerable segments) { _context = context; + _splitter = new DeclarationSplitter(context.SemanticModel, context.CommonConversions); _hoisted = new HashSet(segments.SelectMany(s => FindUsedOutside(model, s)), SymbolEqualityComparer.Default); } @@ -34,7 +33,9 @@ public async Task> ConvertAsync(IEnumerable(); foreach (var statement in statements) { var csStatements = await _context.ConvertAsync(new[] { statement }); - converted.AddRange(statement is VBSyntax.LocalDeclarationStatementSyntax declaration ? Split(declaration, csStatements) : csStatements); + converted.AddRange(statement is VBSyntax.LocalDeclarationStatementSyntax declaration + ? _splitter.Split(declaration, csStatements, _hoisted.Contains, Declarations) + : csStatements); } return converted; } @@ -57,65 +58,4 @@ private IEnumerable FindUsedOutside(OnErrorModel model, StatementR .ToArray(); return declared.Where(l => referencedOutside.Contains(l, SymbolEqualityComparer.Default)); } - - private IEnumerable Split(VBSyntax.LocalDeclarationStatementSyntax vbDeclaration, IEnumerable csStatements) - { - var hoistedByName = vbDeclaration.Declarators - .SelectMany(v => v.Names.Select(n => (Symbol: _context.SemanticModel.GetDeclaredSymbol(n) as ILocalSymbol, NeedsAssignment: NeedsAssignment(v, n)))) - .Where(x => x.Symbol != null && _hoisted.Contains(x.Symbol)) - .ToDictionary(x => x.Symbol.Name, x => x, StringComparer.OrdinalIgnoreCase); - if (!hoistedByName.Any()) return csStatements; - - var inPlace = new List(); - foreach (var csStatement in csStatements) { - if (csStatement is not LocalDeclarationStatementSyntax csDeclaration || - !csDeclaration.Declaration.Variables.Any(v => hoistedByName.ContainsKey(v.Identifier.ValueText))) { - inPlace.Add(csStatement); - } else if (csDeclaration.IsConst) { - Declarations.Add(csDeclaration); - } else { - inPlace.AddRange(SplitDeclaration(csDeclaration, hoistedByName)); - } - } - return inPlace; - } - - private IEnumerable SplitDeclaration(LocalDeclarationStatementSyntax csDeclaration, - Dictionary hoistedByName) - { - var inOrder = new List(); - var kept = new List(); - foreach (var variable in csDeclaration.Declaration.Variables) { - if (!hoistedByName.TryGetValue(variable.Identifier.ValueText, out var hoisted)) { - kept.Add(variable); - continue; - } - AddKept(); - Declarations.Add(DeclareDefault(variable.Identifier, hoisted.Symbol)); - if (hoisted.NeedsAssignment && variable.Initializer != null) { - inOrder.Add(SyntaxFactory.ExpressionStatement(SyntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, - SyntaxFactory.IdentifierName(variable.Identifier.WithoutTrivia()), variable.Initializer.Value.WithoutTrivia()))); - } - } - AddKept(); - return inOrder; - - void AddKept() - { - if (!kept.Any()) return; - inOrder.Add(csDeclaration.WithDeclaration(csDeclaration.Declaration.WithVariables(SyntaxFactory.SeparatedList(kept)))); - kept.Clear(); - } - } - - private LocalDeclarationStatementSyntax DeclareDefault(SyntaxToken identifier, ILocalSymbol local) - { - var declarator = SyntaxFactory.VariableDeclarator(identifier.WithoutTrivia()) - .WithInitializer(SyntaxFactory.EqualsValueClause(SyntaxFactory.LiteralExpression(SyntaxKind.DefaultLiteralExpression))); - var type = _context.CommonConversions.GetTypeSyntax(local.Type); - return SyntaxFactory.LocalDeclarationStatement(SyntaxFactory.VariableDeclaration(type, SyntaxFactory.SingletonSeparatedList(declarator))); - } - - private static bool NeedsAssignment(VBSyntax.VariableDeclaratorSyntax declarator, VBSyntax.ModifiedIdentifierSyntax name) => - declarator.Initializer != null || declarator.AsClause is VBSyntax.AsNewClauseSyntax || name.ArrayBounds != null; } From c2692051f870927603f46406b92957e34364da2f Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 06:13:30 +0000 Subject: [PATCH 11/47] Let a decorator change how every statement is converted Pure refactor: MethodBodyExecutableStatementVisitor keeps its per-scope state visitor, and DecorateStatementVisitor wraps it between that and the comment conversion. Nested statements are already visited through CommentConvertingVisitor, so a decorator sees each statement at any depth without the visitor knowing why. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_019FEr8GzCY8KvPQb6eDtmhX --- .../MethodBodyExecutableStatementVisitor.cs | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/CodeConverter/CSharp/MethodBodyExecutableStatementVisitor.cs b/CodeConverter/CSharp/MethodBodyExecutableStatementVisitor.cs index 7cc2dfbaf..93573c935 100644 --- a/CodeConverter/CSharp/MethodBodyExecutableStatementVisitor.cs +++ b/CodeConverter/CSharp/MethodBodyExecutableStatementVisitor.cs @@ -29,17 +29,29 @@ internal class MethodBodyExecutableStatementVisitor : VBasic.VisualBasicSyntaxVi private readonly HashSet _generatedNames = new(); private readonly HashSet _localsToInlineInLoop; private readonly PerScopeState _perScopeState; + private VBasic.VisualBasicSyntaxVisitor>> _statementVisitor; public bool IsIterator { get; set; } public IdentifierNameSyntax ReturnVariable { get; set; } public bool HasReturnVariable => ReturnVariable != null; - public VBasic.VisualBasicSyntaxVisitor>> CommentConvertingVisitor { get; } + /// How nested statements are converted: every statement is visited through this, whatever its depth. + public VBasic.VisualBasicSyntaxVisitor>> CommentConvertingVisitor { get; private set; } /// Set by the On Error conversion for the shape it emits. Until then, On Error and Resume statements can't be converted. public IOnErrorStatementConverter OnErrorStatementConverter { get; set; } private CommonConversions CommonConversions { get; } + /// + /// Lets another class change the conversion of each statement at every nesting depth, without this visitor knowing why. + /// The decorator sits inside the comment conversion, so comments attach to whatever it returns for the statement. + /// + public void DecorateStatementVisitor(Func>>, VBasic.VisualBasicSyntaxVisitor>>> decorate) + { + _statementVisitor = decorate(_statementVisitor); + CommentConvertingVisitor = new CommentConvertingMethodBodyVisitor(_statementVisitor); + } + public static async Task CreateAsync(VisualBasicSyntaxNode node, SemanticModel semanticModel, CommentConvertingVisitorWrapper triviaConvertingExpressionVisitor, CommonConversions commonConversions, VisualBasicEqualityComparison visualBasicEqualityComparison, Stack withBlockLhs, HashSet extraUsingDirectives, @@ -68,8 +80,8 @@ private MethodBodyExecutableStatementVisitor(VisualBasicSyntaxNode methodNode, S _extraUsingDirectives = extraUsingDirectives; _handledEventsAnalysis = typeContext.HandledEventsAnalysis; _perScopeState = typeContext.PerScopeState; - var byRefParameterVisitor = new PerScopeStateVisitorDecorator(this, _perScopeState, semanticModel, _generatedNames); - CommentConvertingVisitor = new CommentConvertingMethodBodyVisitor(byRefParameterVisitor); + _statementVisitor = new PerScopeStateVisitorDecorator(this, _perScopeState, semanticModel, _generatedNames); + CommentConvertingVisitor = new CommentConvertingMethodBodyVisitor(_statementVisitor); _localsToInlineInLoop = localsToInlineInLoop; } From 76b0202d51b053e81fae6c3c7110e0d020c250e8 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 06:50:05 +0000 Subject: [PATCH 12/47] Share default initializers and let a catch have a filter Pure refactor: the structured emitter's default-initializer rule moves to DefaultInitializers so the other shapes can use it, and ErrStatements.CatchClause takes an optional exception filter. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_019FEr8GzCY8KvPQb6eDtmhX --- .../CSharp/OnError/DefaultInitializers.cs | 20 +++++++++++++++++++ CodeConverter/CSharp/OnError/ErrStatements.cs | 8 +++++--- .../CSharp/OnError/StructuredShapeEmitter.cs | 12 +---------- 3 files changed, 26 insertions(+), 14 deletions(-) create mode 100644 CodeConverter/CSharp/OnError/DefaultInitializers.cs diff --git a/CodeConverter/CSharp/OnError/DefaultInitializers.cs b/CodeConverter/CSharp/OnError/DefaultInitializers.cs new file mode 100644 index 000000000..9694c09ec --- /dev/null +++ b/CodeConverter/CSharp/OnError/DefaultInitializers.cs @@ -0,0 +1,20 @@ +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +/// +/// Gives locals declared without an initializer the = default that VB's zeroed locals have. +/// +/// +/// The converter leaves out an initializer that VB's flow analysis says isn't needed, but that analysis doesn't know a handler can run after any statement, +/// or that an error can skip the assignment. VB locals start zeroed, so = default is exact. +/// +internal static class DefaultInitializers +{ + public static IEnumerable Add(IEnumerable statements) => + statements.Select(s => s is LocalDeclarationStatementSyntax { IsConst: false } declaration + ? declaration.WithDeclaration(declaration.Declaration.WithVariables(SyntaxFactory.SeparatedList(declaration.Declaration.Variables.Select(v => + v.Initializer != null ? v : v.WithInitializer(SyntaxFactory.EqualsValueClause(SyntaxFactory.LiteralExpression(SyntaxKind.DefaultLiteralExpression))))))) + : s); +} diff --git a/CodeConverter/CSharp/OnError/ErrStatements.cs b/CodeConverter/CSharp/OnError/ErrStatements.cs index e65107f2d..41402dbc1 100644 --- a/CodeConverter/CSharp/OnError/ErrStatements.cs +++ b/CodeConverter/CSharp/OnError/ErrStatements.cs @@ -24,13 +24,15 @@ public SyntaxList Clear() => IsMaintained ? SyntaxFactory.SingletonList(ProjectDataCall("ClearProjectError")) : default; /// A catch-all, as VB catches any exception, recording it in Err first as VB's catch does. - public CatchClauseSyntax CatchClause(string exceptionVariableName, IEnumerable statements) + /// VB's catch has a filter on the active handler; an exception filter doesn't unwind the stack when it's false, as in VB. + public CatchClauseSyntax CatchClause(string exceptionVariableName, IEnumerable statements, ExpressionSyntax filter = null) { - if (!IsMaintained) return SyntaxFactory.CatchClause().WithBlock(SyntaxFactory.Block(statements)); + var filterClause = filter == null ? null : SyntaxFactory.CatchFilterClause(filter); + if (!IsMaintained) return SyntaxFactory.CatchClause().WithFilter(filterClause).WithBlock(SyntaxFactory.Block(statements)); _extraUsingDirectives.Add("System"); var declaration = SyntaxFactory.CatchDeclaration(SyntaxFactory.IdentifierName(nameof(Exception)), SyntaxFactory.Identifier(exceptionVariableName)); var setError = ProjectDataCall("SetProjectError", SyntaxFactory.IdentifierName(exceptionVariableName)); - return SyntaxFactory.CatchClause(declaration, null, SyntaxFactory.Block(statements.Prepend(setError))); + return SyntaxFactory.CatchClause(declaration, filterClause, SyntaxFactory.Block(statements.Prepend(setError))); } private StatementSyntax ProjectDataCall(string methodName, params ExpressionSyntax[] arguments) diff --git a/CodeConverter/CSharp/OnError/StructuredShapeEmitter.cs b/CodeConverter/CSharp/OnError/StructuredShapeEmitter.cs index b7dbf9c8f..cb809abc0 100644 --- a/CodeConverter/CSharp/OnError/StructuredShapeEmitter.cs +++ b/CodeConverter/CSharp/OnError/StructuredShapeEmitter.cs @@ -38,7 +38,7 @@ public StructuredShapeEmitter(OnErrorConversionContext context, OnErrorModel mod public async Task> EmitAsync() { - var before = WithDefaultInitializers(await ConvertRangeAsync(0, _plan.OnErrorIndex)); + var before = DefaultInitializers.Add(await ConvertRangeAsync(0, _plan.OnErrorIndex)).ToList(); var protectedAndHandler = _plan.IsSegmented ? await EmitSegmentedAsync() : await EmitPlainAsync(); var statements = before.Concat(_err.Clear()).Concat(_hoisting.Declarations).Concat(protectedAndHandler).ToList(); return WithoutUnreferencedLabels(statements); @@ -89,16 +89,6 @@ private async Task> ConvertHandlerAsync() return withClearedErr; } - /// - /// The converter leaves out an initializer that VB's flow analysis says isn't needed, but that analysis doesn't know a handler can run after any statement. - /// VB locals start zeroed, so = default is exact. - /// - private static List WithDefaultInitializers(List statements) => - statements.Select(s => s is LocalDeclarationStatementSyntax { IsConst: false } declaration - ? declaration.WithDeclaration(declaration.Declaration.WithVariables(SyntaxFactory.SeparatedList(declaration.Declaration.Variables.Select(v => - v.Initializer != null ? v : v.WithInitializer(SyntaxFactory.EqualsValueClause(SyntaxFactory.LiteralExpression(SyntaxKind.DefaultLiteralExpression))))))) - : s).ToList(); - private TryStatementSyntax Try(IEnumerable statements, IEnumerable catchStatements) => SyntaxFactory.TryStatement(SyntaxFactory.Block(statements), SyntaxFactory.SingletonList(_err.CatchClause(_exceptionVariableName, catchStatements)), null); From b558a30a88208e6346463e94f858fa72c7d2ba2b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 20:56:59 +0000 Subject: [PATCH 13/47] Convert On Error Resume Next with a guard per resume point Methods whose active handler is statically resume-next keep their structure: each statement that can fail is wrapped in try/catch, locals are declared as = default before their guard, If/ElseIf conditions and loop conditions that can fail are evaluated in a guard (loops via a local function), Using/SyncLock are one resume point, and Select/For/For Each/With are one guard round the header with their statements guarded individually. A guard decorator in front of the statement visitor guards every statement at any depth. Methods the guards can't express (a label handler as well, or a failing loop condition that reads a ref parameter) keep the previous output. Existing expectations changed: ShapesWithoutAnEmitterYetKeepTheirOutputAsync no longer contains ResumeNextEverywhere (now converted, covered in OnErrorResumeNextTests), so its remaining #error character offsets shift. TriviaTests.TestCarryingOverErrorTriviaAddedByConverterAsync used On Error Resume Next only to get a converter error; it now uses On Error GoTo -1, which stays unsupported. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8GzCY8KvPQb6eDtmhX --- CodeConverter/CSharp/OnError/GuardPolicy.cs | 39 + .../OnError/GuardingStatementVisitor.cs | 24 + .../OnError/OnErrorMethodBodyConverter.cs | 8 +- CodeConverter/CSharp/OnError/README.md | 14 +- .../CSharp/OnError/ResumeNextShapeEmitter.cs | 81 ++ .../OnError/ResumeNextStatementConverter.cs | 33 + CodeConverter/CSharp/OnError/ResumePoints.cs | 109 +++ .../CSharp/OnError/StatementGuards.cs | 133 ++++ CodeConverter/CSharp/OnError/ThrowAnalysis.cs | 60 +- .../StatementTests/OnErrorResumeNextTests.cs | 738 ++++++++++++++++++ .../StatementTests/OnErrorStatementTests.cs | 74 +- Tests/CSharp/TriviaTests.cs | 2 +- .../VBToCS/OnErrorResumeNextErrTests.vb | 96 +++ .../VBToCS/OnErrorResumeNextTests.vb | 316 ++++++++ 14 files changed, 1667 insertions(+), 60 deletions(-) create mode 100644 CodeConverter/CSharp/OnError/GuardPolicy.cs create mode 100644 CodeConverter/CSharp/OnError/GuardingStatementVisitor.cs create mode 100644 CodeConverter/CSharp/OnError/ResumeNextShapeEmitter.cs create mode 100644 CodeConverter/CSharp/OnError/ResumeNextStatementConverter.cs create mode 100644 CodeConverter/CSharp/OnError/ResumePoints.cs create mode 100644 CodeConverter/CSharp/OnError/StatementGuards.cs create mode 100644 Tests/CSharp/StatementTests/OnErrorResumeNextTests.cs create mode 100644 Tests/TestData/SelfVerifyingTests/VBToCS/OnErrorResumeNextErrTests.vb create mode 100644 Tests/TestData/SelfVerifyingTests/VBToCS/OnErrorResumeNextTests.vb diff --git a/CodeConverter/CSharp/OnError/GuardPolicy.cs b/CodeConverter/CSharp/OnError/GuardPolicy.cs new file mode 100644 index 000000000..4a7eb2d0d --- /dev/null +++ b/CodeConverter/CSharp/OnError/GuardPolicy.cs @@ -0,0 +1,39 @@ +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +/// +/// What a guard's catch does with an error, apart from recording it in Err: the part of README.md "Output shapes" that differs between shapes 2 to 4. +/// +internal abstract class GuardPolicy +{ + /// Null for a catch that always catches. + public virtual ExpressionSyntax Filter => null; + + /// Whether may jump back to the label placed before the guarded statement, which VB's Resume does. + public virtual bool CanRetry => false; + + /// Whether may leave the method, which can't be done from a local function. + public virtual bool CanExitMethod => false; + + /// Null unless . + public virtual IEnumerable OnError(string retryLabel) => Enumerable.Empty(); +} + +/// +/// On Error Resume Next is active: the error is recorded and the next statement runs. +/// +internal sealed class ResumeNextGuardPolicy : GuardPolicy +{ +} + +/// +/// Whether On Error Resume Next is active is only known when the method runs, so a flag set where VB's On Error statements were decides whether to catch. +/// +internal sealed class DynamicGuardPolicy : GuardPolicy +{ + public DynamicGuardPolicy(string flagName) => Filter = SyntaxFactory.IdentifierName(flagName); + + public override ExpressionSyntax Filter { get; } +} diff --git a/CodeConverter/CSharp/OnError/GuardingStatementVisitor.cs b/CodeConverter/CSharp/OnError/GuardingStatementVisitor.cs new file mode 100644 index 000000000..7d319f4e2 --- /dev/null +++ b/CodeConverter/CSharp/OnError/GuardingStatementVisitor.cs @@ -0,0 +1,24 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +/// +/// Guards every statement the method body visitor converts, at any depth, so the visitor itself needn't know about resume points. +/// +internal sealed class GuardingStatementVisitor : VBasic.VisualBasicSyntaxVisitor>> +{ + private readonly VBasic.VisualBasicSyntaxVisitor>> _wrappedVisitor; + private readonly StatementGuards _guards; + + public GuardingStatementVisitor(VBasic.VisualBasicSyntaxVisitor>> wrappedVisitor, StatementGuards guards) + { + _wrappedVisitor = wrappedVisitor; + _guards = guards; + } + + public override async Task> DefaultVisit(SyntaxNode node) + { + var converted = await _wrappedVisitor.Visit(node); + return node is VBSyntax.StatementSyntax statement ? _guards.Guard(statement, converted) : converted; + } +} diff --git a/CodeConverter/CSharp/OnError/OnErrorMethodBodyConverter.cs b/CodeConverter/CSharp/OnError/OnErrorMethodBodyConverter.cs index ad4ae264d..d9fbe96ef 100644 --- a/CodeConverter/CSharp/OnError/OnErrorMethodBodyConverter.cs +++ b/CodeConverter/CSharp/OnError/OnErrorMethodBodyConverter.cs @@ -19,10 +19,14 @@ public static async Task> ConvertOrNullAsyn case OnErrorShapeKind.None: return null; case OnErrorShapeKind.Structured: - var err = new ErrStatements(await context.CommonConversions.ErrUsage.IsMaintainedInAsync(context.ContainingType), context.ExtraUsingDirectives); - return await new StructuredShapeEmitter(context, model, shape.Structured, err).EmitAsync(); + return await new StructuredShapeEmitter(context, model, shape.Structured, await CreateErrStatementsAsync(context)).EmitAsync(); + case OnErrorShapeKind.ResumeNext or OnErrorShapeKind.Dynamic when ResumeNextShapeEmitter.CanEmit(model, context.SemanticModel): + return await new ResumeNextShapeEmitter(context, model, await CreateErrStatementsAsync(context)).EmitAsync(); default: return await PendingShapeFallback.ConvertOrNullAsync(statements, context.ConvertAsync); } } + + private static async Task CreateErrStatementsAsync(OnErrorConversionContext context) => + new(await context.CommonConversions.ErrUsage.IsMaintainedInAsync(context.ContainingType), context.ExtraUsingDirectives); } diff --git a/CodeConverter/CSharp/OnError/README.md b/CodeConverter/CSharp/OnError/README.md index 87e857110..028d58ae8 100644 --- a/CodeConverter/CSharp/OnError/README.md +++ b/CodeConverter/CSharp/OnError/README.md @@ -1,6 +1,6 @@ # VB → C# unstructured error handling (`On Error`, `Resume`) — design -Status: the model, shape selection, `Err` usage and shape 1 (structured) are implemented. Shapes 2–4 are recognised but not emitted yet: those methods keep the previous output (`PendingShapeFallback`: one `try`/`catch` when there's exactly one label and one `On Error GoTo`, otherwise statement by statement with `#error`). Tracks [icsharpcode/CodeConverter#426](https://github.com/icsharpcode/CodeConverter/issues/426). +Status: the model, shape selection, `Err` usage, shape 1 (structured) and shape 2 (resume next) are implemented. Shapes 3 and 4 are recognised but not emitted yet: those methods keep the previous output (`PendingShapeFallback`: one `try`/`catch` when there's exactly one label and one `On Error GoTo`, otherwise statement by statement with `#error`). Tracks [icsharpcode/CodeConverter#426](https://github.com/icsharpcode/CodeConverter/issues/426). Sources: * VB: [`LocalRewriter_UnstructuredExceptionHandling.vb`](https://github.com/dotnet/roslyn/blob/main/src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_UnstructuredExceptionHandling.vb) (the lowering, with pseudo-code of the emitted method), the `RegisterUnstructuredExceptionHandlingResumeTarget` calls in the sibling `LocalRewriter_*.vb` files (which statements are resume points), and the [On Error](https://learn.microsoft.com/dotnet/visual-basic/language-reference/statements/on-error-statement) / [Resume](https://learn.microsoft.com/dotnet/visual-basic/language-reference/statements/resume-statement) docs. @@ -102,7 +102,9 @@ Chosen per method, simplest first. `…` is where the `Err` calls go when `Err` * `If` condition: `bool cond = true; try { cond = …; } catch { }` then `if (cond)`. `ElseIf` chains become nested `if`/`else` so each condition has somewhere to go. * Loop condition: a local function, so the loop stays a loop: `bool Cond() { try { return …; } catch { return true; } }` and `while (Cond())`. Bottom-tested conditions return whichever value leaves the loop. * `Using`, `SyncLock`, `Select Case` and `For`/`For Each`: one guard around the whole statement, with the statements inside guarded individually where VB makes them resume points (not inside `Using`/`SyncLock`). A failing header skips the block. - * `Case` expressions: *not spiked*. Only matters when the case expressions aren't constants, where the converter already emits `when` clauses or an `if` chain. + * `Case` expressions: *not spiked*. Only matters when the case expressions aren't constants, where the converter already emits `when` clauses or an `if` chain. A `Select` is only guarded when its expression or a case expression can fail, and then a failing `Case` expression skips the whole block rather than resuming in that case. + * A statement is only guarded when it can fail (`ThrowAnalysis`): constants, locals and parameters of primitive types, their comparisons, `Exit`, `GoTo` and labels aren't. Every `Dim` gets `= default` so that skipping its assignment still compiles. + * `With` is guarded like `Select`, and loops whose condition can fail and which read a `ref`/`out` parameter aren't expressible (a local function can't capture it): the method keeps the fallback. 3. **Handler function.** `On Error GoTo H` where the handler resumes into the covered statements. The handler becomes a local function and each guard calls it: @@ -122,7 +124,8 @@ Chosen per method, simplest first. `…` is where the `Err` calls go when `Err` 5. **Fallback.** Anything else keeps today's behaviour, statement-by-statement conversion plus `#error`: * the handler jumps to a label inside a nested block; * `On Error GoTo -1`; - * a handler local function would need to capture a `ref`/`out` parameter. + * a handler local function would need to capture a `ref`/`out` parameter; + * `On Error Resume Next` and `On Error GoTo