Skip to content

Keep braces the simplifier would wrongly remove under "Prefer braces: No" (#823) - #8

Closed
GrahamTheCoder wants to merge 15 commits into
masterfrom
claude/fix-823-dangling-else
Closed

GrahamTheCoder wants to merge 15 commits into
masterfrom
claude/fix-823-dangling-else

Conversation

@GrahamTheCoder

@GrahamTheCoder GrahamTheCoder commented Nov 10, 2026 •

Copy link
Copy Markdown
Owner

Fixes icsharpcode#823

Root cause

The dangling else comes from Roslyn's simplifier, driven by the user's C# code style, as the reporter and maintainer suspected:

  • In Visual Studio, Tools > Options > C# > Code Style values live in the workspace's global options, which reach the converter through Solution.Options. DocumentExtensions.WithReducedRootAsync passes doc.GetOptionsAsync() (a DocumentOptionSet falling back to those) to Simplifier.ReduceAsync, and Simplifier.GetOptionsAsync builds the CSharpSimplifierOptions from exactly that option set. The web converter and the tests use an AdhocWorkspace with default options, which is why they never reproduced it.
  • With "Prefer braces: No" (csharp_prefer_braces = false, and also when_multiline for code written on one line, which converter output never is), CSharpMiscellaneousReducer.SimplifyBlock replaces a single-statement embedded block with its statement. It doesn't check that the result is valid and means the same (details in the upstream issue draft below).

Fix

Two layers, the guard being the progressive fallback for the override:

  1. Override (primary): GetCSOptions sets the "Prefer braces" option to Always on the options passed to Simplifier.ReduceAsync. The converter already decides where braces go, so the output then matches the default conversion. Roslyn keeps CSharpCodeStyleOptions.PreferBraces internal, so the new CachedReflectedPreferBracesOption reaches it by reflection. It's lazy, in the style of CachedReflectedDelegates, returns null instead of throwing, and checks the new value by reading it back. It works against Roslyn 4.14 (the version this repo uses): every PreferNoBraces test's override path matches the default conversion.

  2. Guard (fallback, always on): CsWouldBeSimplifiedIncorrectly (the existing hook for Roslyn simplifier bugs) excludes from simplification the blocks Roslyn would wrongly unwrap. These are single-statement embedded blocks that:

    • hold a local declaration, local function or label (master's CanBeEmbedded, mirroring the compiler's CS1023 rule), or
    • are directly followed by an else, when their statement could end with an if that has no else. The check looks through else-if chains, loops, using, lock and inner single-statement blocks, or
    • carry a comment on either brace (the unwrap drops it).

    This is cheap, needs only public syntax API, and protects the output on any Roslyn version where the override fails.

The converter's own lone-Dim bug (while (a) int z = F();, CS1023 from UnpackNonNestedBlock) is now fixed upstream on master (5cff392, 5efe10e) with the same CanBeEmbedded rule. This PR merges master and keeps master's version. What #8 still adds there is the reuse of CanBeEmbedded in the simplifier guard, which catches the same CS1023 when Roslyn removes braces the converter kept, e.g. a multi-line If around a lone Dim. This branch's own lone-Dim tests duplicated master's, so they were removed in favour of master's broader ones.

Other options examined

Every option the C# simplifier reads (CSharpSimplifierOptions/SimplifierOptions and the reducers on Roslyn main):

  • var preferences (CSharpVarReducer): guarded semantically by CSharpUseImplicitTypeHelper.AnalyzeTypeName.
  • this. qualification and predefined type keywords (CSharpNameReducer): applied only when speculative binding is unchanged.
  • PreferSimpleDefaultExpression (CanReplaceWithDefaultLiteral) and implicitly typed lambdas (SpeculationAnalyzer): semantically guarded.
  • Parentheses preferences: not read by the simplifier.
  • PreferBraces: the only purely syntactic, unguarded option-driven transform, hence this fix.

Empirical check: all 383 VB->C# self-verifying tests passed with every one of those options set to a non-default value (that experiment isn't committed).

Tests

  • VBToCSPreferNoBracesConversion (test runner): converts as a user with "Prefer braces: No" would, by setting the option on Solution.Options the way VS does. VBToCSPreferNoBracesGuardOnlyConversion also disables the override through an AsyncLocal test switch (DocumentExtensions.DisableBracesOverrideForTesting), so the guard alone is tested as on a Roslyn version where the override fails.
  • PreferNoBracesTests (8 tests), each run through both paths:
    • The override path must equal the default conversion. Before the override, 6 of the 8 differed.
    • The guard-only path pins the existing expectations. These cover the issue's exact repro (red before: the else bound to if (FOO1)), loops/lock/using and else-if chains before an else, declarations and labels (red before: CS1023), comments on braces (red before: // c3 and // e2 lost), and cases where braces are still removed.
  • IfElseBindingTests.vb (15 facts) runs on both paths. Before the fix, 8 failed at runtime under "Prefer braces: No".
  • Lone-Dim output with default options is pinned by master's tests.
  • The first commit's default-options regression tests are kept.

Review round 1

  • No bugs found.
  • Added: keep braces that carry a comment, since losing a user's comment is worse than keeping their braces. Pinned by CommentsOnRemovableBracesKeepBracesAsync.
  • Added: LoopLockAndUsingEndingWithIfKeepBracesBeforeElseAsync covers the loop/lock/using arms of CouldEndWithIfWithoutElse.
  • Declined: the mis-indented else\n if (c)\nY(); under "Prefer braces: No". That's Roslyn's formatting, the code is valid, and it no longer arises on the override path.

Review round 2

  • Converged: no bugs, only nitpicks.
  • Done: CachedReflectedPreferBracesOption now builds and verifies each option value once (pure refactor).
  • Declined, both pre-existing formatting: the blank line before } after a label, and the misindented // c4.

