Repository navigation
Keep braces the simplifier would wrongly remove under "Prefer braces: No" (#823)- #8 - #1325
Merged
GrahamTheCoder merged 15 commits intoNov 18, 2026
Conversation
…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
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
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #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:
Solution.Options.DocumentExtensions.WithReducedRootAsyncpassesdoc.GetOptionsAsync()(aDocumentOptionSetfalling back to those) toSimplifier.ReduceAsync, andSimplifier.GetOptionsAsyncbuilds theCSharpSimplifierOptionsfrom exactly that option set. The web converter and the tests use anAdhocWorkspacewith default options, which is why they never reproduced it.csharp_prefer_braces = false, and alsowhen_multilinefor code written on one line, which converter output never is),CSharpMiscellaneousReducer.SimplifyBlockreplaces 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:
Override (primary):
GetCSOptionssets the "Prefer braces" option toAlwayson the options passed toSimplifier.ReduceAsync. The converter already decides where braces go, so the output then matches the default conversion. Roslyn keepsCSharpCodeStyleOptions.PreferBracesinternal, so the newCachedReflectedPreferBracesOptionreaches it by reflection. It's lazy, in the style ofCachedReflectedDelegates, 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.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:CanBeEmbedded, mirroring the compiler's CS1023 rule), orelse, when their statement could end with anifthat has noelse. The check looks through else-if chains, loops,using,lockand inner single-statement blocks, orThis is cheap, needs only public syntax API, and protects the output on any Roslyn version where the override fails.
The converter's own lone-
Dimbug (while (a) int z = F();, CS1023 fromUnpackNonNestedBlock) is now fixed upstream on master (5cff392, 5efe10e) with the sameCanBeEmbeddedrule. This PR merges master and keeps master's version. What #8 still adds there is the reuse ofCanBeEmbeddedin the simplifier guard, which catches the same CS1023 when Roslyn removes braces the converter kept, e.g. a multi-line If around a loneDim. This branch's own lone-Dimtests duplicated master's, so they were removed in favour of master's broader ones.Other options examined
Every option the C# simplifier reads (
CSharpSimplifierOptions/SimplifierOptionsand the reducers on Roslyn main):varpreferences (CSharpVarReducer): guarded semantically byCSharpUseImplicitTypeHelper.AnalyzeTypeName.this.qualification and predefined type keywords (CSharpNameReducer): applied only when speculative binding is unchanged.PreferSimpleDefaultExpression(CanReplaceWithDefaultLiteral) and implicitly typed lambdas (SpeculationAnalyzer): semantically guarded.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 onSolution.Optionsthe way VS does.VBToCSPreferNoBracesGuardOnlyConversionalso disables the override through anAsyncLocaltest 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:if (FOO1)), loops/lock/using and else-if chains before an else, declarations and labels (red before: CS1023), comments on braces (red before:// c3and// e2lost), 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".Dimoutput with default options is pinned by master's tests.Review round 1
CommentsOnRemovableBracesKeepBracesAsync.LoopLockAndUsingEndingWithIfKeepBracesBeforeElseAsynccovers the loop/lock/using arms ofCouldEndWithIfWithoutElse.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
CachedReflectedPreferBracesOptionnow builds and verifies each option value once (pure refactor).}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
DocumentExtensions.cs, and the success path ofCachedReflectedPreferBracesOption.Extensions.csis now master's version.GetCSOptions's?? optionsfallback. These are unreachable on Roslyn 4.14. The guard they fall back to is covered by the guard-only tests.For the reviewer
Upstream Roslyn issue (draft)
Title: Simplifier removes braces under
csharp_prefer_braces = false/when_multilineeven when that changes meaning (dangling else), breaks compilation (CS1023) or drops commentsComponent: Workspaces /
Simplifier.ReduceAsync:CSharpMiscellaneousReducer.SimplifyBlockSummary
With
csharp_prefer_braces = falseorwhen_multiline,Simplifier.ReduceAsyncunwraps a single-statement block that is the embedded statement of anif/else/for/foreach/while/do/using/lock. It doesn't check that the result is valid and means the same:if (a) { if (b) X(); } else Y();becomesif (a) if (b) X(); else Y();, so theelsenow binds toif (b)(silent behaviour change). The same happens through an intervening loop,lockorusing, e.g.if (a) { lock (this) if (b) X(); } else Y();.if (a) { int x = F(); }becomesif (a) int x = F();, which is error CS1023. The same goes for a labeled statement, a local function, and (underfalse)while/foreach/lock/usingbodies.if (a) { X(); } // c1loses// c1.Under
when_multiline, cases 1 and 2 also happen for anifwritten on one line, including the whole if/else:if (a) { if (b) F(); } else F();becomesif (a) if (b) F(); else F();. The code checks the line layout but not theif's ownelse, 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 #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" />Actual output (as run)
(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 thelockvariant.if (a) { int x = F(); }is unchanged. Same forwhile, 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(); }becomesif (a) X();, andif (a) { if (b) X(); }with no else becomesif (a) if (b) X();.Root cause
SimplifyBlockonly checks the statement count, that the parent can have an embedded statement, and the preference. Forwhen_multilineit also checks the line layout and that the parentifisn't itself inside an if/else (node.Parent.Parent), not whether the parentifhas anelse. It then returnsnode.Statements[0]:https://github.com/dotnet/roslyn/blob/616b2ea1b670fc279c1e6a028579c64ef94924c3/src/Workspaces/CSharp/Portable/Simplification/Reducers/CSharpMiscellaneousReducer.cs#L113-L196(SimplifyBlockandCanHaveEmbeddedStatement)VisitBlock:https://github.com/dotnet/roslyn/blob/616b2ea1b670fc279c1e6a028579c64ef94924c3/src/Workspaces/CSharp/Portable/Simplification/Reducers/CSharpMiscellaneousReducer.Rewriter.cs#L31-L35This code is still on
mainat 616b2ea. The repro above shows the same behaviour in the 4.14.0 package.Suggested fix
In
SimplifyBlock, for bothNoneandWhenMultiline, returnnodeunchanged (keep the braces) when any of these holds:LocalDeclarationStatement,LabeledStatementorLocalFunctionStatement. These are exactly the kinds the binder rejects withERR_BadEmbeddedStmt(CS1023) inBindPossibleEmbeddedStatement: https://github.com/dotnet/roslyn/blob/616b2ea1b670fc279c1e6a028579c64ef94924c3/src/Compilers/CSharp/Portable/Binder/Binder_Statements.cs#L319-L349node.Parentis anIfStatementSyntaxwhoseStatement == nodeand whoseElse != null, and the statement could end with an if without else:ifwith noelse;ifwith anelsewhose statement could end with an if without else (else-if chains);for/foreach/foreach (var (x, y) …)/while/using/lockwhose embedded statement could end with an if without else (docan't, because it ends withwhile (…););node.OpenBraceTokenornode.CloseBraceTokenhas 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 thewhen_multilinenotion viaIsConsideredMultiLine(L151) andRequiresBracesToMatchContext(L236). The reducer only approximates both. It also hasContainsInterleavedDirective(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 undersrc/Analyzers/CSharp.Suggested tests
Brace tests for the reducer live in
src/EditorFeatures/Test2/Simplification/SimplificationTests.vb. It has aDoNotPreferBracesoptions collection (L14-L17) andTestCSharp_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, withDoNotPreferBracesand a when_multiline equivalent:TestCSharp_DoNotSimplifyIfBlockBeforeElseWhenInnerIfHasNoElse:if (a) {|Simplify:{ if (b) X(); }|} else Y();stays unchanged.{ if (b) X(); else if (c) Z(); }),for,foreach,while,lockandusing, 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,…WithLabeledStatementand…WithLocalFunction: unchanged (would be CS1023).TestCSharp_DoNotSimplifyBlockWithCommentOnBrace: comments before/after{and}are kept.🤖 Generated with Claude Code
https://claude.ai/code/session_019FEr8FVAmHV9bscZ82CChg