diff --git a/CodeConverter/CSharp/CachedReflectedPreferBracesOption.cs b/CodeConverter/CSharp/CachedReflectedPreferBracesOption.cs new file mode 100644 index 000000000..9cd76a25b --- /dev/null +++ b/CodeConverter/CSharp/CachedReflectedPreferBracesOption.cs @@ -0,0 +1,90 @@ +using System.Collections.Concurrent; +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 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 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 { + 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; + } + } + + /// 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/CodeConverter/Common/DocumentExtensions.cs b/CodeConverter/Common/DocumentExtensions.cs index ee8872df7..652b1e279 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 { @@ -52,9 +57,58 @@ 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 && MustKeepBraces(block); } + /// + /// 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 + /// no comment is attached to the braces it drops + /// + /// 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 + && (!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 + or CSSyntax.ForStatementSyntax or CSSyntax.WhileStatementSyntax or CSSyntax.DoStatementSyntax + or CSSyntax.UsingStatementSyntax or CSSyntax.LockStatementSyntax; + + 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 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 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), + CSSyntax.UsingStatementSyntax s => CouldEndWithIfWithoutElse(s.Statement), + CSSyntax.LockStatementSyntax s => CouldEndWithIfWithoutElse(s.Statement), + _ => false + }; + public static async Task WithExpandedRootAsync(this Document document, CancellationToken cancellationToken) { if (document.Project.Language == LanguageNames.VisualBasic) { @@ -115,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 6e182f563..831414b44 100644 --- a/Tests/CSharp/SelfVerifyingTests.cs +++ b/Tests/CSharp/SelfVerifyingTests.cs @@ -21,6 +21,18 @@ public async Task VisualBasicToCSharpAsync(NamedTest verifyConvertedTestPasses) await verifyConvertedTestPasses.Execute(); } + [Theory, MemberData(nameof(GetVisualBasicToCSharpPreferNoBracesTestData))] + public async Task VisualBasicToCSharpPreferNoBracesAsync(NamedTest verifyConvertedTestPasses) + { + 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. @@ -32,4 +44,22 @@ 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() => + 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) + .Select(et => new object[] {et}) + .ToArray(); + } +} diff --git a/Tests/CSharp/StatementTests/MethodStatementTests.cs b/Tests/CSharp/StatementTests/MethodStatementTests.cs index 4c2d08d0c..f68e03b02 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/CSharp/StatementTests/PreferNoBracesTests.cs b/Tests/CSharp/StatementTests/PreferNoBracesTests.cs new file mode 100644 index 000000000..dd08315d1 --- /dev/null +++ b/Tests/CSharp/StatementTests/PreferNoBracesTests.cs @@ -0,0 +1,370 @@ +using System.Threading.Tasks; +using ICSharpCode.CodeConverter.CSharp; +using ICSharpCode.CodeConverter.Tests.TestRunners; +using Xunit; + +namespace ICSharpCode.CodeConverter.Tests.CSharp.StatementTests; + +/// +/// 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 +{ + [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() + { + } +}"); + } + + [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; + } +}"); + } + + [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() + { + 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() + { + } +}"); + } + + /// + /// 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/TestData/SelfVerifyingTests/VBToCS/IfElseBindingTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/IfElseBindingTests.vb new file mode 100644 index 000000000..c474752b3 --- /dev/null +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/IfElseBindingTests.vb @@ -0,0 +1,254 @@ +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 + + 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 + + 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 diff --git a/Tests/TestRunners/VBToCSPreferNoBracesConversion.cs b/Tests/TestRunners/VBToCSPreferNoBracesConversion.cs new file mode 100644 index 000000000..94bf241c6 --- /dev/null +++ b/Tests/TestRunners/VBToCSPreferNoBracesConversion.cs @@ -0,0 +1,65 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using ICSharpCode.CodeConverter.Common; +using ICSharpCode.CodeConverter.CSharp; +using Microsoft.CodeAnalysis; + +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. +/// +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); + var solution = document.Project.Solution; + 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; + + ConversionOptions ILanguageConversion.ConversionOptions { + get => _baseConversion.ConversionOptions; + set => _baseConversion.ConversionOptions = value; + } + + Task ILanguageConversion.CreateProjectContentsConverterAsync(Project project, + IProgress progress, CancellationToken cancellationToken) => + _baseConversion.CreateProjectContentsConverterAsync(project, progress, cancellationToken); + + 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); + 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); +} + +/// +public class VBToCSPreferNoBracesGuardOnlyConversion : VBToCSPreferNoBracesConversion +{ + protected override bool DisableBracesOverride => true; +}