Suite

Merged with origin/master (cd6dd93). Full suite (--blame-hang) at 782497d: 1980 passed, 5 skipped, 0 failed. origin/master measured the same way: 1926/5/0. The 54 extra tests are this PR's new tests. No other differences.

Coverage of changed lines

  • Covered: every changed line in DocumentExtensions.cs, and the success path of CachedReflectedPreferBracesOption. Extensions.cs is now master's version.
  • Uncovered: only the reflection failure paths (member not found, exception, override not sticking) and GetCSOptions's ?? options fallback. These are unreachable on Roslyn 4.14. The guard they fall back to is covered by the guard-only tests.

For the reviewer

  • Guard vs override (was pending): both, done as above. The override is primary. It means the user's harmless brace preference is no longer applied to converted code, which now matches the default conversion. The guard stays on as a cheap safety net.
  • Excluding a node from simplification also excludes its ancestors (that's how the existing hook works). So when the guard triggers, simplifications of the enclosing statements' own nodes are skipped. Nested content is still simplified. No existing default-options expectation changed.

Upstream Roslyn issue (draft)

Title: Simplifier removes braces under csharp_prefer_braces = false/when_multiline even when that changes meaning (dangling else), breaks compilation (CS1023) or drops comments

Component: Workspaces / Simplifier.ReduceAsync: CSharpMiscellaneousReducer.SimplifyBlock

Summary

With csharp_prefer_braces = false or when_multiline, Simplifier.ReduceAsync unwraps a single-statement block that is the embedded statement of an if/else/for/foreach/while/do/using/lock. It doesn't check that the result is valid and means the same:

  1. Dangling else: if (a) { if (b) X(); } else Y(); becomes if (a) if (b) X(); else Y();, so the else now binds to if (b) (silent behaviour change). The same happens through an intervening loop, lock or using, e.g. if (a) { lock (this) if (b) X(); } else Y();.
  2. Not embeddable: if (a) { int x = F(); } becomes if (a) int x = F();, which is error CS1023. The same goes for a labeled statement, a local function, and (under false) while/foreach/lock/using bodies.
  3. Lost comments: comment trivia on the removed braces is dropped, e.g. if (a) { X(); } // c1 loses // c1.

Under when_multiline, cases 1 and 2 also happen for an if written on one line, including the whole if/else: if (a) { if (b) F(); } else F(); becomes if (a) if (b) F(); else F();. The code checks the line layout but not the if's own else, although its comment says it does. Written over several lines, the braces are kept, and loop bodies keep theirs.

Found via the VB->C# converter icsharpcode#823, where VS users with "Prefer braces: No" got a dangling else.

Repro (verified against Microsoft.CodeAnalysis.CSharp.Workspaces 4.14.0, net10.0)

repro.csproj: <OutputType>Exe</OutputType>, <TargetFramework>net10.0</TargetFramework>, <Nullable>enable</Nullable>, <ImplicitUsings>enable</ImplicitUsings>, <PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="4.14.0" />

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.CodeAnalysis.Text;

string[] statements = [
    "if (a) { if (b) X(); } else Y();",              // dangling else
    "if (a) { int x = F(); }",                        // CS1023
    "while (a) { int x = F(); }",
    "if (a) { L: X(); }",
    "if (a) { void Local() { } }",
    "if (a) { lock (this) if (b) X(); } else Y();",  // dangling else through lock
    "if (a) { X(); } // c1\nelse Y();",              // comment on a removed brace
];

foreach (var preferBraces in new[] { "false", "when_multiline" }) {
    Console.WriteLine($"## csharp_prefer_braces = {preferBraces}");
    foreach (var statement in statements) {
        var source = $"class C {{\n    bool a, b;\n    void M() {{\n{statement}\n    }}\n    void X() {{ }} void Y() {{ }} int F() => 0;\n}}";
        var project = new AdhocWorkspace().AddProject("P", LanguageNames.CSharp)
            .WithCompilationOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
            .AddMetadataReference(MetadataReference.CreateFromFile(typeof(object).Assembly.Location));
        project = project.AddAnalyzerConfigDocument(".editorconfig",
            SourceText.From($"root = true\n[*.cs]\ncsharp_prefer_braces = {preferBraces}\n"), filePath: "/src/.editorconfig").Project;
        var document = project.AddDocument("C.cs", source, filePath: "/src/C.cs");
        var root = await document.GetSyntaxRootAsync();
        document = document.WithSyntaxRoot(root!.WithAdditionalAnnotations(Simplifier.Annotation));

        var reduced = await Simplifier.ReduceAsync(document, Simplifier.Annotation);

        // Reparse: the reduced tree still says the else belongs to the outer if, but its text does not
        var reparsed = CSharpSyntaxTree.ParseText(await reduced.GetTextAsync()).GetRoot();
        var body = reparsed.DescendantNodes().OfType<MethodDeclarationSyntax>().First().Body!;
        var output = body.Statements.Single().ToFullString().Trim().ReplaceLineEndings("⏎ ");
        var errors = (await reduced.Project.GetCompilationAsync())!.GetDiagnostics()
            .Where(d => d.Severity == DiagnosticSeverity.Error).Select(d => d.Id).Distinct();
        var elseOwner = body.Statements.Single() is IfStatementSyntax { Else: null } outerIf && outerIf.DescendantNodes().OfType<ElseClauseSyntax>().Any()
            ? "   (else now binds to the inner if)" : "";
        Console.WriteLine($"{statement.ReplaceLineEndings("⏎ "),-48} => {output}   errors: [{string.Join(", ", errors)}]{elseOwner}");
    }
}

Actual output (as run)

## csharp_prefer_braces = false
if (a) { if (b) X(); } else Y();                 => if (a) if (b) X(); else Y();   errors: []   (else now binds to the inner if)
if (a) { int x = F(); }                          => if (a) int x = F();   errors: [CS1023]
while (a) { int x = F(); }                       => while (a) int x = F();   errors: [CS1023]
if (a) { L: X(); }                               => if (a) L: X();   errors: [CS1023]
if (a) { void Local() { } }                      => if (a) void Local() { }   errors: [CS1023]
if (a) { lock (this) if (b) X(); } else Y();     => if (a) lock (this) if (b) X(); else Y();   errors: []   (else now binds to the inner if)
if (a) { X(); } // c1⏎ else Y();                 => if (a) X(); else Y();   errors: []
## csharp_prefer_braces = when_multiline
if (a) { if (b) X(); } else Y();                 => if (a) if (b) X(); else Y();   errors: []   (else now binds to the inner if)
if (a) { int x = F(); }                          => if (a) int x = F();   errors: [CS1023]
while (a) { int x = F(); }                       => while (a) { int x = F(); }   errors: []
if (a) { L: X(); }                               => if (a) L: X();   errors: [CS1023]
if (a) { void Local() { } }                      => if (a) void Local() { }   errors: [CS1023]
if (a) { lock (this) if (b) X(); } else Y();     => if (a) lock (this) if (b) X(); else Y();   errors: []   (else now binds to the inner if)
if (a) { X(); } // c1⏎ else Y();                 => if (a) X(); else Y();   errors: []

(The dangling-else case reports no error because the reduced tree still has the else on the outer if. Only its text, once reparsed or saved, binds differently.)

Expected output

The braces are kept in each case above, since the unbraced form changes meaning, doesn't compile or loses a comment:

  • if (a) { if (b) X(); } else Y(); is unchanged. Same for the lock variant.
  • if (a) { int x = F(); } is unchanged. Same for while, label and local function.
  • if (a) { X(); } // c1⏎ else Y(); is unchanged.

Braces should still be removed where that's safe, e.g. if (a) { X(); } becomes if (a) X();, and if (a) { if (b) X(); } with no else becomes if (a) if (b) X();.

Root cause

SimplifyBlock only checks the statement count, that the parent can have an embedded statement, and the preference. For when_multiline it also checks the line layout and that the parent if isn't itself inside an if/else (node.Parent.Parent), not whether the parent if has an else. It then returns node.Statements[0]:

  • https://github.com/dotnet/roslyn/blob/616b2ea1b670fc279c1e6a028579c64ef94924c3/src/Workspaces/CSharp/Portable/Simplification/Reducers/CSharpMiscellaneousReducer.cs#L113-L196 (SimplifyBlock and CanHaveEmbeddedStatement)
  • called from VisitBlock: https://github.com/dotnet/roslyn/blob/616b2ea1b670fc279c1e6a028579c64ef94924c3/src/Workspaces/CSharp/Portable/Simplification/Reducers/CSharpMiscellaneousReducer.Rewriter.cs#L31-L35

This code is still on main at 616b2ea. The repro above shows the same behaviour in the 4.14.0 package.

Suggested fix

In SimplifyBlock, for both None and WhenMultiline, return node unchanged (keep the braces) when any of these holds:

  1. The statement can't be embedded: it's a LocalDeclarationStatement, LabeledStatement or LocalFunctionStatement. These are exactly the kinds the binder rejects with ERR_BadEmbeddedStmt (CS1023) in BindPossibleEmbeddedStatement: https://github.com/dotnet/roslyn/blob/616b2ea1b670fc279c1e6a028579c64ef94924c3/src/Compilers/CSharp/Portable/Binder/Binder_Statements.cs#L319-L349
  2. Dangling else: node.Parent is an IfStatementSyntax whose Statement == node and whose Else != null, and the statement could end with an if without else:
    • an if with no else;
    • an if with an else whose statement could end with an if without else (else-if chains);
    • a for/foreach/foreach (var (x, y) …)/while/using/lock whose embedded statement could end with an if without else (do can't, because it ends with while (…););
    • a single-statement block that the reducer may itself unwrap, whose statement could end with an if without else. Inner blocks are reduced too, so assume they may lose their braces.
  3. Comments would be lost: node.OpenBraceToken or node.CloseBraceToken has comment trivia (leading or trailing). Alternatively, move that trivia onto the statement, but keeping the braces is simpler and safer.

Reusable logic in the IDE0011 "Add braces" analyzer: CSharpAddBracesDiagnosticAnalyzer (https://github.com/dotnet/roslyn/blob/616b2ea1b670fc279c1e6a028579c64ef94924c3/src/Analyzers/CSharp/Analyzers/AddBraces/CSharpAddBracesDiagnosticAnalyzer.cs) shares the when_multiline notion via IsConsideredMultiLine (L151) and RequiresBracesToMatchContext (L236). The reducer only approximates both. It also has ContainsInterleavedDirective (L123) for if/else with directives, which the reducer may also need. IDE0011 only adds braces, so it has no dangling-else or CS1023 check to reuse. Roslyn has no "remove braces" analyzer or fixer: only the AddBraces analyzer and code fix exist under src/Analyzers/CSharp.

Suggested tests

Brace tests for the reducer live in src/EditorFeatures/Test2/Simplification/SimplificationTests.vb. It has a DoNotPreferBraces options collection (L14-L17) and TestCSharp_Simplify{If,Else,While,Do,Using,Lock,For,Foreach}Block (L130-L417): https://github.com/dotnet/roslyn/blob/616b2ea1b670fc279c1e6a028579c64ef94924c3/src/EditorFeatures/Test2/Simplification/SimplificationTests.vb#L14-L417. Add, with DoNotPreferBraces and a when_multiline equivalent:

  • TestCSharp_DoNotSimplifyIfBlockBeforeElseWhenInnerIfHasNoElse: if (a) {|Simplify:{ if (b) X(); }|} else Y(); stays unchanged.
  • The same through an else-if chain ({ if (b) X(); else if (c) Z(); }), for, foreach, while, lock and using, and through a nested single-statement block.
  • TestCSharp_SimplifyIfBlockBeforeElseWhenInnerIfHasElse: if (a) { if (b) X(); else Z(); } else Y(); still unwraps (no dangling else possible).
  • TestCSharp_SimplifyIfBlockWithoutElse: if (a) { if (b) X(); } still unwraps.
  • TestCSharp_DoNotSimplify{If,While,Foreach,Lock,Using}BlockWithLocalDeclaration, …WithLabeledStatement and …WithLocalFunction: unchanged (would be CS1023).
  • TestCSharp_DoNotSimplifyBlockWithCommentOnBrace: comments before/after { and } are kept.

🤖 Generated with Claude Code

https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg

@GrahamTheCoder

GrahamTheCoder commented Nov 10, 2026 •

Copy link
Copy Markdown
Owner Author

The original issue mentions it's to do with the options set which the simplifier uses. Won't this still be a problem? Closing until that's properly investigated

…ode#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 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
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 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
)

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 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
…csharpcode#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 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
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 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
@GrahamTheCoder
GrahamTheCoder force-pushed the claude/fix-823-dangling-else branch from a6de59a to e308beb Compare November 18, 2026 16:26
@GrahamTheCoder GrahamTheCoder changed the title Add regression test for If immediately preceded by Else (#823) Keep braces the simplifier would wrongly remove under "Prefer braces: No" (#823) Nov 18, 2026
Pure refactor so the converter's own block unpacking can use the same rule.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
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 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
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 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
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 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
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 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
…ying

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 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
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 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
Resolves CodeConverter/CSharp/Extensions.cs with master's version: master
already has CanBeEmbedded (5efe10e), with the same semantics, and
UnpackNonNestedBlock delegating to UnpackPossiblyNestedBlock (5cff392).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
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 <[email protected]>
Claude-Session: https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg
@GrahamTheCoder

Copy link
Copy Markdown
Owner Author

Superseded: icsharpcode#1325

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

VB -> C#: Incorrect conversion of If immediately preceded by Else

2 participants