Permalink
Fetching contributors…
Cannot retrieve contributors at this time
64 lines (47 sloc) 1.99 KB
// Copyright (c) Josef Pihrt. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Roslynator.CSharp.Analysis
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class BlockAnalyzer : BaseDiagnosticAnalyzer
{
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get { return ImmutableArray.Create(DiagnosticDescriptors.FormatEmptyBlock); }
}
public override void Initialize(AnalysisContext context)
{
if (context == null)
throw new ArgumentNullException(nameof(context));
base.Initialize(context);
context.RegisterSyntaxNodeAction(AnalyzeBlock, SyntaxKind.Block);
}
public static void AnalyzeBlock(SyntaxNodeAnalysisContext context)
{
var block = (BlockSyntax)context.Node;
SyntaxList<StatementSyntax> statements = block.Statements;
if (statements.Any())
return;
if (block.Parent is AccessorDeclarationSyntax)
return;
if (block.Parent is AnonymousFunctionExpressionSyntax)
return;
SyntaxToken openBrace = block.OpenBraceToken;
SyntaxToken closeBrace = block.CloseBraceToken;
int startLine = openBrace.GetSpanStartLine();
int endLine = closeBrace.GetSpanEndLine();
if ((endLine - startLine) == 1)
return;
if (!openBrace.TrailingTrivia.IsEmptyOrWhitespace())
return;
if (!closeBrace.LeadingTrivia.IsEmptyOrWhitespace())
return;
context.ReportDiagnostic(DiagnosticDescriptors.FormatEmptyBlock, block);
}
}
}