Added detection for compile-time constant patterns

This commit is contained in:
Thorsten Sommer 2026-06-09 10:28:04 +02:00
parent e9da7d31df
commit d91b11e32a
Signed by untrusted user who does not match committer: tsommer
GPG Key ID: 371BBA77A02C0108

View File

@ -13,76 +13,94 @@ namespace SourceCodeRules.UsageAnalyzers;
public sealed class EmptyStringAnalyzer : DiagnosticAnalyzer public sealed class EmptyStringAnalyzer : DiagnosticAnalyzer
{ {
private const string DIAGNOSTIC_ID = Identifier.EMPTY_STRING_ANALYZER; private const string DIAGNOSTIC_ID = Identifier.EMPTY_STRING_ANALYZER;
private static readonly string TITLE = """ private static readonly string TITLE = """
Use string.Empty instead of "" Use string.Empty instead of ""
"""; """;
private static readonly string MESSAGE_FORMAT = """ private static readonly string MESSAGE_FORMAT = """
Use string.Empty instead of "" Use string.Empty instead of ""
"""; """;
private static readonly string DESCRIPTION = """Empty string literals ("") should be replaced with string.Empty for better code consistency and readability except in const contexts."""; private static readonly string DESCRIPTION = """Empty string literals ("") should be replaced with string.Empty for better code consistency and readability except in contexts requiring compile-time constants.""";
private const string CATEGORY = "Usage"; private const string CATEGORY = "Usage";
private static readonly DiagnosticDescriptor RULE = new(DIAGNOSTIC_ID, TITLE, MESSAGE_FORMAT, CATEGORY, DiagnosticSeverity.Error, isEnabledByDefault: true, description: DESCRIPTION); private static readonly DiagnosticDescriptor RULE = new(DIAGNOSTIC_ID, TITLE, MESSAGE_FORMAT, CATEGORY, DiagnosticSeverity.Error, isEnabledByDefault: true, description: DESCRIPTION);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => [RULE]; public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => [RULE];
public override void Initialize(AnalysisContext context) public override void Initialize(AnalysisContext context)
{ {
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.EnableConcurrentExecution(); context.EnableConcurrentExecution();
context.RegisterSyntaxNodeAction(AnalyzeEmptyStringLiteral, SyntaxKind.StringLiteralExpression); context.RegisterSyntaxNodeAction(AnalyzeEmptyStringLiteral, SyntaxKind.StringLiteralExpression);
} }
private static void AnalyzeEmptyStringLiteral(SyntaxNodeAnalysisContext context) private static void AnalyzeEmptyStringLiteral(SyntaxNodeAnalysisContext context)
{ {
var stringLiteral = (LiteralExpressionSyntax)context.Node; var stringLiteral = (LiteralExpressionSyntax)context.Node;
if (stringLiteral.Token.ValueText != string.Empty) if (stringLiteral.Token.ValueText != string.Empty)
return; return;
if (IsInConstContext(stringLiteral)) if (RequiresCompileTimeConstant(stringLiteral))
return; return;
if (IsInParameterDefaultValue(stringLiteral))
return;
var diagnostic = Diagnostic.Create(RULE, stringLiteral.GetLocation()); var diagnostic = Diagnostic.Create(RULE, stringLiteral.GetLocation());
context.ReportDiagnostic(diagnostic); context.ReportDiagnostic(diagnostic);
} }
private static bool IsInConstContext(LiteralExpressionSyntax stringLiteral) private static bool RequiresCompileTimeConstant(LiteralExpressionSyntax stringLiteral)
{
return IsInConstDeclarationInitializer(stringLiteral)
|| IsInParameterDefaultValue(stringLiteral)
|| IsInAttributeArgument(stringLiteral)
|| IsInSwitchCaseLabel(stringLiteral)
|| IsInConstantPattern(stringLiteral);
}
private static bool IsInConstDeclarationInitializer(LiteralExpressionSyntax stringLiteral)
{ {
var variableDeclarator = stringLiteral.FirstAncestorOrSelf<VariableDeclaratorSyntax>(); var variableDeclarator = stringLiteral.FirstAncestorOrSelf<VariableDeclaratorSyntax>();
if (variableDeclarator is null) if (variableDeclarator?.Initializer is null || !ContainsNode(variableDeclarator.Initializer.Value, stringLiteral))
return false; return false;
var declaration = variableDeclarator.Parent?.Parent; var declaration = variableDeclarator.Parent?.Parent;
return declaration switch return declaration switch
{ {
FieldDeclarationSyntax fieldDeclaration => fieldDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword), FieldDeclarationSyntax fieldDeclaration => fieldDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword),
LocalDeclarationStatementSyntax localDeclaration => localDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword), LocalDeclarationStatementSyntax localDeclaration => localDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword),
_ => false _ => false
}; };
} }
private static bool IsInParameterDefaultValue(LiteralExpressionSyntax stringLiteral) private static bool IsInParameterDefaultValue(LiteralExpressionSyntax stringLiteral)
{ {
// Prüfen, ob das String-Literal Teil eines Parameter-Defaults ist
var parameter = stringLiteral.FirstAncestorOrSelf<ParameterSyntax>(); var parameter = stringLiteral.FirstAncestorOrSelf<ParameterSyntax>();
if (parameter is null) return parameter?.Default is not null && ContainsNode(parameter.Default.Value, stringLiteral);
return false; }
// Überprüfen, ob das String-Literal im Default-Wert des Parameters verwendet wird private static bool IsInAttributeArgument(LiteralExpressionSyntax stringLiteral)
if (parameter.Default is not null && {
parameter.Default.Value == stringLiteral) var attributeArgument = stringLiteral.FirstAncestorOrSelf<AttributeArgumentSyntax>();
{ return attributeArgument is not null && ContainsNode(attributeArgument.Expression, stringLiteral);
return true; }
}
private static bool IsInSwitchCaseLabel(LiteralExpressionSyntax stringLiteral)
return false; {
var caseSwitchLabel = stringLiteral.FirstAncestorOrSelf<CaseSwitchLabelSyntax>();
return caseSwitchLabel is not null && ContainsNode(caseSwitchLabel.Value, stringLiteral);
}
private static bool IsInConstantPattern(LiteralExpressionSyntax stringLiteral)
{
var constantPattern = stringLiteral.FirstAncestorOrSelf<ConstantPatternSyntax>();
return constantPattern is not null && ContainsNode(constantPattern.Expression, stringLiteral);
}
private static bool ContainsNode(SyntaxNode parent, SyntaxNode child)
{
return parent.SpanStart <= child.SpanStart && child.Span.End <= parent.Span.End;
} }
} }