|
| 1 | +// <copyright file="ConfigurationBuilderWithKeysAnalyzer.cs" company="Datadog"> |
| 2 | +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. |
| 3 | +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. |
| 4 | +// </copyright> |
| 5 | + |
| 6 | +using System.Collections.Immutable; |
| 7 | +using Microsoft.CodeAnalysis; |
| 8 | +using Microsoft.CodeAnalysis.CSharp; |
| 9 | +using Microsoft.CodeAnalysis.CSharp.Syntax; |
| 10 | +using Microsoft.CodeAnalysis.Diagnostics; |
| 11 | + |
| 12 | +namespace Datadog.Trace.Tools.Analyzers.ConfigurationAnalyzers |
| 13 | +{ |
| 14 | + /// <summary> |
| 15 | + /// Analyzer to ensure that ConfigurationBuilder.WithKeys method calls only accept string constants |
| 16 | + /// from PlatformKeys or ConfigurationKeys classes, not hardcoded strings or variables. |
| 17 | + /// </summary> |
| 18 | + [DiagnosticAnalyzer(LanguageNames.CSharp)] |
| 19 | + public class ConfigurationBuilderWithKeysAnalyzer : DiagnosticAnalyzer |
| 20 | + { |
| 21 | + /// <summary> |
| 22 | + /// Diagnostic descriptor for when WithKeys or Or is called with a hardcoded string instead of a constant from PlatformKeys or ConfigurationKeys. |
| 23 | + /// </summary> |
| 24 | + public static readonly DiagnosticDescriptor UseConfigurationConstantsRule = new DiagnosticDescriptor( |
| 25 | + id: "DD0007", |
| 26 | + title: "Use configuration constants instead of hardcoded strings in WithKeys/Or calls", |
| 27 | + messageFormat: "{0} method should use constants from PlatformKeys or ConfigurationKeys classes instead of hardcoded string '{1}'", |
| 28 | + category: "Usage", |
| 29 | + defaultSeverity: DiagnosticSeverity.Error, |
| 30 | + isEnabledByDefault: true, |
| 31 | + description: "ConfigurationBuilder.WithKeys and HasKeys.Or method calls should only accept string constants from PlatformKeys or ConfigurationKeys classes to ensure consistency and avoid typos."); |
| 32 | + |
| 33 | + /// <summary> |
| 34 | + /// Diagnostic descriptor for when WithKeys or Or is called with a variable instead of a constant from PlatformKeys or ConfigurationKeys. |
| 35 | + /// </summary> |
| 36 | + public static readonly DiagnosticDescriptor UseConfigurationConstantsNotVariablesRule = new DiagnosticDescriptor( |
| 37 | + id: "DD0008", |
| 38 | + title: "Use configuration constants instead of variables in WithKeys/Or calls", |
| 39 | + messageFormat: "{0} method should use constants from PlatformKeys or ConfigurationKeys classes instead of variable '{1}'", |
| 40 | + category: "Usage", |
| 41 | + defaultSeverity: DiagnosticSeverity.Error, |
| 42 | + isEnabledByDefault: true, |
| 43 | + description: "ConfigurationBuilder.WithKeys and HasKeys.Or method calls should only accept string constants from PlatformKeys or ConfigurationKeys classes, not variables or computed values."); |
| 44 | + |
| 45 | + public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => |
| 46 | + ImmutableArray.Create(UseConfigurationConstantsRule, UseConfigurationConstantsNotVariablesRule); |
| 47 | + |
| 48 | + public override void Initialize(AnalysisContext context) |
| 49 | + { |
| 50 | + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); |
| 51 | + context.EnableConcurrentExecution(); |
| 52 | + context.RegisterSyntaxNodeAction(AnalyzeInvocationExpression, SyntaxKind.InvocationExpression); |
| 53 | + } |
| 54 | + |
| 55 | + private static void AnalyzeInvocationExpression(SyntaxNodeAnalysisContext context) |
| 56 | + { |
| 57 | + var invocation = (InvocationExpressionSyntax)context.Node; |
| 58 | + |
| 59 | + // Check if this is a WithKeys or Or method call |
| 60 | + var methodName = GetConfigurationMethodName(invocation, context.SemanticModel); |
| 61 | + if (methodName == null) |
| 62 | + { |
| 63 | + return; |
| 64 | + } |
| 65 | + |
| 66 | + // Analyze each argument to the method |
| 67 | + var argumentList = invocation.ArgumentList; |
| 68 | + if (argumentList?.Arguments.Count > 0) |
| 69 | + { |
| 70 | + var argument = argumentList.Arguments[0]; // Both WithKeys and Or take a single string argument |
| 71 | + AnalyzeConfigurationArgument(context, argument, methodName); |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + private static string GetConfigurationMethodName(InvocationExpressionSyntax invocation, SemanticModel semanticModel) |
| 76 | + { |
| 77 | + if (invocation.Expression is MemberAccessExpressionSyntax memberAccess) |
| 78 | + { |
| 79 | + var methodName = memberAccess.Name.Identifier.ValueText; |
| 80 | + |
| 81 | + // Check if the method being called is "WithKeys" or "Or" |
| 82 | + if (methodName == "WithKeys" || methodName == "Or") |
| 83 | + { |
| 84 | + // Get the symbol info for the method |
| 85 | + var symbolInfo = semanticModel.GetSymbolInfo(memberAccess); |
| 86 | + if (symbolInfo.Symbol is IMethodSymbol method) |
| 87 | + { |
| 88 | + var containingType = method.ContainingType?.Name; |
| 89 | + var containingNamespace = method.ContainingNamespace?.ToDisplayString(); |
| 90 | + |
| 91 | + // Check if this is the ConfigurationBuilder.WithKeys method |
| 92 | + if (methodName == "WithKeys" && |
| 93 | + containingType == "ConfigurationBuilder" && |
| 94 | + containingNamespace == "Datadog.Trace.Configuration.Telemetry") |
| 95 | + { |
| 96 | + return "WithKeys"; |
| 97 | + } |
| 98 | + |
| 99 | + // Check if this is the HasKeys.Or method |
| 100 | + if (methodName == "Or" && |
| 101 | + containingType == "HasKeys" && |
| 102 | + containingNamespace == "Datadog.Trace.Configuration.Telemetry") |
| 103 | + { |
| 104 | + return "Or"; |
| 105 | + } |
| 106 | + } |
| 107 | + } |
| 108 | + } |
| 109 | + |
| 110 | + return null; |
| 111 | + } |
| 112 | + |
| 113 | + private static void AnalyzeConfigurationArgument(SyntaxNodeAnalysisContext context, ArgumentSyntax argument, string methodName) |
| 114 | + { |
| 115 | + var expression = argument.Expression; |
| 116 | + |
| 117 | + switch (expression) |
| 118 | + { |
| 119 | + case LiteralExpressionSyntax literal when literal.Token.IsKind(SyntaxKind.StringLiteralToken): |
| 120 | + // This is a hardcoded string literal - report diagnostic |
| 121 | + var literalValue = literal.Token.ValueText; |
| 122 | + var diagnostic = Diagnostic.Create( |
| 123 | + UseConfigurationConstantsRule, |
| 124 | + literal.GetLocation(), |
| 125 | + methodName, |
| 126 | + literalValue); |
| 127 | + context.ReportDiagnostic(diagnostic); |
| 128 | + break; |
| 129 | + |
| 130 | + case MemberAccessExpressionSyntax memberAccess: |
| 131 | + // Check if this is accessing a constant from PlatformKeys or ConfigurationKeys |
| 132 | + if (!IsValidConfigurationConstant(memberAccess, context.SemanticModel)) |
| 133 | + { |
| 134 | + // This is accessing something else - report diagnostic |
| 135 | + var memberName = memberAccess.ToString(); |
| 136 | + var memberDiagnostic = Diagnostic.Create( |
| 137 | + UseConfigurationConstantsNotVariablesRule, |
| 138 | + memberAccess.GetLocation(), |
| 139 | + methodName, |
| 140 | + memberName); |
| 141 | + context.ReportDiagnostic(memberDiagnostic); |
| 142 | + } |
| 143 | + |
| 144 | + break; |
| 145 | + |
| 146 | + case IdentifierNameSyntax identifier: |
| 147 | + // This is a variable or local constant - report diagnostic |
| 148 | + var identifierName = identifier.Identifier.ValueText; |
| 149 | + var variableDiagnostic = Diagnostic.Create( |
| 150 | + UseConfigurationConstantsNotVariablesRule, |
| 151 | + identifier.GetLocation(), |
| 152 | + methodName, |
| 153 | + identifierName); |
| 154 | + context.ReportDiagnostic(variableDiagnostic); |
| 155 | + break; |
| 156 | + |
| 157 | + default: |
| 158 | + // Any other expression type (method calls, computed values, etc.) - report diagnostic |
| 159 | + var expressionText = expression.ToString(); |
| 160 | + var defaultDiagnostic = Diagnostic.Create( |
| 161 | + UseConfigurationConstantsNotVariablesRule, |
| 162 | + expression.GetLocation(), |
| 163 | + methodName, |
| 164 | + expressionText); |
| 165 | + context.ReportDiagnostic(defaultDiagnostic); |
| 166 | + break; |
| 167 | + } |
| 168 | + } |
| 169 | + |
| 170 | + private static bool IsValidConfigurationConstant(MemberAccessExpressionSyntax memberAccess, SemanticModel semanticModel) |
| 171 | + { |
| 172 | + var symbolInfo = semanticModel.GetSymbolInfo(memberAccess); |
| 173 | + if (symbolInfo.Symbol is IFieldSymbol field) |
| 174 | + { |
| 175 | + // Check if this is a const string field |
| 176 | + if (field.IsConst && field.Type?.SpecialType == SpecialType.System_String) |
| 177 | + { |
| 178 | + var containingType = field.ContainingType; |
| 179 | + if (containingType != null) |
| 180 | + { |
| 181 | + // Check if the containing type is PlatformKeys or ConfigurationKeys (or their nested classes) |
| 182 | + return IsValidConfigurationClass(containingType); |
| 183 | + } |
| 184 | + } |
| 185 | + } |
| 186 | + |
| 187 | + return false; |
| 188 | + } |
| 189 | + |
| 190 | + private static bool IsValidConfigurationClass(INamedTypeSymbol typeSymbol) |
| 191 | + { |
| 192 | + // Check if this is PlatformKeys or ConfigurationKeys class or their nested classes |
| 193 | + var currentType = typeSymbol; |
| 194 | + while (currentType != null) |
| 195 | + { |
| 196 | + var typeName = currentType.Name; |
| 197 | + var namespaceName = currentType.ContainingNamespace?.ToDisplayString(); |
| 198 | + |
| 199 | + // Check for PlatformKeys class |
| 200 | + if (typeName == "PlatformKeys" && namespaceName == "Datadog.Trace.Configuration") |
| 201 | + { |
| 202 | + return true; |
| 203 | + } |
| 204 | + |
| 205 | + // Check for ConfigurationKeys class |
| 206 | + if (typeName == "ConfigurationKeys" && namespaceName == "Datadog.Trace.Configuration") |
| 207 | + { |
| 208 | + return true; |
| 209 | + } |
| 210 | + |
| 211 | + // Check nested classes within PlatformKeys or ConfigurationKeys |
| 212 | + currentType = currentType.ContainingType; |
| 213 | + } |
| 214 | + |
| 215 | + return false; |
| 216 | + } |
| 217 | + } |
| 218 | +} |
0 commit comments