Permalink
Fetching contributors…
Cannot retrieve contributors at this time
60 lines (44 sloc) 2.06 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 RemoveEmptyInitializerAnalyzer : BaseDiagnosticAnalyzer
{
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get { return ImmutableArray.Create(DiagnosticDescriptors.RemoveEmptyInitializer); }
}
public override void Initialize(AnalysisContext context)
{
if (context == null)
throw new ArgumentNullException(nameof(context));
base.Initialize(context);
context.RegisterSyntaxNodeAction(AnalyzeObjectCreationExpression, SyntaxKind.ObjectCreationExpression);
}
public static void AnalyzeObjectCreationExpression(SyntaxNodeAnalysisContext context)
{
var objectCreationExpression = (ObjectCreationExpressionSyntax)context.Node;
if (objectCreationExpression.ContainsDiagnostics)
return;
TypeSyntax type = objectCreationExpression.Type;
if (type?.IsMissing != false)
return;
InitializerExpressionSyntax initializer = objectCreationExpression.Initializer;
if (initializer?.Expressions.Any() != false)
return;
if (!initializer.OpenBraceToken.TrailingTrivia.IsEmptyOrWhitespace())
return;
if (!initializer.CloseBraceToken.LeadingTrivia.IsEmptyOrWhitespace())
return;
if (initializer.IsInExpressionTree(context.SemanticModel, context.CancellationToken))
return;
context.ReportDiagnostic(DiagnosticDescriptors.RemoveEmptyInitializer, initializer);
}
}
}