| 1 | using System.Collections.Immutable; |
| 2 | using Microsoft.CodeAnalysis; |
| 3 | using Microsoft.CodeAnalysis.CSharp; |
| 4 | using Microsoft.CodeAnalysis.Diagnostics; |
| 5 | |
| 6 | namespace AgentForge.PluginAnalyzers.Tests; |
| 7 | |
| 8 | internal static class AnalyzerTestHelper |
| 9 | { |
| 10 | private static readonly MetadataReference[] DefaultReferences = |
| 11 | [ |
| 12 | MetadataReference.CreateFromFile(typeof(object).Assembly.Location), |
| 13 | MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location), |
| 14 | MetadataReference.CreateFromFile(typeof(ImmutableArray<>).Assembly.Location), |
| 15 | MetadataReference.CreateFromFile(typeof(DiagnosticAnalyzer).Assembly.Location), |
| 16 | ]; |
| 17 | |
| 18 | public static async Task<ImmutableArray<Diagnostic>> GetDiagnosticsAsync( |
| 19 | string source, |
| 20 | string assemblyName = "AgentForge.Plugin.Test", |
| 21 | IEnumerable<MetadataReference>? extraReferences = null, |
| 22 | IEnumerable<AdditionalText>? additionalFiles = null) |
| 23 | { |
| 24 | var syntaxTree = CSharpSyntaxTree.ParseText(source); |
| 25 | var references = DefaultReferences |
| 26 | .Concat(extraReferences ?? []) |
| 27 | .ToArray(); |
| 28 | |
| 29 | var compilation = CSharpCompilation.Create( |
| 30 | assemblyName, |
| 31 | [syntaxTree], |
| 32 | references, |
| 33 | new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); |
| 34 | |
| 35 | var analyzer = new ForgePluginAnalyzer(); |
| 36 | var compilationWithAnalyzers = compilation.WithAnalyzers( |
| 37 | ImmutableArray.Create<DiagnosticAnalyzer>(analyzer), |
| 38 | new AnalyzerOptions(additionalFiles?.ToImmutableArray() ?? [])); |
| 39 | |
| 40 | return await compilationWithAnalyzers.GetAnalyzerDiagnosticsAsync(); |
| 41 | } |
| 42 | |
| 43 | public static MetadataReference SdkReference => |
| 44 | MetadataReference.CreateFromFile(typeof(AgentForge.Abstractions.ForgeCommandDescriptor).Assembly.Location); |
| 45 | |
| 46 | public static bool HasDiagnostic( |
| 47 | ImmutableArray<Diagnostic> diagnostics, |
| 48 | string id, |
| 49 | DiagnosticSeverity? severity = null) => |
| 50 | diagnostics.Any(d => |
| 51 | d.Id == id |
| 52 | && (severity is null || d.Severity == severity)); |
| 53 | } |
| 54 | |