|
| 1 | +using System.Collections.Immutable; |
| 2 | +using System.Threading; |
| 3 | +using Microsoft.CodeAnalysis; |
| 4 | +using Microsoft.CodeAnalysis.CSharp; |
| 5 | +using Microsoft.CodeAnalysis.CSharp.Syntax; |
| 6 | +using Microsoft.CodeAnalysis.Diagnostics; |
| 7 | + |
| 8 | +namespace SqlServerSimulator.Analyzers; |
| 9 | + |
| 10 | +/// <summary> |
| 11 | +/// Flags a <c>switch</c> over a <see cref="System.Span{Char}"/> / |
| 12 | +/// <see cref="System.ReadOnlySpan{Char}"/> whose arm is written as a discard |
| 13 | +/// guard <c>_ when <governing>.SequenceEqual("literal")</c> instead of |
| 14 | +/// the equivalent constant string pattern <c>"literal"</c>. Since C# 11 a |
| 15 | +/// span-of-char switch matches string constants directly (the compiler |
| 16 | +/// lowers the pattern to the same element-wise comparison), so the |
| 17 | +/// hand-written <c>SequenceEqual</c> guard is pure noise — and, being a |
| 18 | +/// guard, it also opts the whole switch out of the |
| 19 | +/// <c>SortedConstantSwitchAnalyzer</c> (SSS005) ordering check that the |
| 20 | +/// constant-pattern form would enjoy. |
| 21 | +/// </summary> |
| 22 | +/// <remarks> |
| 23 | +/// This is the enforcement companion to <c>TransientUpperLowerInvariant</c> |
| 24 | +/// (SSS003): that rule pushes an uppercased switch scrutinee onto a |
| 25 | +/// <c>stackalloc</c> <c>Span<char></c>, and the natural next mistake is |
| 26 | +/// to reach for <c>SequenceEqual</c> guards — the pre-C#-11 idiom — rather |
| 27 | +/// than plain string-literal arms. The <c>ResolveBuiltIn</c> keyword-dispatch |
| 28 | +/// tables in <c>Parser/Expression.cs</c> are the reference for the intended |
| 29 | +/// shape: a <c>Span<char></c> scrutinee with bare <c>"NAME" => …</c> |
| 30 | +/// arms. Only the pure single-invocation guard is flagged (a negated or |
| 31 | +/// <c>&&</c>-combined condition has no single-pattern equivalent and |
| 32 | +/// is left alone), and only when the receiver is the switch's own governing |
| 33 | +/// expression (otherwise no constant pattern can replace it). |
| 34 | +/// </remarks> |
| 35 | +[DiagnosticAnalyzer(LanguageNames.CSharp)] |
| 36 | +public sealed class SpanCharSequenceEqualGuardAnalyzer : DiagnosticAnalyzer |
| 37 | +{ |
| 38 | + private static readonly DiagnosticDescriptor Rule = new( |
| 39 | + id: "SSS007", |
| 40 | + title: "Span<char> switch guard should be a constant string pattern", |
| 41 | + messageFormat: "Replace the guard '_ when {0}.SequenceEqual(\"{1}\")' with the constant pattern \"{1}\" — a Span<char>/ReadOnlySpan<char> switch matches string constants directly since C# 11", |
| 42 | + category: "Maintainability", |
| 43 | + defaultSeverity: DiagnosticSeverity.Warning, |
| 44 | + isEnabledByDefault: true, |
| 45 | + description: "A switch over Span<char> / ReadOnlySpan<char> matches string-literal patterns directly since C# 11 — the compiler lowers a constant string pattern to the same element-wise comparison a hand-written SequenceEqual performs. Writing the arm as a '_ when scrutinee.SequenceEqual(\"literal\")' guard is therefore redundant, and because it is a guard it also exempts the whole switch from the SSS005 sorted-arms check that the constant-pattern form would be held to. Only the pure single-invocation guard whose receiver is the switch's governing expression is flagged; a negated or combined condition, or one probing a different span, has no single-pattern equivalent and is left alone."); |
| 46 | + |
| 47 | + /// <inheritdoc/> |
| 48 | + public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => [Rule]; |
| 49 | + |
| 50 | + /// <inheritdoc/> |
| 51 | + public override void Initialize(AnalysisContext context) |
| 52 | + { |
| 53 | + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); |
| 54 | + context.EnableConcurrentExecution(); |
| 55 | + // Switch expressions only. A discard-with-guard case label |
| 56 | + // (`case _ when …`) doesn't parse as a discard in a switch statement |
| 57 | + // — `_` reads as an identifier there — so the anti-pattern this rule |
| 58 | + // targets can only be written in the expression form (which is also |
| 59 | + // where the clean span-constant-pattern alternative applies). |
| 60 | + context.RegisterSyntaxNodeAction(AnalyzeSwitchExpression, SyntaxKind.SwitchExpression); |
| 61 | + } |
| 62 | + |
| 63 | + private static void AnalyzeSwitchExpression(SyntaxNodeAnalysisContext context) |
| 64 | + { |
| 65 | + var switchExpression = (SwitchExpressionSyntax)context.Node; |
| 66 | + var governing = switchExpression.GoverningExpression; |
| 67 | + if (!IsSpanOfChar(governing, context.SemanticModel, context.CancellationToken)) |
| 68 | + return; |
| 69 | + |
| 70 | + foreach (var arm in switchExpression.Arms) |
| 71 | + { |
| 72 | + if (arm.Pattern is DiscardPatternSyntax && arm.WhenClause is { Condition: { } condition }) |
| 73 | + InspectGuard(context, governing, condition); |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + // Reports when `condition` is exactly `<governing>.SequenceEqual(<const |
| 78 | + // string>)` — the manual spelling of a constant string pattern. |
| 79 | + private static void InspectGuard(SyntaxNodeAnalysisContext context, ExpressionSyntax governing, ExpressionSyntax condition) |
| 80 | + { |
| 81 | + // netstandard2.0 (the analyzer TFM) has no System.Index, so list |
| 82 | + // patterns aren't available — match arity explicitly. |
| 83 | + if (condition is not InvocationExpressionSyntax |
| 84 | + { |
| 85 | + Expression: MemberAccessExpressionSyntax |
| 86 | + { |
| 87 | + Name.Identifier.ValueText: "SequenceEqual", |
| 88 | + Expression: { } receiver, |
| 89 | + }, |
| 90 | + ArgumentList.Arguments: { Count: 1 } arguments, |
| 91 | + }) |
| 92 | + { |
| 93 | + return; |
| 94 | + } |
| 95 | + |
| 96 | + var argument = arguments[0].Expression; |
| 97 | + |
| 98 | + // The receiver must be the switch's own scrutinee — a constant |
| 99 | + // pattern can only replace a guard that probes the governing value. |
| 100 | + if (!SyntaxFactory.AreEquivalent(receiver, governing)) |
| 101 | + return; |
| 102 | + |
| 103 | + if (context.SemanticModel.GetConstantValue(argument, context.CancellationToken).Value is not string text) |
| 104 | + return; |
| 105 | + |
| 106 | + context.ReportDiagnostic(Diagnostic.Create(Rule, condition.GetLocation(), receiver.ToString(), text)); |
| 107 | + } |
| 108 | + |
| 109 | + // True when the switch scrutinee is System.Span<char> or |
| 110 | + // System.ReadOnlySpan<char> — the two types C# 11's constant-string |
| 111 | + // pattern support applies to. |
| 112 | + private static bool IsSpanOfChar(ExpressionSyntax expression, SemanticModel model, CancellationToken cancellationToken) => |
| 113 | + model.GetTypeInfo(expression, cancellationToken).Type is INamedTypeSymbol |
| 114 | + { |
| 115 | + Name: "Span" or "ReadOnlySpan", |
| 116 | + ContainingNamespace: { Name: "System", ContainingNamespace.IsGlobalNamespace: true }, |
| 117 | + TypeArguments: { Length: 1 } typeArguments, |
| 118 | + } && typeArguments[0].SpecialType == SpecialType.System_Char; |
| 119 | +} |
0 commit comments