From ae662d9639c9abc71e953516ba1038ddbcc60f94 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 17:23:28 +0000 Subject: [PATCH 01/14] Add regression tests for If before Else keeping its binding (#823) Pins that, with default code style options, the converter keeps the braces that stop an inner if capturing the outer else: multi-line If bodies keep braces, and UnpackNonNestedBlock keeps braces around a single statement that has nested statements. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- .../StatementTests/MethodStatementTests.cs | 46 ++++ .../VBToCS/IfElseBindingTests.vb | 206 ++++++++++++++++++ 2 files changed, 252 insertions(+) create mode 100644 Tests/TestData/SelfVerifyingTests/VBToCS/IfElseBindingTests.vb diff --git a/Tests/CSharp/StatementTests/MethodStatementTests.cs b/Tests/CSharp/StatementTests/MethodStatementTests.cs index 1bcc291c6..795fb853d 100644 --- a/Tests/CSharp/StatementTests/MethodStatementTests.cs +++ b/Tests/CSharp/StatementTests/MethodStatementTests.cs @@ -863,6 +863,52 @@ public static void MultiStatement(int a) }"); } + [Fact] + public async Task SingleLineIfAsLastStatementBeforeElseKeepsBracesIssue823Async() + { + await TestConversionVisualBasicToCSharpAsync(@"Class TestClass + Private Sub TestMethod(OUTER As Boolean, FOO1 As Boolean, FOO2 As Boolean) + If OUTER Then + If FOO1 Then Bar1() : Exit Sub + Else 'NOT OUTER + If FOO2 Then + Bar2() + Exit Sub + End If + End If 'OUTER + End Sub + Private Sub Bar1() + End Sub + Private Sub Bar2() + End Sub +End Class", @" +internal partial class TestClass +{ + private void TestMethod(bool OUTER, bool FOO1, bool FOO2) + { + if (OUTER) + { + if (FOO1) + { + Bar1(); + return; + } + } + else if (FOO2) // NOT OUTER + { + Bar2(); + return; + } // OUTER + } + private void Bar1() + { + } + private void Bar2() + { + } +}"); + } + [Fact] public async Task NestedBlockStatementsKeepSameNestingAsync() { diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/IfElseBindingTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/IfElseBindingTests.vb new file mode 100644 index 000000000..bedc8788b --- /dev/null +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/IfElseBindingTests.vb @@ -0,0 +1,206 @@ +Imports System +Imports System.Collections.Generic +Imports System.IO +Imports Xunit + +''' +''' Each Else must stay attached to the same If after conversion (C#'s dangling else binds to the nearest if). +''' Each test runs every combination of (outer, f1, f2) in the order FFF,FFT,FTF,FTT,TFF,TFT,TTF,TTT and logs the branches taken. +''' +Public Class IfElseBindingTests + Private ReadOnly _log As New List(Of String) + + Private Sub Log(s As String) + _log.Add(s) + End Sub + + Private Function RunAllCombinations(body As Action(Of Boolean, Boolean, Boolean)) As String + Dim results As New List(Of String) + For Each outer In {False, True} + For Each f1 In {False, True} + For Each f2 In {False, True} + _log.Clear() + body(outer, f1, f2) + results.Add(String.Join(",", _log)) + Next + Next + Next + Return String.Join("|", results) + End Function + + + Public Sub SingleLineIfWithExitAsLastStatementBeforeElse_Issue823() + Assert.Equal("end|bar2|end|bar2|end|end|bar1|bar1", RunAllCombinations(AddressOf Issue823)) + End Sub + + Private Sub Issue823(outer As Boolean, f1 As Boolean, f2 As Boolean) + If outer Then + If f1 Then Log("bar1") : Exit Sub + Else 'NOT OUTER + If f2 Then + Log("bar2") + Exit Sub + End If + End If 'OUTER + Log("end") + End Sub + + + Public Sub SingleLineIfElseAsLastStatementBeforeElse() + Assert.Equal("end|c,end|end|c,end|b,end|b,end|a,end|a,end", RunAllCombinations(AddressOf SingleLineIfElseBeforeElse)) + End Sub + + Private Sub SingleLineIfElseBeforeElse(outer As Boolean, f1 As Boolean, f2 As Boolean) + If outer Then + If f1 Then Log("a") Else Log("b") + Else + If f2 Then Log("c") + End If + Log("end") + End Sub + + + Public Sub NestedSingleLineIfElseBindsToInnerIf() + Assert.Equal("end|end|end|end|b,end|b,end|a,end|a,end", RunAllCombinations(AddressOf NestedSingleLineIfElse)) + End Sub + + Private Sub NestedSingleLineIfElse(outer As Boolean, f1 As Boolean, f2 As Boolean) + If outer Then If f1 Then Log("a") Else Log("b") + Log("end") + End Sub + + + Public Sub NestedSingleLineIfWithTwoElses() + Assert.Equal("c,end|c,end|c,end|c,end|b,end|b,end|a,end|a,end", RunAllCombinations(AddressOf NestedSingleLineIfTwoElses)) + End Sub + + Private Sub NestedSingleLineIfTwoElses(outer As Boolean, f1 As Boolean, f2 As Boolean) + If outer Then If f1 Then Log("a") Else Log("b") Else Log("c") + Log("end") + End Sub + + + Public Sub IfWithoutElseBeforeElseIf() + Assert.Equal("end|c,end|end|b,end|end|end|a,end|a,end", RunAllCombinations(AddressOf IfBeforeElseIf)) + End Sub + + Private Sub IfBeforeElseIf(outer As Boolean, f1 As Boolean, f2 As Boolean) + If outer Then + If f1 Then Log("a") + ElseIf f2 Then + If f1 Then Log("b") Else Log("c") + End If + Log("end") + End Sub + + + Public Sub TwoLevelsOfIfWithoutElseBeforeElses() + Assert.Equal("c,end|c,end|c,end|c,end|b,end|b,end|end|a,end", RunAllCombinations(AddressOf TwoLevels)) + End Sub + + Private Sub TwoLevels(outer As Boolean, f1 As Boolean, f2 As Boolean) + If outer Then + If f1 Then + If f2 Then Log("a") + Else + Log("b") + End If + Else + Log("c") + End If + Log("end") + End Sub + + + Public Sub SingleLineIfWithExitForBeforeElseInLoop() + Assert.Equal("loop,end|b,loop,end|loop,end|b,loop,end|loop,end|loop,end|a,end|a,end", RunAllCombinations(AddressOf InForLoop)) + End Sub + + Private Sub InForLoop(outer As Boolean, f1 As Boolean, f2 As Boolean) + For i = 1 To 1 + If outer Then + If f1 Then Log("a") : Exit For + Else + If f2 Then Log("b") + End If + Log("loop") + Next + Log("end") + End Sub + + + Public Sub LoopContainingIfBeforeElse() + Assert.Equal("b,end|b,end|b,end|b,end|end|end|end|a,end", RunAllCombinations(AddressOf LoopBeforeElse)) + End Sub + + Private Sub LoopBeforeElse(outer As Boolean, f1 As Boolean, f2 As Boolean) + If outer Then + Do While f1 + f1 = False + If f2 Then Log("a") + Loop + Else + Log("b") + End If + Log("end") + End Sub + + + Public Sub LambdaContainingIfBeforeElse() + Assert.Equal("b,end|b,end|b,end|b,end|end|end|a,end|a,end", RunAllCombinations(AddressOf LambdaBeforeElse)) + End Sub + + Private Sub LambdaBeforeElse(outer As Boolean, f1 As Boolean, f2 As Boolean) + If outer Then + Dim act As Action = Sub() If f1 Then Log("a") + act() + Else + Log("b") + End If + Log("end") + End Sub + + + Public Sub SingleLineLambdaWithIfElseInSingleLineIf() + Assert.Equal("end|end|end|end|b,end|b,end|a,end|a,end", RunAllCombinations(AddressOf SingleLineLambdaInSingleLineIf)) + End Sub + + Private Sub SingleLineLambdaInSingleLineIf(outer As Boolean, f1 As Boolean, f2 As Boolean) + Dim act As Action = Nothing + If outer Then act = Sub() If f1 Then Log("a") Else Log("b") + If act IsNot Nothing Then act() + Log("end") + End Sub + + + Public Sub SyncLockContainingIfBeforeElse() + Assert.Equal("b,end|b,end|b,end|b,end|end|end|a,end|a,end", RunAllCombinations(AddressOf SyncLockBeforeElse)) + End Sub + + Private Sub SyncLockBeforeElse(outer As Boolean, f1 As Boolean, f2 As Boolean) + If outer Then + SyncLock _log + If f1 Then Log("a") + End SyncLock + Else + Log("b") + End If + Log("end") + End Sub + + + Public Sub UsingContainingIfBeforeElse() + Assert.Equal("b,end|b,end|b,end|b,end|end|end|a,end|a,end", RunAllCombinations(AddressOf UsingBeforeElse)) + End Sub + + Private Sub UsingBeforeElse(outer As Boolean, f1 As Boolean, f2 As Boolean) + If outer Then + Using New MemoryStream() + If f1 Then Log("a") + End Using + Else + Log("b") + End If + Log("end") + End Sub +End Class From 66ff2ad8db62618c253de7de0081f4cdfdf6b352 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 16:09:06 +0000 Subject: [PATCH 02/14] Add a test conversion using the user's "Prefer braces: No" code style Visual Studio's Tools > Options code style reaches the converter through Solution.Options, which the simplifier honours, so tests need a way to convert as such a user would. Roslyn keeps these options internal, so the test runner sets the option by reflection. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- .../VBToCSPreferNoBracesConversion.cs | 66 +++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 Tests/TestRunners/VBToCSPreferNoBracesConversion.cs diff --git a/Tests/TestRunners/VBToCSPreferNoBracesConversion.cs b/Tests/TestRunners/VBToCSPreferNoBracesConversion.cs new file mode 100644 index 000000000..2d05dd4c8 --- /dev/null +++ b/Tests/TestRunners/VBToCSPreferNoBracesConversion.cs @@ -0,0 +1,66 @@ +using System; +using System.Collections.Generic; +using System.Reflection; +using System.Threading; +using System.Threading.Tasks; +using ICSharpCode.CodeConverter.Common; +using ICSharpCode.CodeConverter.CSharp; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Options; + +namespace ICSharpCode.CodeConverter.Tests.TestRunners; + +/// +/// Converts as if the user's C# code style says "Prefer braces: No" (csharp_prefer_braces = false). +/// In Visual Studio, Tools > Options code style preferences reach the converter through , +/// which falls back to, and the simplifier honours them. +/// Roslyn keeps its code style options internal, so this sets the option by reflection. +/// +public class VBToCSPreferNoBracesConversion : ILanguageConversion +{ + private readonly VBToCSConversion _baseConversion = new(); + + async Task ILanguageConversion.CreateProjectDocumentFromTreeAsync(SyntaxTree tree, IEnumerable references) + { + var document = await _baseConversion.CreateProjectDocumentFromTreeAsync(tree, references); + var solution = document.Project.Solution; + return solution.WithOptions(WithPreferBracesNone(solution.Options)).GetDocument(document.Id); + } + + private static OptionSet WithPreferBracesNone(OptionSet options) + { + var csharpWorkspacesAssembly = typeof(Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions).Assembly; + var preferBracesOption = (IOption)csharpWorkspacesAssembly + .GetType("Microsoft.CodeAnalysis.CSharp.CodeStyle.CSharpCodeStyleOptions", throwOnError: true) + .GetField("PreferBraces", BindingFlags.Public | BindingFlags.Static)!.GetValue(null); + var codeStyleOptionType = preferBracesOption.Type; + var notificationParameterType = codeStyleOptionType.GetConstructors()[0].GetParameters()[1].ParameterType; + var silentNotification = notificationParameterType.GetProperty("Silent", BindingFlags.Public | BindingFlags.Static)!.GetValue(null); + var preferBracesNone = Enum.Parse(codeStyleOptionType.GetGenericArguments()[0], "None"); + var preferBracesNoneValue = Activator.CreateInstance(codeStyleOptionType, preferBracesNone, silentNotification); + return options.WithChangedOption(new OptionKey(preferBracesOption), preferBracesNoneValue); + } + + string ILanguageConversion.TargetLanguage => _baseConversion.TargetLanguage; + + ConversionOptions ILanguageConversion.ConversionOptions { + get => _baseConversion.ConversionOptions; + set => _baseConversion.ConversionOptions = value; + } + + Task ILanguageConversion.CreateProjectContentsConverterAsync(Project project, + IProgress progress, CancellationToken cancellationToken) => + _baseConversion.CreateProjectContentsConverterAsync(project, progress, cancellationToken); + + Task ILanguageConversion.SingleSecondPassAsync(Document doc) => _baseConversion.SingleSecondPassAsync(doc); + SyntaxTree ILanguageConversion.CreateTree(string text) => _baseConversion.CreateTree(text); + List ILanguageConversion.FindSingleImportantChild(SyntaxNode annotatedNode) => _baseConversion.FindSingleImportantChild(annotatedNode); + bool ILanguageConversion.CanBeContainedByMethod(SyntaxNode node) => _baseConversion.CanBeContainedByMethod(node); + bool ILanguageConversion.MustBeContainedByClass(SyntaxNode node) => _baseConversion.MustBeContainedByClass(node); + string ILanguageConversion.WithSurroundingMethod(string text) => _baseConversion.WithSurroundingMethod(text); + string ILanguageConversion.WithSurroundingClass(string text) => _baseConversion.WithSurroundingClass(text); + SyntaxNode ILanguageConversion.GetSurroundedNode(IEnumerable descendantNodes, bool surroundedWithMethod) => _baseConversion.GetSurroundedNode(descendantNodes, surroundedWithMethod); + IReadOnlyCollection<(string, string)> ILanguageConversion.GetProjectTypeGuidMappings() => _baseConversion.GetProjectTypeGuidMappings(); + IEnumerable<(string, string)> ILanguageConversion.GetProjectFileReplacementRegexes() => _baseConversion.GetProjectFileReplacementRegexes(); + string ILanguageConversion.PostTransformProjectFile(string xml) => _baseConversion.PostTransformProjectFile(xml); +} From 2f9db195015d93bf674f152753c3a6f0d5c160a6 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 16:09:06 +0000 Subject: [PATCH 03/14] Keep braces that stop an else binding to a different if (#823) With "Prefer braces: No" (csharp_prefer_braces = false or when_multiline) Roslyn's simplifier (CSharpMiscellaneousReducer.SimplifyBlock) unwraps a single-statement block with no check for a following else, turning if (a) { if (b) x(); } else y(); into a dangling else. Still present in Roslyn main. Rather than overriding the user's code style (internal Roslyn API), exclude from simplification exactly the blocks whose removal would let the else bind to an if within them, using the existing CsWouldBeSimplifiedIncorrectly hook. Braces elsewhere are still removed as the user prefers. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- CodeConverter/Common/DocumentExtensions.cs | 34 ++- Tests/CSharp/SelfVerifyingTests.cs | 19 +- .../StatementTests/PreferNoBracesTests.cs | 196 ++++++++++++++++++ .../VBToCS/IfElseBindingTests.vb | 33 +++ 4 files changed, 280 insertions(+), 2 deletions(-) create mode 100644 Tests/CSharp/StatementTests/PreferNoBracesTests.cs diff --git a/CodeConverter/Common/DocumentExtensions.cs b/CodeConverter/Common/DocumentExtensions.cs index 442513604..fa857fed2 100644 --- a/CodeConverter/Common/DocumentExtensions.cs +++ b/CodeConverter/Common/DocumentExtensions.cs @@ -52,9 +52,41 @@ private static bool CsWouldBeSimplifiedIncorrectly(SyntaxNode n) { //"private int value = unchecked((int)0x80000010);" is simplified to "private int value = unchecked(0x80000010);" // which causes CS0266: "Cannot implicitly convert type 'uint' to 'int'" - return (n is CSSyntax.CastExpressionSyntax { Parent : CSSyntax.CheckedExpressionSyntax }); + return (n is CSSyntax.CastExpressionSyntax { Parent : CSSyntax.CheckedExpressionSyntax }) + || n is CSSyntax.BlockSyntax block && BracesGuardElseBinding(block); } + /// + /// Roslyn bug: when the user's code style is "Prefer braces: No" (csharp_prefer_braces = false or when_multiline), + /// the simplifier unwraps a single-statement block without checking what follows it, so in + /// if (a) { if (b) x(); } else y(); the else would then bind to the nearest if, i.e. if (b): https://github.com/icsharpcode/CodeConverter/issues/823 + /// The user's code style reaches us through the document's options (e.g. Visual Studio's Tools > Options) and is otherwise harmless, + /// so rather than overriding it, keep exactly the braces that stop an else changing which if it belongs to. + /// + private static bool BracesGuardElseBinding(CSSyntax.BlockSyntax block) => + block.Parent is CSSyntax.IfStatementSyntax { Else: not null } ifStatement + && ifStatement.Statement == block + && block.Statements.Count == 1 + && CouldEndWithIfWithoutElse(block.Statements[0]); + + /// + /// Whether an else placed right after this statement could bind to an if within it, assuming any single-statement block within it may lose its braces too. + /// + private static bool CouldEndWithIfWithoutElse(CSSyntax.StatementSyntax statement) => + statement switch { + CSSyntax.IfStatementSyntax { Else: null } => true, + CSSyntax.IfStatementSyntax { Else: { } elseClause } => CouldEndWithIfWithoutElse(elseClause.Statement), + CSSyntax.BlockSyntax { Statements.Count: 1 } block => CouldEndWithIfWithoutElse(block.Statements[0]), + CSSyntax.CommonForEachStatementSyntax s => CouldEndWithIfWithoutElse(s.Statement), + CSSyntax.ForStatementSyntax s => CouldEndWithIfWithoutElse(s.Statement), + CSSyntax.WhileStatementSyntax s => CouldEndWithIfWithoutElse(s.Statement), + CSSyntax.UsingStatementSyntax s => CouldEndWithIfWithoutElse(s.Statement), + CSSyntax.LockStatementSyntax s => CouldEndWithIfWithoutElse(s.Statement), + CSSyntax.FixedStatementSyntax s => CouldEndWithIfWithoutElse(s.Statement), + CSSyntax.LabeledStatementSyntax s => CouldEndWithIfWithoutElse(s.Statement), + _ => false + }; + public static async Task WithExpandedRootAsync(this Document document, CancellationToken cancellationToken) { if (document.Project.Language == LanguageNames.VisualBasic) { diff --git a/Tests/CSharp/SelfVerifyingTests.cs b/Tests/CSharp/SelfVerifyingTests.cs index 6e182f563..52672ad07 100644 --- a/Tests/CSharp/SelfVerifyingTests.cs +++ b/Tests/CSharp/SelfVerifyingTests.cs @@ -21,6 +21,12 @@ public async Task VisualBasicToCSharpAsync(NamedTest verifyConvertedTestPasses) await verifyConvertedTestPasses.Execute(); } + [Theory, MemberData(nameof(GetVisualBasicToCSharpPreferNoBracesTestData))] + public async Task VisualBasicToCSharpPreferNoBracesAsync(NamedTest verifyConvertedTestPasses) + { + await verifyConvertedTestPasses.Execute(); + } + /// /// Compile VB.NET source, convert it to C#, compile the conversion /// and return actions which run each corresponding pair of tests. @@ -32,4 +38,15 @@ public static IEnumerable GetVisualBasicToCSharpTestData() .Select(et => new object[] {et}) .ToArray(); } -} \ No newline at end of file + + /// + /// The user's "Prefer braces: No" code style lets the simplifier remove braces, so check that doesn't change which if an else binds to. + /// + public static IEnumerable GetVisualBasicToCSharpPreferNoBracesTestData() + { + var testFile = Path.Combine(TestConstants.GetTestDataDirectory(), "SelfVerifyingTests/VBToCS/IfElseBindingTests.vb"); + return SelfVerifyingTestFactory.GetSelfVerifyingFacts(testFile) + .Select(et => new object[] {et}) + .ToArray(); + } +} diff --git a/Tests/CSharp/StatementTests/PreferNoBracesTests.cs b/Tests/CSharp/StatementTests/PreferNoBracesTests.cs new file mode 100644 index 000000000..feddf8cc2 --- /dev/null +++ b/Tests/CSharp/StatementTests/PreferNoBracesTests.cs @@ -0,0 +1,196 @@ +using System.Threading.Tasks; +using ICSharpCode.CodeConverter.Tests.TestRunners; +using Xunit; + +namespace ICSharpCode.CodeConverter.Tests.CSharp.StatementTests; + +/// +/// The simplifier honours the user's "Prefer braces" code style, but must never let an else bind to a different if. +/// +public class PreferNoBracesTests : ConverterTestBase +{ + [Fact] + public async Task SingleLineIfAsLastStatementBeforeElseKeepsBracesIssue823Async() + { + await TestPreferNoBracesConversionAsync(@"Class TestClass + Private Sub TestMethod(OUTER As Boolean, FOO1 As Boolean, FOO2 As Boolean) + If OUTER Then + If FOO1 Then Bar1() : Exit Sub + Else 'NOT OUTER + If FOO2 Then + Bar2() + Exit Sub + End If + End If 'OUTER + End Sub + Private Sub Bar1() + End Sub + Private Sub Bar2() + End Sub +End Class", @" +internal partial class TestClass +{ + private void TestMethod(bool OUTER, bool FOO1, bool FOO2) + { + if (OUTER) + { + if (FOO1) + { + Bar1(); + return; + } + } + else if (FOO2) // NOT OUTER + { + Bar2(); + return; + } // OUTER + } + private void Bar1() + { + } + private void Bar2() + { + } +}"); + } + + [Fact] + public async Task BracesRemovedWhenOuterIfHasNoElseAsync() + { + await TestPreferNoBracesConversionAsync(@"Class TestClass + Private Sub TestMethod(a As Boolean, b As Boolean) + If a Then + If b Then Bar() + End If + End Sub + Private Sub Bar() + End Sub +End Class", @" +internal partial class TestClass +{ + private void TestMethod(bool a, bool b) + { + if (a) + if (b) + Bar(); + } + private void Bar() + { + } +}"); + } + + [Fact] + public async Task BracesRemovedWhenInnerIfHasElseAsync() + { + await TestPreferNoBracesConversionAsync(@"Class TestClass + Private Sub TestMethod(a As Boolean, b As Boolean) + If a Then + If b Then Bar() Else Baz() + Else + Baz() + End If + End Sub + Private Sub Bar() + End Sub + Private Sub Baz() + End Sub +End Class", @" +internal partial class TestClass +{ + private void TestMethod(bool a, bool b) + { + if (a) + if (b) + Bar(); + else + Baz(); + else + Baz(); + } + private void Bar() + { + } + private void Baz() + { + } +}"); + } + + [Fact] + public async Task OnlyOutermostBracesKeptForLoopEndingWithIfBeforeElseAsync() + { + await TestPreferNoBracesConversionAsync(@"Class TestClass + Private Sub TestMethod(a As Boolean, b As Boolean) + If a Then + For Each x In {1} + If b Then Bar() + Next + Else + Bar() + End If + End Sub + Private Sub Bar() + End Sub +End Class", @" +internal partial class TestClass +{ + private void TestMethod(bool a, bool b) + { + if (a) + { + foreach (var x in new[] { 1 }) + if (b) + Bar(); + } + else + Bar(); + } + private void Bar() + { + } +}"); + } + + [Fact] + public async Task ElseIfChainEndingWithoutElseKeepsBracesBeforeElseAsync() + { + await TestPreferNoBracesConversionAsync(@"Class TestClass + Private Sub TestMethod(a As Boolean, b As Boolean, c As Boolean) + If a Then + If b Then + Bar() + ElseIf c Then + Bar() + End If + Else + Bar() + End If + End Sub + Private Sub Bar() + End Sub +End Class", @" +internal partial class TestClass +{ + private void TestMethod(bool a, bool b, bool c) + { + if (a) + { + if (b) + Bar(); + else if (c) + Bar(); + } + else + Bar(); + } + private void Bar() + { + } +}"); + } + + private Task TestPreferNoBracesConversionAsync(string visualBasicCode, string expectedCsharpCode) => + AssertConvertedCodeResultEqualsAsync(visualBasicCode, expectedCsharpCode); +} diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/IfElseBindingTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/IfElseBindingTests.vb index bedc8788b..247ce0607 100644 --- a/Tests/TestData/SelfVerifyingTests/VBToCS/IfElseBindingTests.vb +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/IfElseBindingTests.vb @@ -203,4 +203,37 @@ Public Class IfElseBindingTests End If Log("end") End Sub + + Public Sub ForEachContainingIfBeforeElse() + Assert.Equal("b,end|b,end|b,end|b,end|end|end|a,end|a,end", RunAllCombinations(AddressOf ForEachBeforeElse)) + End Sub + + Private Sub ForEachBeforeElse(outer As Boolean, f1 As Boolean, f2 As Boolean) + If outer Then + For Each x In {1} + If f1 Then Log("a") + Next + Else + Log("b") + End If + Log("end") + End Sub + + + Public Sub ElseIfChainWithoutElseBeforeElse() + Assert.Equal("c,end|c,end|c,end|c,end|end|b,end|a,end|a,end", RunAllCombinations(AddressOf ElseIfChainBeforeElse)) + End Sub + + Private Sub ElseIfChainBeforeElse(outer As Boolean, f1 As Boolean, f2 As Boolean) + If outer Then + If f1 Then + Log("a") + ElseIf f2 Then + Log("b") + End If + Else + Log("c") + End If + Log("end") + End Sub End Class From 02ea50309187d946ad368e89b9d67ff7e487de7f Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 16:13:45 +0000 Subject: [PATCH 04/14] Keep braces around a declaration or label the simplifier would embed (#823) The same "Prefer braces: No" brace removal in Roslyn's simplifier also unwraps a block whose only statement is a local declaration, local function or label, giving CS1023 (e.g. if (a) int x = F();). Keep braces for those too, and only consider blocks that are embedded statements, which are the only ones the simplifier unwraps. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- CodeConverter/Common/DocumentExtensions.cs | 39 ++++++++++------ .../StatementTests/PreferNoBracesTests.cs | 44 +++++++++++++++++++ 2 files changed, 69 insertions(+), 14 deletions(-) diff --git a/CodeConverter/Common/DocumentExtensions.cs b/CodeConverter/Common/DocumentExtensions.cs index fa857fed2..a87a83989 100644 --- a/CodeConverter/Common/DocumentExtensions.cs +++ b/CodeConverter/Common/DocumentExtensions.cs @@ -53,37 +53,48 @@ private static bool CsWouldBeSimplifiedIncorrectly(SyntaxNode n) //"private int value = unchecked((int)0x80000010);" is simplified to "private int value = unchecked(0x80000010);" // which causes CS0266: "Cannot implicitly convert type 'uint' to 'int'" return (n is CSSyntax.CastExpressionSyntax { Parent : CSSyntax.CheckedExpressionSyntax }) - || n is CSSyntax.BlockSyntax block && BracesGuardElseBinding(block); + || n is CSSyntax.BlockSyntax block && MustKeepBraces(block); } /// - /// Roslyn bug: when the user's code style is "Prefer braces: No" (csharp_prefer_braces = false or when_multiline), - /// the simplifier unwraps a single-statement block without checking what follows it, so in - /// if (a) { if (b) x(); } else y(); the else would then bind to the nearest if, i.e. if (b): https://github.com/icsharpcode/CodeConverter/issues/823 - /// The user's code style reaches us through the document's options (e.g. Visual Studio's Tools > Options) and is otherwise harmless, - /// so rather than overriding it, keep exactly the braces that stop an else changing which if it belongs to. + /// Roslyn bug: with the user's code style "Prefer braces: No" (csharp_prefer_braces = false or when_multiline), + /// the simplifier unwraps any single-statement block that is an embedded statement, without checking that: + /// + /// the statement can be embedded: if (a) int x = F(); is CS1023 + /// a following else still binds to the same if: in if (a) { if (b) x(); } else y(); it would bind to if (b) https://github.com/icsharpcode/CodeConverter/issues/823 + /// + /// The code style reaches us through the document's options (e.g. Visual Studio's Tools > Options), and Roslyn keeps the option internal. + /// Rather than override it, keep only the braces it would wrongly remove. /// - private static bool BracesGuardElseBinding(CSSyntax.BlockSyntax block) => - block.Parent is CSSyntax.IfStatementSyntax { Else: not null } ifStatement - && ifStatement.Statement == block - && block.Statements.Count == 1 - && CouldEndWithIfWithoutElse(block.Statements[0]); + private static bool MustKeepBraces(CSSyntax.BlockSyntax block) => + IsEmbeddedStatement(block) && block.Statements.Count == 1 + && (!CanBeEmbedded(block.Statements[0]) || IsFollowedByElse(block) && CouldEndWithIfWithoutElse(block.Statements[0])); + + private static bool IsEmbeddedStatement(CSSyntax.BlockSyntax block) => + block.Parent is CSSyntax.IfStatementSyntax or CSSyntax.ElseClauseSyntax or CSSyntax.CommonForEachStatementSyntax + or CSSyntax.ForStatementSyntax or CSSyntax.WhileStatementSyntax or CSSyntax.DoStatementSyntax + or CSSyntax.UsingStatementSyntax or CSSyntax.LockStatementSyntax or CSSyntax.FixedStatementSyntax; + + private static bool CanBeEmbedded(CSSyntax.StatementSyntax statement) => + statement is not (CSSyntax.LocalDeclarationStatementSyntax or CSSyntax.LocalFunctionStatementSyntax or CSSyntax.LabeledStatementSyntax); + + private static bool IsFollowedByElse(CSSyntax.BlockSyntax block) => + block.Parent is CSSyntax.IfStatementSyntax { Else: not null } ifStatement && ifStatement.Statement == block; /// - /// Whether an else placed right after this statement could bind to an if within it, assuming any single-statement block within it may lose its braces too. + /// Whether an else placed right after this statement could bind to an if within it, assuming any block within it that can lose its braces does. /// private static bool CouldEndWithIfWithoutElse(CSSyntax.StatementSyntax statement) => statement switch { CSSyntax.IfStatementSyntax { Else: null } => true, CSSyntax.IfStatementSyntax { Else: { } elseClause } => CouldEndWithIfWithoutElse(elseClause.Statement), - CSSyntax.BlockSyntax { Statements.Count: 1 } block => CouldEndWithIfWithoutElse(block.Statements[0]), + CSSyntax.BlockSyntax { Statements.Count: 1 } block when IsEmbeddedStatement(block) && CanBeEmbedded(block.Statements[0]) => CouldEndWithIfWithoutElse(block.Statements[0]), CSSyntax.CommonForEachStatementSyntax s => CouldEndWithIfWithoutElse(s.Statement), CSSyntax.ForStatementSyntax s => CouldEndWithIfWithoutElse(s.Statement), CSSyntax.WhileStatementSyntax s => CouldEndWithIfWithoutElse(s.Statement), CSSyntax.UsingStatementSyntax s => CouldEndWithIfWithoutElse(s.Statement), CSSyntax.LockStatementSyntax s => CouldEndWithIfWithoutElse(s.Statement), CSSyntax.FixedStatementSyntax s => CouldEndWithIfWithoutElse(s.Statement), - CSSyntax.LabeledStatementSyntax s => CouldEndWithIfWithoutElse(s.Statement), _ => false }; diff --git a/Tests/CSharp/StatementTests/PreferNoBracesTests.cs b/Tests/CSharp/StatementTests/PreferNoBracesTests.cs index feddf8cc2..506aaab3c 100644 --- a/Tests/CSharp/StatementTests/PreferNoBracesTests.cs +++ b/Tests/CSharp/StatementTests/PreferNoBracesTests.cs @@ -191,6 +191,50 @@ private void Bar() }"); } + [Fact] + public async Task BracesKeptAroundStatementsThatCannotBeEmbeddedAsync() + { + await TestPreferNoBracesConversionAsync(@"Class TestClass + Private Sub TestMethod(a As Boolean) + If a Then + Dim x = F() + Else + Dim y = F() + End If + If a Then +label1: + End If + End Sub + Private Function F() As Integer + Return 1 + End Function +End Class", @" +internal partial class TestClass +{ + private void TestMethod(bool a) + { + if (a) + { + int x = F(); + } + else + { + int y = F(); + } + if (a) + { + label1: + ; + + } + } + private int F() + { + return 1; + } +}"); + } + private Task TestPreferNoBracesConversionAsync(string visualBasicCode, string expectedCsharpCode) => AssertConvertedCodeResultEqualsAsync(visualBasicCode, expectedCsharpCode); } From 0e307c68267729ab5fc843e12ed0f1ed638fcd14 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 16:21:49 +0000 Subject: [PATCH 05/14] Test a For loop ending with an if before an else (#823) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- .../VBToCS/IfElseBindingTests.vb | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/IfElseBindingTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/IfElseBindingTests.vb index 247ce0607..c474752b3 100644 --- a/Tests/TestData/SelfVerifyingTests/VBToCS/IfElseBindingTests.vb +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/IfElseBindingTests.vb @@ -236,4 +236,19 @@ Public Class IfElseBindingTests End If Log("end") End Sub + + Public Sub ForContainingIfBeforeElse() + Assert.Equal("b,end|b,end|b,end|b,end|end|end|a,end|a,end", RunAllCombinations(AddressOf ForBeforeElse)) + End Sub + + Private Sub ForBeforeElse(outer As Boolean, f1 As Boolean, f2 As Boolean) + If outer Then + For i = 1 To 1 + If f1 Then Log("a") + Next + Else + Log("b") + End If + Log("end") + End Sub End Class From e308beb019bdb053607f64afa2da39e113b40d0a Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 16:22:15 +0000 Subject: [PATCH 06/14] Drop the fixed statement from the brace guard VB has no fixed statement, so the converter never emits one and the simplifier doesn't unwrap its block anyway. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- CodeConverter/Common/DocumentExtensions.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/CodeConverter/Common/DocumentExtensions.cs b/CodeConverter/Common/DocumentExtensions.cs index a87a83989..7ede8b393 100644 --- a/CodeConverter/Common/DocumentExtensions.cs +++ b/CodeConverter/Common/DocumentExtensions.cs @@ -73,7 +73,7 @@ private static bool MustKeepBraces(CSSyntax.BlockSyntax block) => private static bool IsEmbeddedStatement(CSSyntax.BlockSyntax block) => block.Parent is CSSyntax.IfStatementSyntax or CSSyntax.ElseClauseSyntax or CSSyntax.CommonForEachStatementSyntax or CSSyntax.ForStatementSyntax or CSSyntax.WhileStatementSyntax or CSSyntax.DoStatementSyntax - or CSSyntax.UsingStatementSyntax or CSSyntax.LockStatementSyntax or CSSyntax.FixedStatementSyntax; + or CSSyntax.UsingStatementSyntax or CSSyntax.LockStatementSyntax; private static bool CanBeEmbedded(CSSyntax.StatementSyntax statement) => statement is not (CSSyntax.LocalDeclarationStatementSyntax or CSSyntax.LocalFunctionStatementSyntax or CSSyntax.LabeledStatementSyntax); @@ -94,7 +94,6 @@ private static bool CouldEndWithIfWithoutElse(CSSyntax.StatementSyntax statement CSSyntax.WhileStatementSyntax s => CouldEndWithIfWithoutElse(s.Statement), CSSyntax.UsingStatementSyntax s => CouldEndWithIfWithoutElse(s.Statement), CSSyntax.LockStatementSyntax s => CouldEndWithIfWithoutElse(s.Statement), - CSSyntax.FixedStatementSyntax s => CouldEndWithIfWithoutElse(s.Statement), _ => false }; From 67a9f4cd3160cd3be6c68559fb94ccb72acb3cb8 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 16:28:57 +0000 Subject: [PATCH 07/14] Move CanBeEmbedded to the shared C# syntax extensions Pure refactor so the converter's own block unpacking can use the same rule. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- CodeConverter/CSharp/Extensions.cs | 6 ++++++ CodeConverter/Common/DocumentExtensions.cs | 7 ++----- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/CodeConverter/CSharp/Extensions.cs b/CodeConverter/CSharp/Extensions.cs index df6292d4e..12e41a287 100644 --- a/CodeConverter/CSharp/Extensions.cs +++ b/CodeConverter/CSharp/Extensions.cs @@ -59,6 +59,12 @@ public static StatementSyntax UnpackPossiblyNestedBlock(this BlockSyntax block) return statementSyntaxs.Count == 1 ? statementSyntaxs[0] : block; } + /// + /// C# forbids a declaration or labeled statement as the embedded statement of an if, else, loop, using or lock (CS1023). + /// + public static bool CanBeEmbedded(this StatementSyntax statement) => + statement is not (LocalDeclarationStatementSyntax or LocalFunctionStatementSyntax or LabeledStatementSyntax); + private static bool ContainsNestedStatements(this BlockSyntax block) { return block.Statements.Any(HasDescendantCSharpStatement); diff --git a/CodeConverter/Common/DocumentExtensions.cs b/CodeConverter/Common/DocumentExtensions.cs index 7ede8b393..055ad2745 100644 --- a/CodeConverter/Common/DocumentExtensions.cs +++ b/CodeConverter/Common/DocumentExtensions.cs @@ -68,16 +68,13 @@ private static bool CsWouldBeSimplifiedIncorrectly(SyntaxNode n) /// private static bool MustKeepBraces(CSSyntax.BlockSyntax block) => IsEmbeddedStatement(block) && block.Statements.Count == 1 - && (!CanBeEmbedded(block.Statements[0]) || IsFollowedByElse(block) && CouldEndWithIfWithoutElse(block.Statements[0])); + && (!block.Statements[0].CanBeEmbedded() || IsFollowedByElse(block) && CouldEndWithIfWithoutElse(block.Statements[0])); private static bool IsEmbeddedStatement(CSSyntax.BlockSyntax block) => block.Parent is CSSyntax.IfStatementSyntax or CSSyntax.ElseClauseSyntax or CSSyntax.CommonForEachStatementSyntax or CSSyntax.ForStatementSyntax or CSSyntax.WhileStatementSyntax or CSSyntax.DoStatementSyntax or CSSyntax.UsingStatementSyntax or CSSyntax.LockStatementSyntax; - private static bool CanBeEmbedded(CSSyntax.StatementSyntax statement) => - statement is not (CSSyntax.LocalDeclarationStatementSyntax or CSSyntax.LocalFunctionStatementSyntax or CSSyntax.LabeledStatementSyntax); - private static bool IsFollowedByElse(CSSyntax.BlockSyntax block) => block.Parent is CSSyntax.IfStatementSyntax { Else: not null } ifStatement && ifStatement.Statement == block; @@ -88,7 +85,7 @@ private static bool CouldEndWithIfWithoutElse(CSSyntax.StatementSyntax statement statement switch { CSSyntax.IfStatementSyntax { Else: null } => true, CSSyntax.IfStatementSyntax { Else: { } elseClause } => CouldEndWithIfWithoutElse(elseClause.Statement), - CSSyntax.BlockSyntax { Statements.Count: 1 } block when IsEmbeddedStatement(block) && CanBeEmbedded(block.Statements[0]) => CouldEndWithIfWithoutElse(block.Statements[0]), + CSSyntax.BlockSyntax { Statements.Count: 1 } block when IsEmbeddedStatement(block) && block.Statements[0].CanBeEmbedded() => CouldEndWithIfWithoutElse(block.Statements[0]), CSSyntax.CommonForEachStatementSyntax s => CouldEndWithIfWithoutElse(s.Statement), CSSyntax.ForStatementSyntax s => CouldEndWithIfWithoutElse(s.Statement), CSSyntax.WhileStatementSyntax s => CouldEndWithIfWithoutElse(s.Statement), From a44155cff016ebdcbe2b0ccbe087b096734323f0 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 16:35:01 +0000 Subject: [PATCH 08/14] Keep braces around a lone declaration or label in converted bodies UnpackNonNestedBlock and UnpackPossiblyNestedBlock unwrapped a body whose only statement is a local declaration, giving e.g. while (a) int z = F(); (CS1023) for single-line If, loops, SyncLock and Using bodies. They now use the same CanBeEmbedded rule as the simplifier guard. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- CodeConverter/CSharp/Extensions.cs | 7 +- .../StatementTests/MethodStatementTests.cs | 93 +++++++++++++++++++ .../VBToCS/LoneDeclarationBodyTests.vb | 42 +++++++++ 3 files changed, 139 insertions(+), 3 deletions(-) create mode 100644 Tests/TestData/SelfVerifyingTests/VBToCS/LoneDeclarationBodyTests.vb diff --git a/CodeConverter/CSharp/Extensions.cs b/CodeConverter/CSharp/Extensions.cs index 12e41a287..20d6b411e 100644 --- a/CodeConverter/CSharp/Extensions.cs +++ b/CodeConverter/CSharp/Extensions.cs @@ -8,11 +8,12 @@ internal static class Extensions /// Returns the single statement in a block if it has no nested statements. /// If it has nested statements, and the surrounding block was removed, it could be ambiguous, /// e.g. if (...) { if (...) return null; } else return ""; - /// Unbundling the middle if statement would bind the else to it, rather than the outer if statement + /// Unbundling the middle if statement would bind the else to it, rather than the outer if statement. + /// A declaration or label can't be unpacked either (). /// public static StatementSyntax UnpackNonNestedBlock(this BlockSyntax block) { - return block.Statements.Count == 1 && !block.ContainsNestedStatements() ? block.Statements[0] : block; + return block.Statements.Count == 1 && block.Statements[0].CanBeEmbedded() && !block.ContainsNestedStatements() ? block.Statements[0] : block; } /// @@ -56,7 +57,7 @@ public static bool TryUnpackSingleExpressionFromStatement(this StatementSyntax s public static StatementSyntax UnpackPossiblyNestedBlock(this BlockSyntax block) { SyntaxList statementSyntaxs = block.Statements; - return statementSyntaxs.Count == 1 ? statementSyntaxs[0] : block; + return statementSyntaxs.Count == 1 && statementSyntaxs[0].CanBeEmbedded() ? statementSyntaxs[0] : block; } /// diff --git a/Tests/CSharp/StatementTests/MethodStatementTests.cs b/Tests/CSharp/StatementTests/MethodStatementTests.cs index 795fb853d..ab1982841 100644 --- a/Tests/CSharp/StatementTests/MethodStatementTests.cs +++ b/Tests/CSharp/StatementTests/MethodStatementTests.cs @@ -909,6 +909,99 @@ private void Bar2() }"); } + [Fact] + public async Task BodyWithLoneDeclarationOrLabelKeepsBracesAsync() + { + await TestConversionVisualBasicToCSharpAsync(@"Class TestClass + Private Sub TestMethod(a As Boolean, xs As Integer()) + If a Then Dim v = F() + If a Then + Dim w = F() + Else + Dim x = F() + End If + While a + Dim y = F() + End While + Do + Dim z = F() + Loop While a + For i = 1 To 2 + Dim i2 = F() + Next + For Each x In xs + Dim x2 = F() + Next + SyncLock xs + Dim l = F() + End SyncLock + Using New System.IO.MemoryStream() + Dim u = F() + End Using + While a +label1: + End While + End Sub + Private Function F() As Integer + Return 1 + End Function +End Class", @"using System.IO; + +internal partial class TestClass +{ + private void TestMethod(bool a, int[] xs) + { + if (a) + { + int v = F(); + } + if (a) + { + int w = F(); + } + else + { + int x = F(); + } + while (a) + { + int y = F(); + } + do + { + int z = F(); + } + while (a); + for (int i = 1; i <= 2; i++) + { + int i2 = F(); + } + foreach (var x in xs) + { + int x2 = F(); + } + lock (xs) + { + int l = F(); + } + using (new MemoryStream()) + { + int u = F(); + } + while (a) + { + label1: + ; + + } + } + private int F() + { + return 1; + } +}"); + } + [Fact] public async Task NestedBlockStatementsKeepSameNestingAsync() { diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/LoneDeclarationBodyTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/LoneDeclarationBodyTests.vb new file mode 100644 index 000000000..55c702b93 --- /dev/null +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/LoneDeclarationBodyTests.vb @@ -0,0 +1,42 @@ +Imports System +Imports System.Collections.Generic +Imports System.IO +Imports Xunit + +''' +''' A body whose only statement is a declaration must still run its initializer each time (C# can't embed a declaration without braces). +''' +Public Class LoneDeclarationBodyTests + Private ReadOnly _log As New List(Of String) + + Private Function Log(s As String) As Integer + _log.Add(s) + Return _log.Count + End Function + + + Public Sub LoneDeclarationBodiesRunTheirInitializers() + Dim a = True + If a Then Dim v = Log("if") + Dim n = 0 + While n < 2 + Dim y = Log("while" & n) + Math.Min(0, Threading.Interlocked.Increment(n)) + End While + Do + Dim z = Log("do") + Loop While False + For i = 1 To 2 + Dim i2 = Log("for" & i) + Next + For Each x In {"a", "b"} + Dim x2 = Log("each" & x) + Next + SyncLock _log + Dim l = Log("lock") + End SyncLock + Using New MemoryStream() + Dim u = Log("using") + End Using + Assert.Equal("if,while0,while1,do,for1,for2,eacha,eachb,lock,using", String.Join(",", _log)) + End Sub +End Class From 50c5f2f6d6214357a4671eef846df4c149966010 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 16:39:35 +0000 Subject: [PATCH 09/14] Test braces kept for a loop, lock or using ending with an if before else Covers the loop, lock and using arms of the dangling-else guard under "Prefer braces: No" (review round 1). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- .../StatementTests/PreferNoBracesTests.cs | 66 +++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/Tests/CSharp/StatementTests/PreferNoBracesTests.cs b/Tests/CSharp/StatementTests/PreferNoBracesTests.cs index 506aaab3c..07f8f0c1c 100644 --- a/Tests/CSharp/StatementTests/PreferNoBracesTests.cs +++ b/Tests/CSharp/StatementTests/PreferNoBracesTests.cs @@ -235,6 +235,72 @@ private int F() }"); } + [Fact] + public async Task LoopLockAndUsingEndingWithIfKeepBracesBeforeElseAsync() + { + await TestPreferNoBracesConversionAsync(@"Class TestClass + Private Sub TestMethod(a As Boolean, b As Boolean) + If a Then + For i = 1 To 2 + If b Then X() + Next + Else + X() + End If + If a Then + SyncLock Me + If b Then X() + End SyncLock + Else + X() + End If + If a Then + Using New System.IO.MemoryStream() + If b Then X() + End Using + Else + X() + End If + End Sub + Private Sub X() + End Sub +End Class", @"using System.IO; + +internal partial class TestClass +{ + private void TestMethod(bool a, bool b) + { + if (a) + { + for (int i = 1; i <= 2; i++) + if (b) + X(); + } + else + X(); + if (a) + { + lock (this) + if (b) + X(); + } + else + X(); + if (a) + { + using (new MemoryStream()) + if (b) + X(); + } + else + X(); + } + private void X() + { + } +}"); + } + private Task TestPreferNoBracesConversionAsync(string visualBasicCode, string expectedCsharpCode) => AssertConvertedCodeResultEqualsAsync(visualBasicCode, expectedCsharpCode); } From fc6d2321ab6528d502881fa4c4da358d6e44ae71 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 16:40:31 +0000 Subject: [PATCH 10/14] Keep braces that carry a comment under "Prefer braces: No" Roslyn's unwrap of a single-statement block drops comments attached to the braces, e.g. a trailing comment on End If (review round 1). Losing a user's comment is worse than keeping their braces. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- CodeConverter/Common/DocumentExtensions.cs | 10 +++- .../StatementTests/PreferNoBracesTests.cs | 56 +++++++++++++++++++ 2 files changed, 65 insertions(+), 1 deletion(-) diff --git a/CodeConverter/Common/DocumentExtensions.cs b/CodeConverter/Common/DocumentExtensions.cs index 055ad2745..96e304a26 100644 --- a/CodeConverter/Common/DocumentExtensions.cs +++ b/CodeConverter/Common/DocumentExtensions.cs @@ -68,7 +68,15 @@ private static bool CsWouldBeSimplifiedIncorrectly(SyntaxNode n) /// private static bool MustKeepBraces(CSSyntax.BlockSyntax block) => IsEmbeddedStatement(block) && block.Statements.Count == 1 - && (!block.Statements[0].CanBeEmbedded() || IsFollowedByElse(block) && CouldEndWithIfWithoutElse(block.Statements[0])); + && (!block.Statements[0].CanBeEmbedded() || IsFollowedByElse(block) && CouldEndWithIfWithoutElse(block.Statements[0]) + || HasComment(block.OpenBraceToken) || HasComment(block.CloseBraceToken)); + + /// + /// The unwrap drops comments attached to the removed braces, and losing a user's comment is worse than keeping their braces. + /// + private static bool HasComment(SyntaxToken braceToken) => + braceToken.LeadingTrivia.Concat(braceToken.TrailingTrivia) + .Any(t => t.IsKind(CS.SyntaxKind.SingleLineCommentTrivia) || t.IsKind(CS.SyntaxKind.MultiLineCommentTrivia)); private static bool IsEmbeddedStatement(CSSyntax.BlockSyntax block) => block.Parent is CSSyntax.IfStatementSyntax or CSSyntax.ElseClauseSyntax or CSSyntax.CommonForEachStatementSyntax diff --git a/Tests/CSharp/StatementTests/PreferNoBracesTests.cs b/Tests/CSharp/StatementTests/PreferNoBracesTests.cs index 07f8f0c1c..4cf9ddd46 100644 --- a/Tests/CSharp/StatementTests/PreferNoBracesTests.cs +++ b/Tests/CSharp/StatementTests/PreferNoBracesTests.cs @@ -235,6 +235,62 @@ private int F() }"); } + [Fact] + public async Task CommentsOnRemovableBracesKeepBracesAsync() + { + await TestPreferNoBracesConversionAsync(@"Class TestClass + Private Sub TestMethod(a As Boolean, b As Boolean) + If a Then + If b Then X() ' c1 + Else ' c2 + Y() ' c3 + End If ' c4 + If a Then + If b Then ' e0 + X() ' e1 + End If ' e2 + Else + Y() + End If + End Sub + Private Sub X() + End Sub + Private Sub Y() + End Sub +End Class", @" +internal partial class TestClass +{ + private void TestMethod(bool a, bool b) + { + if (a) + { + if (b) + X(); // c1 + } + else // c2 + { + Y(); + } // c3 + // c4 + if (a) + { + if (b) // e0 + { + X(); // e1 + } // e2 + } + else + Y(); + } + private void X() + { + } + private void Y() + { + } +}"); + } + [Fact] public async Task LoopLockAndUsingEndingWithIfKeepBracesBeforeElseAsync() { From 3f46612b191a5601814b358ea0a5f5aba2473bbc Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 16:44:49 +0000 Subject: [PATCH 11/14] Move the reflected "Prefer braces" option accessor into the converter Pure refactor: the test runner's reflection over Roslyn's internal CSharpCodeStyleOptions.PreferBraces becomes a cached accessor that returns null instead of throwing, ready for the converter to read and override it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- .../CachedReflectedPreferBracesOption.cs | 69 +++++++++++++++++++ .../VBToCSPreferNoBracesConversion.cs | 20 +----- 2 files changed, 71 insertions(+), 18 deletions(-) create mode 100644 CodeConverter/CSharp/CachedReflectedPreferBracesOption.cs diff --git a/CodeConverter/CSharp/CachedReflectedPreferBracesOption.cs b/CodeConverter/CSharp/CachedReflectedPreferBracesOption.cs new file mode 100644 index 000000000..85f67dd3e --- /dev/null +++ b/CodeConverter/CSharp/CachedReflectedPreferBracesOption.cs @@ -0,0 +1,69 @@ +using System.Reflection; +using Microsoft.CodeAnalysis.Options; + +namespace ICSharpCode.CodeConverter.CSharp; + +/// +/// The C# code style option "Prefer braces" (csharp_prefer_braces), which Roslyn keeps internal: +/// https://github.com/dotnet/roslyn/blob/main/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/CodeStyle/CSharpCodeStyleOptions.cs +/// +/// +/// Use with the same care as : an internal rename in another Roslyn version breaks this, +/// so each member returns null rather than throwing, and callers must have a fallback. +/// +internal static class CachedReflectedPreferBracesOption +{ + private static readonly Lazy PreferBracesOption = new(FindPreferBracesOption); + + /// The name of a Roslyn PreferBracesPreference: None, WhenMultiline or Always + /// The options with "Prefer braces" set to , or null if it can't be set (checked by reading it back) + public static OptionSet WithPreferBraces(this OptionSet options, string preference) + { + try { + if (PreferBracesOption.Value is not { } option) return null; + var newOptions = options.WithChangedOption(new OptionKey(option), CreateCodeStyleOption(option.Type, preference)); + return newOptions.GetPreferBraces() == preference ? newOptions : null; + } catch (Exception) { + return null; + } + } + + /// The name of the "Prefer braces" PreferBracesPreference in , or null if it can't be read + public static string GetPreferBraces(this OptionSet options) + { + try { + if (PreferBracesOption.Value is not { } option) return null; + var codeStyleOption = options.GetOption(new OptionKey(option)); + return codeStyleOption?.GetType().GetProperty("Value", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) + ?.GetValue(codeStyleOption)?.ToString(); + } catch (Exception) { + return null; + } + } + + private static IOption FindPreferBracesOption() + { + try { + return typeof(CS.Formatting.CSharpFormattingOptions).Assembly + .GetType("Microsoft.CodeAnalysis.CSharp.CodeStyle.CSharpCodeStyleOptions") + ?.GetField("PreferBraces", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static) + ?.GetValue(null) as IOption; + } catch (Exception) { + return null; + } + } + + /// + /// Creates new CodeStyleOption2<PreferBracesPreference>(preference, NotificationOption2.Silent) + /// + private static object CreateCodeStyleOption(Type codeStyleOptionType, string preference) + { + var constructor = codeStyleOptionType.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) + .Single(c => c.GetParameters().Length == 2); + var notificationType = constructor.GetParameters()[1].ParameterType; + var silent = notificationType.GetProperty("Silent", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static)?.GetValue(null) + ?? notificationType.GetField("Silent", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static)?.GetValue(null); + var preferenceValue = Enum.Parse(codeStyleOptionType.GetGenericArguments()[0], preference); + return constructor.Invoke(new[] { preferenceValue, silent }); + } +} diff --git a/Tests/TestRunners/VBToCSPreferNoBracesConversion.cs b/Tests/TestRunners/VBToCSPreferNoBracesConversion.cs index 2d05dd4c8..f4fcbf1aa 100644 --- a/Tests/TestRunners/VBToCSPreferNoBracesConversion.cs +++ b/Tests/TestRunners/VBToCSPreferNoBracesConversion.cs @@ -1,12 +1,10 @@ using System; using System.Collections.Generic; -using System.Reflection; using System.Threading; using System.Threading.Tasks; using ICSharpCode.CodeConverter.Common; using ICSharpCode.CodeConverter.CSharp; using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Options; namespace ICSharpCode.CodeConverter.Tests.TestRunners; @@ -14,7 +12,6 @@ namespace ICSharpCode.CodeConverter.Tests.TestRunners; /// Converts as if the user's C# code style says "Prefer braces: No" (csharp_prefer_braces = false). /// In Visual Studio, Tools > Options code style preferences reach the converter through , /// which falls back to, and the simplifier honours them. -/// Roslyn keeps its code style options internal, so this sets the option by reflection. /// public class VBToCSPreferNoBracesConversion : ILanguageConversion { @@ -24,21 +21,8 @@ async Task ILanguageConversion.CreateProjectDocumentFromTreeAsync(Synt { var document = await _baseConversion.CreateProjectDocumentFromTreeAsync(tree, references); var solution = document.Project.Solution; - return solution.WithOptions(WithPreferBracesNone(solution.Options)).GetDocument(document.Id); - } - - private static OptionSet WithPreferBracesNone(OptionSet options) - { - var csharpWorkspacesAssembly = typeof(Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions).Assembly; - var preferBracesOption = (IOption)csharpWorkspacesAssembly - .GetType("Microsoft.CodeAnalysis.CSharp.CodeStyle.CSharpCodeStyleOptions", throwOnError: true) - .GetField("PreferBraces", BindingFlags.Public | BindingFlags.Static)!.GetValue(null); - var codeStyleOptionType = preferBracesOption.Type; - var notificationParameterType = codeStyleOptionType.GetConstructors()[0].GetParameters()[1].ParameterType; - var silentNotification = notificationParameterType.GetProperty("Silent", BindingFlags.Public | BindingFlags.Static)!.GetValue(null); - var preferBracesNone = Enum.Parse(codeStyleOptionType.GetGenericArguments()[0], "None"); - var preferBracesNoneValue = Activator.CreateInstance(codeStyleOptionType, preferBracesNone, silentNotification); - return options.WithChangedOption(new OptionKey(preferBracesOption), preferBracesNoneValue); + var options = solution.Options.WithPreferBraces("None") ?? throw new InvalidOperationException("Can't set the \"Prefer braces\" option on this Roslyn version"); + return solution.WithOptions(options).GetDocument(document.Id); } string ILanguageConversion.TargetLanguage => _baseConversion.TargetLanguage; From 72f945b5da8aaaa9fb4ba29eaab5ef4d0fee1218 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 16:47:00 +0000 Subject: [PATCH 12/14] Override the user's "Prefer braces" preference to Always when simplifying The simplifier's unwrap of single-statement blocks under "Prefer braces: No" is unsafe (dangling else, CS1023, lost comments), and the converter already decides where braces go. Override the internal option by reflection, checked by reading it back. The existing MustKeepBraces guard stays on as the fallback for Roslyn versions where the override fails. PreferNoBraces tests now check both paths: the override path matches the default conversion, and a guard-only runner (forced by an AsyncLocal test switch) keeps the existing expectations. The self-verifying IfElseBindingTests run on both paths. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- CodeConverter/Common/DocumentExtensions.cs | 25 +++++++++++++++---- Tests/CSharp/SelfVerifyingTests.cs | 17 +++++++++++-- .../StatementTests/PreferNoBracesTests.cs | 14 ++++++++--- .../VBToCSPreferNoBracesConversion.cs | 17 ++++++++++++- 4 files changed, 62 insertions(+), 11 deletions(-) diff --git a/CodeConverter/Common/DocumentExtensions.cs b/CodeConverter/Common/DocumentExtensions.cs index 96e304a26..2b1cad423 100644 --- a/CodeConverter/Common/DocumentExtensions.cs +++ b/CodeConverter/Common/DocumentExtensions.cs @@ -8,6 +8,11 @@ namespace ICSharpCode.CodeConverter.Common; internal static class DocumentExtensions { + /// + /// Lets tests exercise alone, as on a Roslyn version where can't override the "Prefer braces" preference + /// + internal static AsyncLocal DisableBracesOverrideForTesting { get; } = new(); + public static async Task SimplifyStatementsAsync(this Document convertedDocument, string unresolvedTypeDiagnosticId, CancellationToken cancellationToken) where TUsingDirectiveSyntax : SyntaxNode { @@ -62,9 +67,11 @@ private static bool CsWouldBeSimplifiedIncorrectly(SyntaxNode n) /// /// the statement can be embedded: if (a) int x = F(); is CS1023 /// a following else still binds to the same if: in if (a) { if (b) x(); } else y(); it would bind to if (b) https://github.com/icsharpcode/CodeConverter/issues/823 + /// no comment is attached to the braces it drops /// - /// The code style reaches us through the document's options (e.g. Visual Studio's Tools > Options), and Roslyn keeps the option internal. - /// Rather than override it, keep only the braces it would wrongly remove. + /// See SimplifyBlock in https://github.com/dotnet/roslyn/blob/main/src/Workspaces/CSharp/Portable/Simplification/Reducers/CSharpMiscellaneousReducer.cs + /// The code style reaches us through the document's options (e.g. Visual Studio's Tools > Options). + /// overrides it, but Roslyn keeps the option internal, so where that fails, keep the braces it would wrongly remove. /// private static bool MustKeepBraces(CSSyntax.BlockSyntax block) => IsEmbeddedStatement(block) && block.Statements.Count == 1 @@ -162,11 +169,19 @@ private static SyntaxNode WithWarningAnnotation(SyntaxNode node, string warningT { return node.WithAdditionalAnnotations(new SyntaxAnnotation(AnnotationConstants.ConversionErrorAnnotationKind, warningText)); } - private static DocumentOptionSet GetVBOptions(DocumentOptionSet options) + private static OptionSet GetVBOptions(DocumentOptionSet options) { return options; } - private static DocumentOptionSet GetCSOptions(DocumentOptionSet options) { - return options; + + /// + /// The simplifier's unwrap of single-statement blocks under "Prefer braces: No" is unsafe (see ), + /// and the converter decides where braces go, so always keep braces. + /// If the internal option can't be overridden on this Roslyn version, still protects the output. + /// + private static OptionSet GetCSOptions(DocumentOptionSet options) + { + if (DisableBracesOverrideForTesting.Value) return options; + return options.WithPreferBraces("Always") ?? options; } } \ No newline at end of file diff --git a/Tests/CSharp/SelfVerifyingTests.cs b/Tests/CSharp/SelfVerifyingTests.cs index 52672ad07..831414b44 100644 --- a/Tests/CSharp/SelfVerifyingTests.cs +++ b/Tests/CSharp/SelfVerifyingTests.cs @@ -27,6 +27,12 @@ public async Task VisualBasicToCSharpPreferNoBracesAsync(NamedTest verifyConvert await verifyConvertedTestPasses.Execute(); } + [Theory, MemberData(nameof(GetVisualBasicToCSharpPreferNoBracesGuardOnlyTestData))] + public async Task VisualBasicToCSharpPreferNoBracesGuardOnlyAsync(NamedTest verifyConvertedTestPasses) + { + await verifyConvertedTestPasses.Execute(); + } + /// /// Compile VB.NET source, convert it to C#, compile the conversion /// and return actions which run each corresponding pair of tests. @@ -42,10 +48,17 @@ public static IEnumerable GetVisualBasicToCSharpTestData() /// /// The user's "Prefer braces: No" code style lets the simplifier remove braces, so check that doesn't change which if an else binds to. /// - public static IEnumerable GetVisualBasicToCSharpPreferNoBracesTestData() + public static IEnumerable GetVisualBasicToCSharpPreferNoBracesTestData() => + GetIfElseBindingTestData(); + + /// + public static IEnumerable GetVisualBasicToCSharpPreferNoBracesGuardOnlyTestData() => + GetIfElseBindingTestData(); + + private static IEnumerable GetIfElseBindingTestData() where TConversion : ILanguageConversion, new() { var testFile = Path.Combine(TestConstants.GetTestDataDirectory(), "SelfVerifyingTests/VBToCS/IfElseBindingTests.vb"); - return SelfVerifyingTestFactory.GetSelfVerifyingFacts(testFile) + return SelfVerifyingTestFactory.GetSelfVerifyingFacts(testFile) .Select(et => new object[] {et}) .ToArray(); } diff --git a/Tests/CSharp/StatementTests/PreferNoBracesTests.cs b/Tests/CSharp/StatementTests/PreferNoBracesTests.cs index 4cf9ddd46..dd08315d1 100644 --- a/Tests/CSharp/StatementTests/PreferNoBracesTests.cs +++ b/Tests/CSharp/StatementTests/PreferNoBracesTests.cs @@ -1,11 +1,12 @@ using System.Threading.Tasks; +using ICSharpCode.CodeConverter.CSharp; using ICSharpCode.CodeConverter.Tests.TestRunners; using Xunit; namespace ICSharpCode.CodeConverter.Tests.CSharp.StatementTests; /// -/// The simplifier honours the user's "Prefer braces" code style, but must never let an else bind to a different if. +/// The user's "Prefer braces: No" code style must never let the simplifier produce invalid code, lose comments, or let an else bind to a different if. /// public class PreferNoBracesTests : ConverterTestBase { @@ -357,6 +358,13 @@ private void X() }"); } - private Task TestPreferNoBracesConversionAsync(string visualBasicCode, string expectedCsharpCode) => - AssertConvertedCodeResultEqualsAsync(visualBasicCode, expectedCsharpCode); + /// + /// The converter overrides the preference to always keep braces, so the output matches the default conversion. + /// Where it can't (Roslyn keeps the option internal), only the guard protects the output, so check that path's output too. + /// + private async Task TestPreferNoBracesConversionAsync(string visualBasicCode, string expectedCsharpCodeWithGuardOnly) + { + Assert.Equal(await ConvertAsync(visualBasicCode), await ConvertAsync(visualBasicCode)); + await AssertConvertedCodeResultEqualsAsync(visualBasicCode, expectedCsharpCodeWithGuardOnly); + } } diff --git a/Tests/TestRunners/VBToCSPreferNoBracesConversion.cs b/Tests/TestRunners/VBToCSPreferNoBracesConversion.cs index f4fcbf1aa..94bf241c6 100644 --- a/Tests/TestRunners/VBToCSPreferNoBracesConversion.cs +++ b/Tests/TestRunners/VBToCSPreferNoBracesConversion.cs @@ -17,6 +17,11 @@ public class VBToCSPreferNoBracesConversion : ILanguageConversion { private readonly VBToCSConversion _baseConversion = new(); + /// + /// Whether to convert as on a Roslyn version where the converter can't override the preference, leaving only its guard against wrongly removed braces + /// + protected virtual bool DisableBracesOverride => false; + async Task ILanguageConversion.CreateProjectDocumentFromTreeAsync(SyntaxTree tree, IEnumerable references) { var document = await _baseConversion.CreateProjectDocumentFromTreeAsync(tree, references); @@ -36,7 +41,11 @@ Task ILanguageConversion.CreateProjectContentsConvert IProgress progress, CancellationToken cancellationToken) => _baseConversion.CreateProjectContentsConverterAsync(project, progress, cancellationToken); - Task ILanguageConversion.SingleSecondPassAsync(Document doc) => _baseConversion.SingleSecondPassAsync(doc); + async Task ILanguageConversion.SingleSecondPassAsync(Document doc) + { + DocumentExtensions.DisableBracesOverrideForTesting.Value = DisableBracesOverride; + return await _baseConversion.SingleSecondPassAsync(doc); + } SyntaxTree ILanguageConversion.CreateTree(string text) => _baseConversion.CreateTree(text); List ILanguageConversion.FindSingleImportantChild(SyntaxNode annotatedNode) => _baseConversion.FindSingleImportantChild(annotatedNode); bool ILanguageConversion.CanBeContainedByMethod(SyntaxNode node) => _baseConversion.CanBeContainedByMethod(node); @@ -48,3 +57,9 @@ Task ILanguageConversion.CreateProjectContentsConvert IEnumerable<(string, string)> ILanguageConversion.GetProjectFileReplacementRegexes() => _baseConversion.GetProjectFileReplacementRegexes(); string ILanguageConversion.PostTransformProjectFile(string xml) => _baseConversion.PostTransformProjectFile(xml); } + +/// +public class VBToCSPreferNoBracesGuardOnlyConversion : VBToCSPreferNoBracesConversion +{ + protected override bool DisableBracesOverride => true; +} From 509c495fcc6d9fa70dc1ad9ba9d6fd7ec00a278b Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 17:07:16 +0000 Subject: [PATCH 13/14] Cache the verified "Prefer braces" option value per preference Pure refactor (review round 2): build each CodeStyleOption value and check that it sticks once, rather than repeating the reflection and the read-back for every document. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- .../CachedReflectedPreferBracesOption.cs | 29 ++++++++++++++++--- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/CodeConverter/CSharp/CachedReflectedPreferBracesOption.cs b/CodeConverter/CSharp/CachedReflectedPreferBracesOption.cs index 85f67dd3e..9cd76a25b 100644 --- a/CodeConverter/CSharp/CachedReflectedPreferBracesOption.cs +++ b/CodeConverter/CSharp/CachedReflectedPreferBracesOption.cs @@ -1,3 +1,4 @@ +using System.Collections.Concurrent; using System.Reflection; using Microsoft.CodeAnalysis.Options; @@ -15,14 +16,34 @@ internal static class CachedReflectedPreferBracesOption { private static readonly Lazy PreferBracesOption = new(FindPreferBracesOption); + /// + /// The option value for each preference, or null where it can't be built or doesn't stick when set + /// + private static readonly ConcurrentDictionary VerifiedValueByPreference = new(); + /// The name of a Roslyn PreferBracesPreference: None, WhenMultiline or Always - /// The options with "Prefer braces" set to , or null if it can't be set (checked by reading it back) + /// The options with "Prefer braces" set to , or null if it can't be set (checked once by reading it back) public static OptionSet WithPreferBraces(this OptionSet options, string preference) + { + if (PreferBracesOption.Value is not { } option) return null; + var value = VerifiedValueByPreference.GetOrAdd(preference, p => CreateVerifiedValue(option, options, p)); + return value == null ? null : WithChangedOptionOrNull(options, option, value); + } + + private static object CreateVerifiedValue(IOption option, OptionSet options, string preference) { try { - if (PreferBracesOption.Value is not { } option) return null; - var newOptions = options.WithChangedOption(new OptionKey(option), CreateCodeStyleOption(option.Type, preference)); - return newOptions.GetPreferBraces() == preference ? newOptions : null; + var value = CreateCodeStyleOption(option.Type, preference); + return WithChangedOptionOrNull(options, option, value)?.GetPreferBraces() == preference ? value : null; + } catch (Exception) { + return null; + } + } + + private static OptionSet WithChangedOptionOrNull(OptionSet options, IOption option, object value) + { + try { + return options.WithChangedOption(new OptionKey(option), value); } catch (Exception) { return null; } From 782497d08ef769c3fc42838953026fc71ebbf110 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 21:03:26 +0000 Subject: [PATCH 14/14] Remove lone declaration tests that master now covers Master's 5efe10e pins the same lone Dim and label bodies in LoopStatementTests/MethodStatementTests and VariableScopeTests.vb (which also covers Else), so drop this branch's duplicates. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg --- .../StatementTests/MethodStatementTests.cs | 93 ------------------- .../VBToCS/LoneDeclarationBodyTests.vb | 42 --------- 2 files changed, 135 deletions(-) delete mode 100644 Tests/TestData/SelfVerifyingTests/VBToCS/LoneDeclarationBodyTests.vb diff --git a/Tests/CSharp/StatementTests/MethodStatementTests.cs b/Tests/CSharp/StatementTests/MethodStatementTests.cs index 34ca9a1a7..f68e03b02 100644 --- a/Tests/CSharp/StatementTests/MethodStatementTests.cs +++ b/Tests/CSharp/StatementTests/MethodStatementTests.cs @@ -909,99 +909,6 @@ private void Bar2() }"); } - [Fact] - public async Task BodyWithLoneDeclarationOrLabelKeepsBracesAsync() - { - await TestConversionVisualBasicToCSharpAsync(@"Class TestClass - Private Sub TestMethod(a As Boolean, xs As Integer()) - If a Then Dim v = F() - If a Then - Dim w = F() - Else - Dim x = F() - End If - While a - Dim y = F() - End While - Do - Dim z = F() - Loop While a - For i = 1 To 2 - Dim i2 = F() - Next - For Each x In xs - Dim x2 = F() - Next - SyncLock xs - Dim l = F() - End SyncLock - Using New System.IO.MemoryStream() - Dim u = F() - End Using - While a -label1: - End While - End Sub - Private Function F() As Integer - Return 1 - End Function -End Class", @"using System.IO; - -internal partial class TestClass -{ - private void TestMethod(bool a, int[] xs) - { - if (a) - { - int v = F(); - } - if (a) - { - int w = F(); - } - else - { - int x = F(); - } - while (a) - { - int y = F(); - } - do - { - int z = F(); - } - while (a); - for (int i = 1; i <= 2; i++) - { - int i2 = F(); - } - foreach (var x in xs) - { - int x2 = F(); - } - lock (xs) - { - int l = F(); - } - using (new MemoryStream()) - { - int u = F(); - } - while (a) - { - label1: - ; - - } - } - private int F() - { - return 1; - } -}"); - } - [Fact] public async Task NestedBlockStatementsKeepSameNestingAsync() { diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/LoneDeclarationBodyTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/LoneDeclarationBodyTests.vb deleted file mode 100644 index 55c702b93..000000000 --- a/Tests/TestData/SelfVerifyingTests/VBToCS/LoneDeclarationBodyTests.vb +++ /dev/null @@ -1,42 +0,0 @@ -Imports System -Imports System.Collections.Generic -Imports System.IO -Imports Xunit - -''' -''' A body whose only statement is a declaration must still run its initializer each time (C# can't embed a declaration without braces). -''' -Public Class LoneDeclarationBodyTests - Private ReadOnly _log As New List(Of String) - - Private Function Log(s As String) As Integer - _log.Add(s) - Return _log.Count - End Function - - - Public Sub LoneDeclarationBodiesRunTheirInitializers() - Dim a = True - If a Then Dim v = Log("if") - Dim n = 0 - While n < 2 - Dim y = Log("while" & n) + Math.Min(0, Threading.Interlocked.Increment(n)) - End While - Do - Dim z = Log("do") - Loop While False - For i = 1 To 2 - Dim i2 = Log("for" & i) - Next - For Each x In {"a", "b"} - Dim x2 = Log("each" & x) - Next - SyncLock _log - Dim l = Log("lock") - End SyncLock - Using New MemoryStream() - Dim u = Log("using") - End Using - Assert.Equal("if,while0,while1,do,for1,for2,eacha,eachb,lock,using", String.Join(",", _log)) - End Sub -End Class