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