Skip to content

Commit 279ca9d

Browse files
committed
Fix SA1509 getting reported for consecutive blocks
Fixes #689
1 parent 784cfff commit 279ca9d

2 files changed

Lines changed: 49 additions & 0 deletions

File tree

StyleCop.Analyzers/StyleCop.Analyzers.Test/LayoutRules/SA1509UnitTests.cs

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -637,6 +637,42 @@ void Bar()
637637
await this.VerifyCSharpDiagnosticAsync(testCode, EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
638638
}
639639

640+
[Fact]
641+
public async Task TestBlockStatementsAsync()
642+
{
643+
var testCode = @"
644+
class Foo
645+
{
646+
void Bar()
647+
{
648+
649+
{
650+
}
651+
652+
{
653+
}
654+
}
655+
}";
656+
657+
var fixedCode = @"
658+
class Foo
659+
{
660+
void Bar()
661+
{
662+
{
663+
}
664+
665+
{
666+
}
667+
}
668+
}";
669+
670+
DiagnosticResult expected = this.CSharpDiagnostic().WithLocation(7, 9);
671+
await this.VerifyCSharpDiagnosticAsync(testCode, expected, CancellationToken.None).ConfigureAwait(false);
672+
await this.VerifyCSharpDiagnosticAsync(fixedCode, EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
673+
await this.VerifyCSharpFixAsync(testCode, fixedCode, cancellationToken: CancellationToken.None).ConfigureAwait(false);
674+
}
675+
640676
[Fact]
641677
public async Task TestComplex1Async()
642678
{

StyleCop.Analyzers/StyleCop.Analyzers/LayoutRules/SA1509OpeningBracesMustNotBePrecededByBlankLine.cs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ namespace StyleCop.Analyzers.LayoutRules
88
using System.Linq;
99
using Microsoft.CodeAnalysis;
1010
using Microsoft.CodeAnalysis.CSharp;
11+
using Microsoft.CodeAnalysis.CSharp.Syntax;
1112
using Microsoft.CodeAnalysis.Diagnostics;
1213
using StyleCop.Analyzers.Helpers;
1314

@@ -79,6 +80,18 @@ private static void HandleSyntaxTree(SyntaxTreeAnalysisContext context)
7980

8081
foreach (var openBrace in openBraces)
8182
{
83+
BlockSyntax blockSyntax = openBrace.Parent as BlockSyntax;
84+
if (blockSyntax != null)
85+
{
86+
BlockSyntax parentBlock = blockSyntax.Parent as BlockSyntax;
87+
if (parentBlock != null && parentBlock.Statements[0] != blockSyntax)
88+
{
89+
// Do not disallow a blank line before an independent block, unless it is the first child of its
90+
// parent.
91+
continue;
92+
}
93+
}
94+
8295
AnalyzeOpenBrace(context, openBrace);
8396
}
8497
}

0 commit comments

Comments
 (0)