|
| 1 | +using System.Collections.Immutable; |
| 2 | +using Microsoft.CodeAnalysis; |
| 3 | +using Microsoft.CodeAnalysis.CSharp; |
| 4 | +using Microsoft.CodeAnalysis.CSharp.Syntax; |
| 5 | +using Microsoft.CodeAnalysis.Diagnostics; |
| 6 | + |
| 7 | +namespace LearnStack.Analyzers; |
| 8 | + |
| 9 | +/// <summary> |
| 10 | +/// Rule "LearnStackException-DomainExceptionThrow" (Roslyn diagnostic id |
| 11 | +/// <see cref="DiagnosticId"/> = <c>LS0001</c>) — flags every |
| 12 | +/// <c>throw new DomainException(...)</c> in Domain / Application code per |
| 13 | +/// ADR-0032 § Sub-decision 4. Expected business-rule violations return |
| 14 | +/// <c>Result.Fail(business_rule_violation, ...)</c>; the exception is |
| 15 | +/// reserved for programmer errors. |
| 16 | +/// </summary> |
| 17 | +/// <remarks> |
| 18 | +/// <para> |
| 19 | +/// The Roslyn diagnostic id MUST be a valid identifier (letters/digits, no |
| 20 | +/// hyphens) — Roslyn throws <c>AD0001</c> at report time otherwise. The |
| 21 | +/// human-readable rule name <c>LearnStackException-DomainExceptionThrow</c> |
| 22 | +/// (ADR-0032 / Standards 21 naming convention) is carried in the title and |
| 23 | +/// help text; the wire-level id is <c>LS0001</c>. See ADR-0032 Amendment 1. |
| 24 | +/// </para> |
| 25 | +/// <para> |
| 26 | +/// Severity: <see cref="DiagnosticSeverity.Warning"/> in Phase 02a. Per |
| 27 | +/// ADR-0032 the severity escalates to <see cref="DiagnosticSeverity.Error"/> |
| 28 | +/// after Phase 03 exit when every existing call site has been migrated. |
| 29 | +/// Until then <c>LS0001</c> is listed in <c>WarningsNotAsErrors</c> |
| 30 | +/// (Directory.Build.props) so a legitimate aggregate-invariant throw does |
| 31 | +/// not break CI under <c>TreatWarningsAsErrors</c> before the documented |
| 32 | +/// escalation point. |
| 33 | +/// </para> |
| 34 | +/// </remarks> |
| 35 | +[DiagnosticAnalyzer(LanguageNames.CSharp)] |
| 36 | +public sealed class DomainExceptionThrowAnalyzer : DiagnosticAnalyzer |
| 37 | +{ |
| 38 | + public const string DiagnosticId = "LS0001"; |
| 39 | + |
| 40 | + /// <summary>The human-readable rule name (ADR-0032 / Standards 21).</summary> |
| 41 | + public const string RuleName = "LearnStackException-DomainExceptionThrow"; |
| 42 | + |
| 43 | + private static readonly LocalizableString Title = |
| 44 | + "Avoid throwing DomainException for expected business-rule violations (LearnStackException-DomainExceptionThrow)"; |
| 45 | + |
| 46 | + private static readonly LocalizableString MessageFormat = |
| 47 | + "DomainException is reserved for programmer errors. " + |
| 48 | + "Return Result.Fail(business_rule_violation, ...) instead."; |
| 49 | + |
| 50 | + private static readonly LocalizableString Description = |
| 51 | + "ADR-0032 § Sub-decision 4 reserves DomainException for aggregate-invariant " + |
| 52 | + "violations that signal a programming mistake. Expected business-rule " + |
| 53 | + "violations are an outcome — return Result.Fail(business_rule_violation, ...) " + |
| 54 | + "from the domain method."; |
| 55 | + |
| 56 | + private static readonly DiagnosticDescriptor Rule = new( |
| 57 | + id: DiagnosticId, |
| 58 | + title: Title, |
| 59 | + messageFormat: MessageFormat, |
| 60 | + category: "Design", |
| 61 | + defaultSeverity: DiagnosticSeverity.Warning, |
| 62 | + isEnabledByDefault: true, |
| 63 | + description: Description, |
| 64 | + helpLinkUri: "https://github.com/cemililik/LearnStack/blob/main/docs/decisions/0032-exception-handling-logging-and-observability.md"); |
| 65 | + |
| 66 | + public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics |
| 67 | + => ImmutableArray.Create(Rule); |
| 68 | + |
| 69 | + public override void Initialize(AnalysisContext context) |
| 70 | + { |
| 71 | + if (context is null) throw new System.ArgumentNullException(nameof(context)); |
| 72 | + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); |
| 73 | + context.EnableConcurrentExecution(); |
| 74 | + context.RegisterSyntaxNodeAction(AnalyzeThrowExpression, SyntaxKind.ThrowExpression); |
| 75 | + context.RegisterSyntaxNodeAction(AnalyzeThrowStatement, SyntaxKind.ThrowStatement); |
| 76 | + } |
| 77 | + |
| 78 | + private static void AnalyzeThrowStatement(SyntaxNodeAnalysisContext context) |
| 79 | + { |
| 80 | + var node = (ThrowStatementSyntax)context.Node; |
| 81 | + if (node.Expression is null) return; |
| 82 | + InspectThrown(context, node.Expression); |
| 83 | + } |
| 84 | + |
| 85 | + private static void AnalyzeThrowExpression(SyntaxNodeAnalysisContext context) |
| 86 | + { |
| 87 | + var node = (ThrowExpressionSyntax)context.Node; |
| 88 | + InspectThrown(context, node.Expression); |
| 89 | + } |
| 90 | + |
| 91 | + private static void InspectThrown(SyntaxNodeAnalysisContext context, ExpressionSyntax expression) |
| 92 | + { |
| 93 | + if (expression is not ObjectCreationExpressionSyntax creation) |
| 94 | + { |
| 95 | + return; |
| 96 | + } |
| 97 | + |
| 98 | + var typeInfo = context.SemanticModel.GetTypeInfo(creation, context.CancellationToken); |
| 99 | + var symbol = typeInfo.Type; |
| 100 | + if (symbol is null) |
| 101 | + { |
| 102 | + return; |
| 103 | + } |
| 104 | + |
| 105 | + if (!IsDomainException(symbol)) |
| 106 | + { |
| 107 | + return; |
| 108 | + } |
| 109 | + |
| 110 | + context.ReportDiagnostic(Diagnostic.Create(Rule, creation.GetLocation())); |
| 111 | + } |
| 112 | + |
| 113 | + private static bool IsDomainException(ITypeSymbol type) |
| 114 | + { |
| 115 | + for (var current = type; current is not null; current = current.BaseType) |
| 116 | + { |
| 117 | + if (current.Name == "DomainException" && |
| 118 | + current.ContainingNamespace?.ToDisplayString() == "LearnStack.SharedKernel.Errors") |
| 119 | + { |
| 120 | + return true; |
| 121 | + } |
| 122 | + } |
| 123 | + |
| 124 | + return false; |
| 125 | + } |
| 126 | +} |
0 commit comments