Skip to content

SA1143: Format conditional expressions consistently - #4318

Merged
AArnott merged 1 commit into
masterfrom
aarnott-ternary-expression-formatting
Oct 16, 2026
Merged

AArnott merged 1 commit into
masterfrom
aarnott-ternary-expression-formatting

Conversation

@AArnott

@AArnott AArnott commented Oct 16, 2026

Copy link
Copy Markdown
Contributor

Conditional expressions are easier to read when wrapping follows a predictable layout. This implements the proposal in #651, including the requested aligned layout for chained conditions.

Fixes #651

Approach

Adds SA1143, enabled by default as a warning, accepting:

  • An entire conditional expression on one line.
  • Separate, indented lines beginning with ? and :.
  • Aligned false-branch chains, with one condition and true branch per line and the final false branch on its own line.

The code-fix provider offers single-line and expanded layouts, plus an aligned-chain action where applicable. All actions support Fix All. Nested diagnostics share the outermost expression's edit to avoid conflicting formatting changes. Inline block comments are preserved; fixes are withheld for line comments, directives, multiline comments, and multiline literal tokens that cannot safely be flattened.

Behavior and compatibility

This intentionally extends the original proposal to allow aligned chains. Multiline operator lines require indentation, and chained continuations align with the first condition. There is no line-length limit or switch-expression conversion.

Analysis is syntax-only, registered only for conditional expressions, with a single-line fast path and no semantic-model calls or full-tree walks. False-branch chains are checked from their outermost expression. No performance benchmark was run.

Includes rule documentation and navigation for all editions, Russian and Simplified Chinese resource translations, and English fallback for Czech. Translations have not had native-speaker review. Resource accessors were regenerated by the build.

Validation

  • Baseline reproduction confirmed that the existing analyzers report no diagnostic for the partially wrapped expression.
  • All 42 SA1143 cases pass under each compiler from C# 6 through C# 15, including nested Fix All, tabs, LF/CRLF, comments, unsafe-fix exclusions, and malformed syntax. Derived test classes are source-generated.
  • Full Debug solution build: zero warnings and errors.
  • All four DocFX editions build successfully; focused documentation/localization checks pass.
  • Analyzer configuration checks and git diff --check pass.

Opened as a draft pending CI.

Support single-line, indented expanded, and aligned chained ternary layouts. Preserve trivia and coordinate nested Fix All edits.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@codecov

codecov Bot commented Oct 16, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.73300% with 9 lines in your changes missing coverage. Please review.
✅ Project coverage is 97.62%. Comparing base (1f2a075) to head (8078fde).

Additional details and impacted files
@@           Coverage Diff            @@
##           master    #4318    +/-   ##
========================================
  Coverage   97.61%   97.62%            
========================================
  Files        1316     1319     +3     
  Lines      143857   144254   +397     
  Branches     4827     4864    +37     
========================================
+ Hits       140431   140823   +392     
+ Misses       2175     2174     -1     
- Partials     1251     1257     +6     
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@AArnott
AArnott marked this pull request as ready for review October 16, 2026 04:03
Copilot AI balanced review requested due to automatic review settings October 16, 2026 04:03
@AArnott
AArnott merged commit 119e00b into master Oct 16, 2026
29 of 30 checks passed
@AArnott
AArnott deleted the aarnott-ternary-expression-formatting branch October 16, 2026 04:05

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Code fixes can throw on malformed outer expressions, and aligned-chain Fix All can leave sibling expressions misaligned.

2 open findings
What changed in this PR

Adds SA1143 to StyleCop’s readability rules, implementing #651 with support for aligned conditional chains.

Changes:

  • Adds a default-enabled warning and three formatting fixes.
  • Adds layout, comment-preservation, and Fix All tests.
  • Adds resources and documentation across four editions.
File Description
test/​StyleCop.Analyzers.Test/​ReadabilityRules/​SA1143UnitTests.cs Tests diagnostics and formatting fixes.
src/​StyleCop.Analyzers/​ReadabilityRules/​SA1143ConditionalExpressionsMustBeFormattedConsistently.cs Implements layout analysis.
src/​StyleCop.Analyzers/​ReadabilityRules/​ReadabilityResources.zh-CN.resx Adds Chinese resources.
src/​StyleCop.Analyzers/​ReadabilityRules/​ReadabilityResources.ru-RU.resx Adds Russian resources.
src/​StyleCop.Analyzers/​ReadabilityRules/​ReadabilityResources.resx Adds English resources.
src/​StyleCop.Analyzers/​Lightup/​.generated/​Microsoft.CodeAnalysis.ResxSourceGenerator.CSharp/​Microsoft.CodeAnalysis.ResxSourceGenerator.CSharp.CSharpResxGenerator/​ReadabilityResources.Designer.cs Adds generated resource accessors.
src/​StyleCop.Analyzers/​AnalyzerReleases.Unshipped.md Registers SA1143.
src/​StyleCop.Analyzers.CodeFixes/​ReadabilityRules/​SA1143CodeFixProvider.cs Implements formatting actions.
documentation/​zh-cn/​toc.yml Adds navigation entry.
documentation/​zh-cn/​SA1143.md Documents the rule in Chinese.
documentation/​zh-cn/​ReadabilityRules.md Adds rule index entry.
documentation/​toc.yml Adds navigation entry.
documentation/​SA1143.md Documents layouts and fixes.
documentation/​ru-ru/​toc.yml Adds navigation entry.
documentation/​ru-ru/​SA1143.md Documents the rule in Russian.
documentation/​ru-ru/​ReadabilityRules.md Adds rule index entry.
documentation/​ReadabilityRules.md Adds rule index entry.
documentation/​cs-cz/​toc.yml Adds navigation entry.
documentation/​cs-cz/​SA1143.md Provides English fallback documentation.
documentation/​cs-cz/​ReadabilityRules.md Adds English fallback index entry.
Files not reviewed (1)
  • src/StyleCop.Analyzers/Lightup/.generated/Microsoft.CodeAnalysis.ResxSourceGenerator.CSharp/Microsoft.CodeAnalysis.ResxSourceGenerator.CSharp.CSharpResxGenerator/ReadabilityResources.Designer.cs: Generated file

🧠 Review effort: Balanced


💡 Configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

{
// Nested diagnostics must produce the same edit so Fix All cannot re-expand an inner branch.
var expression = root.FindToken(diagnostic.Location.SourceSpan.Start).Parent?.AncestorsAndSelf().OfType<ConditionalExpressionSyntax>().LastOrDefault();
if (expression == null || !CanFormat(expression, text))
Comment on lines +140 to +141
var column = SA1143ConditionalExpressionsMustBeFormattedConsistently.GetColumn(text, expression.SpanStart, settings.Indentation.TabSize);
FormatConditional(expression, layout, indentation, column, settings.Indentation, newLine, text, changes);
This was referenced Nov 11, 2026
This was referenced Nov 24, 2026
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.

New readability rule to format ternary expression

2 participants