Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 90 additions & 0 deletions CodeConverter/CSharp/CachedReflectedPreferBracesOption.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
using System.Collections.Concurrent;
using System.Reflection;
using Microsoft.CodeAnalysis.Options;

namespace ICSharpCode.CodeConverter.CSharp;

/// <summary>
/// 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
/// </summary>
/// <remarks>
/// Use with the same care as <see cref="CachedReflectedDelegates"/>: an internal rename in another Roslyn version breaks this,
/// so each member returns null rather than throwing, and callers must have a fallback.
/// </remarks>
internal static class CachedReflectedPreferBracesOption
{
private static readonly Lazy<IOption> PreferBracesOption = new(FindPreferBracesOption);

/// <summary>
/// The option value for each preference, or null where it can't be built or doesn't stick when set
/// </summary>
private static readonly ConcurrentDictionary<string, object> VerifiedValueByPreference = new();

/// <param name="preference">The name of a Roslyn PreferBracesPreference: None, WhenMultiline or Always</param>
/// <returns>The options with "Prefer braces" set to <paramref name="preference"/>, or null if it can't be set (checked once by reading it back)</returns>
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;
}
}

/// <returns>The name of the "Prefer braces" PreferBracesPreference in <paramref name="options"/>, or null if it can't be read</returns>
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;
}
}

/// <summary>
/// Creates <c>new CodeStyleOption2&lt;PreferBracesPreference&gt;(preference, NotificationOption2.Silent)</c>
/// </summary>
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 });
}
}
70 changes: 66 additions & 4 deletions CodeConverter/Common/DocumentExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@ namespace ICSharpCode.CodeConverter.Common;

internal static class DocumentExtensions
{
/// <summary>
/// Lets tests exercise <see cref="MustKeepBraces"/> alone, as on a Roslyn version where <see cref="GetCSOptions"/> can't override the "Prefer braces" preference
/// </summary>
internal static AsyncLocal<bool> DisableBracesOverrideForTesting { get; } = new();

public static async Task<Document> SimplifyStatementsAsync<TUsingDirectiveSyntax>(this Document convertedDocument, string unresolvedTypeDiagnosticId, CancellationToken cancellationToken)
where TUsingDirectiveSyntax : SyntaxNode
{
Expand Down Expand Up @@ -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);
}

/// <summary>
/// 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:
/// <list type="bullet">
/// <item>the statement can be embedded: <c>if (a) int x = F();</c> is CS1023</item>
/// <item>a following else still binds to the same if: in <c>if (a) { if (b) x(); } else y();</c> it would bind to <c>if (b)</c> https://github.com/icsharpcode/CodeConverter/issues/823</item>
/// <item>no comment is attached to the braces it drops</item>
/// </list>
/// 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).
/// <see cref="GetCSOptions"/> overrides it, but Roslyn keeps the option internal, so where that fails, keep the braces it would wrongly remove.
/// </summary>
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));

/// <summary>
/// The unwrap drops comments attached to the removed braces, and losing a user's comment is worse than keeping their braces.
/// </summary>
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;

/// <summary>
/// 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.
/// </summary>
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<Document> WithExpandedRootAsync(this Document document, CancellationToken cancellationToken)
{
if (document.Project.Language == LanguageNames.VisualBasic) {
Expand Down Expand Up @@ -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;

/// <summary>
/// The simplifier's unwrap of single-statement blocks under "Prefer braces: No" is unsafe (see <see cref="MustKeepBraces"/>),
/// and the converter decides where braces go, so always keep braces.
/// If the internal option can't be overridden on this Roslyn version, <see cref="MustKeepBraces"/> still protects the output.
/// </summary>
private static OptionSet GetCSOptions(DocumentOptionSet options)
{
if (DisableBracesOverrideForTesting.Value) return options;
return options.WithPreferBraces("Always") ?? options;
}
}
32 changes: 31 additions & 1 deletion Tests/CSharp/SelfVerifyingTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}

/// <summary>
/// Compile VB.NET source, convert it to C#, compile the conversion
/// and return actions which run each corresponding pair of tests.
Expand All @@ -32,4 +44,22 @@ public static IEnumerable<object[]> GetVisualBasicToCSharpTestData()
.Select(et => new object[] {et})
.ToArray();
}
}

/// <summary>
/// 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.
/// </summary>
public static IEnumerable<object[]> GetVisualBasicToCSharpPreferNoBracesTestData() =>
GetIfElseBindingTestData<VBToCSPreferNoBracesConversion>();

/// <inheritdoc cref="GetVisualBasicToCSharpPreferNoBracesTestData"/>
public static IEnumerable<object[]> GetVisualBasicToCSharpPreferNoBracesGuardOnlyTestData() =>
GetIfElseBindingTestData<VBToCSPreferNoBracesGuardOnlyConversion>();

private static IEnumerable<object[]> GetIfElseBindingTestData<TConversion>() where TConversion : ILanguageConversion, new()
{
var testFile = Path.Combine(TestConstants.GetTestDataDirectory(), "SelfVerifyingTests/VBToCS/IfElseBindingTests.vb");
return SelfVerifyingTestFactory.GetSelfVerifyingFacts<VisualBasicCompiler, CSharpCompiler, TConversion>(testFile)
.Select(et => new object[] {et})
.ToArray();
}
}
46 changes: 46 additions & 0 deletions Tests/CSharp/StatementTests/MethodStatementTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
{
Expand Down
Loading
Loading