Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions src/FakeAnalyzers/DiagnosticDescriptors.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,12 @@ public static class DiagnosticDescriptors
category: "Code",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true);

public static readonly DiagnosticDescriptor TestFlagEnabled = new(
id: DiagnosticIds.TestFlagEnabled,
title: "Test flag is enabled",
messageFormat: "The test flag is enabled for '{0}'",
category: "Code",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true);
}
1 change: 1 addition & 0 deletions src/FakeAnalyzers/DiagnosticIds.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,5 @@ public static class DiagnosticIds
public const string NowUsedInsteadOfUtcNow = "FAKE0001";
public const string AsyncVoid = "FAKE0002";
public const string IdentifierContainsFoo = "FAKE0003";
public const string TestFlagEnabled = "FAKE0004";
}
40 changes: 40 additions & 0 deletions src/FakeAnalyzers/TestFlagAnalyzer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
namespace FakeAnalyzers;

using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;

[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class TestFlagAnalyzer : DiagnosticAnalyzer
{
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => [DiagnosticDescriptors.TestFlagEnabled];

public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);

context.RegisterCompilationStartAction(startContext =>
{
if (!startContext.Options.AnalyzerConfigOptionsProvider.GlobalOptions.TryGetValue("build_property.TestFlag", out var value) || value != "enabled")
{
return;
}

startContext.RegisterSyntaxNodeAction(AnalyzeClass, SyntaxKind.ClassDeclaration);
});
}

static void AnalyzeClass(SyntaxNodeAnalysisContext context)
{
if (context.Node is not ClassDeclarationSyntax classDeclaration)
{
return;
}

var diagnostic = Diagnostic.Create(DiagnosticDescriptors.TestFlagEnabled, classDeclaration.Identifier.GetLocation(), classDeclaration.Identifier.Text);
context.ReportDiagnostic(diagnostic);
}
}
27 changes: 27 additions & 0 deletions src/Particular.AnalyzerTesting/AnalyzerConfigOptionsFactory.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
namespace Particular.AnalyzerTesting;

using System.Collections.Generic;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;

static class AnalyzerConfigOptionsFactory
{
public static AnalyzerConfigOptionsProvider CreateOptionsProvider(IReadOnlyDictionary<string, string> properties)
=> new OptionsProvider(new DictionaryAnalyzerConfigOptions(properties));

public static AnalyzerOptions CreateAnalyzerOptions(IReadOnlyDictionary<string, string> properties)
=> new([], CreateOptionsProvider(properties));

sealed class OptionsProvider(AnalyzerConfigOptions options) : AnalyzerConfigOptionsProvider
{
public override AnalyzerConfigOptions GetOptions(SyntaxTree tree) => options;
public override AnalyzerConfigOptions GetOptions(AdditionalText textFile) => options;
public override AnalyzerConfigOptions GlobalOptions => options;
}

sealed class DictionaryAnalyzerConfigOptions(IReadOnlyDictionary<string, string> properties) : AnalyzerConfigOptions
{
public override bool TryGetValue(string key, out string value)
=> properties.TryGetValue(key, out value!);
}
}
4 changes: 2 additions & 2 deletions src/Particular.AnalyzerTesting/BaseAnalyzerTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ private protected static async Task<Diagnostic[]> GetCompilerDiagnostics(Project
private protected async Task<Diagnostic[]> GetAnalyzerDiagnostics(Compilation compilation, string[] ignoreDiagnosticIds, CancellationToken cancellationToken = default)
{
var analyzerTasks = analyzers
.Select(analyzer => compilation.GetAnalyzerDiagnostics(analyzer, cancellationToken))
.Select(analyzer => compilation.GetAnalyzerDiagnostics(analyzer, features, cancellationToken))
.ToArray();

await Task.WhenAll(analyzerTasks);
Expand Down Expand Up @@ -212,4 +212,4 @@ static void OutputAnalyzerDiagnostics(Diagnostic[] analyzerDiagnostics)

private protected record SourceFile(string Filename, string Source, TextSpan[] Spans);
private protected record DiagnosticInfo(string Filename, TextSpan Span, string Id);
}
}
6 changes: 3 additions & 3 deletions src/Particular.AnalyzerTesting/CompilationExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,12 @@ public void Compile(bool throwOnFailure = true)
Debug.WriteLine("Compilation failed.");
}

public async Task<IEnumerable<Diagnostic>> GetAnalyzerDiagnostics(DiagnosticAnalyzer analyzer, CancellationToken cancellationToken = default)
public async Task<IEnumerable<Diagnostic>> GetAnalyzerDiagnostics(DiagnosticAnalyzer analyzer, IReadOnlyDictionary<string, string> properties, CancellationToken cancellationToken = default)
{
var exceptions = new List<Exception>();

var analysisOptions = new CompilationWithAnalyzersOptions(
new AnalyzerOptions([]),
AnalyzerConfigOptionsFactory.CreateAnalyzerOptions(properties),
(exception, _, __) => exceptions.Add(exception),
concurrentAnalysis: false,
logAnalyzerExecutionTime: false);
Expand All @@ -56,4 +56,4 @@ public async Task<IEnumerable<Diagnostic>> GetAnalyzerDiagnostics(DiagnosticAnal
.ThenBy(diagnostic => diagnostic.Id);
}
}
}
}
13 changes: 10 additions & 3 deletions src/Particular.AnalyzerTesting/SourceGeneratorBuild.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,25 @@ class SourceGeneratorBuild
readonly GeneratorDriver driver;
readonly ImmutableArray<DiagnosticAnalyzer> analyzers;
readonly ImmutableArray<DiagnosticSuppressor> suppressors;
readonly AnalyzerConfigOptionsProvider optionsProvider;

public SourceGeneratorBuild(Compilation initialCompilation, GeneratorDriver driver, ImmutableArray<DiagnosticAnalyzer> analyzers, ImmutableArray<DiagnosticSuppressor> suppressors)
public SourceGeneratorBuild(Compilation initialCompilation, GeneratorDriver driver, ImmutableArray<DiagnosticAnalyzer> analyzers, ImmutableArray<DiagnosticSuppressor> suppressors, AnalyzerConfigOptionsProvider optionsProvider)
{
this.initialCompilation = initialCompilation;
this.driver = driver.RunGeneratorsAndUpdateCompilation(initialCompilation, out var outputCompilation, out var generatorDiagnostics);
this.analyzers = analyzers;
this.suppressors = suppressors;
this.optionsProvider = optionsProvider;

RunResult = this.driver.GetRunResult();

var allAnalyzers = analyzers.Concat(suppressors).ToImmutableArray();
OutputCompilation = outputCompilation.WithAnalyzers(allAnalyzers);
var analysisOptions = new CompilationWithAnalyzersOptions(
new([], optionsProvider),
onAnalyzerException: null,
concurrentAnalysis: false,
logAnalyzerExecutionTime: false);
OutputCompilation = outputCompilation.WithAnalyzers(allAnalyzers, analysisOptions);
GeneratorDiagnostics = generatorDiagnostics;
}

Expand All @@ -33,6 +40,6 @@ public SourceGeneratorBuild(Compilation initialCompilation, GeneratorDriver driv
public SourceGeneratorBuild Clone()
{
var cloneCompilation = initialCompilation.Clone();
return new SourceGeneratorBuild(cloneCompilation, driver, analyzers, suppressors);
return new SourceGeneratorBuild(cloneCompilation, driver, analyzers, suppressors, optionsProvider);
}
}
19 changes: 2 additions & 17 deletions src/Particular.AnalyzerTesting/SourceGeneratorTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ public SourceGeneratorTestResult Run()
disabledOutputs: IncrementalGeneratorOutputKind.None,
trackIncrementalGeneratorSteps: true);

var optsProvider = new OptionsProvider(new DictionaryAnalyzerOptions(features));
var optsProvider = AnalyzerConfigOptionsFactory.CreateOptionsProvider(features);

var driver = CSharpGeneratorDriver.Create(generators,
driverOptions: driverOpts,
Expand All @@ -183,7 +183,7 @@ public SourceGeneratorTestResult Run()

ImmutableArray<DiagnosticAnalyzer> analyzersToUse = analyzers.Count > 0 ? [.. analyzers] : [new NoOpAnalyzer()];
ImmutableArray<DiagnosticSuppressor> suppressorsToUse = suppressors.Count > 0 ? [.. suppressors] : [];
build = new SourceGeneratorBuild(initialCompilation, driver, analyzersToUse, suppressorsToUse);
build = new SourceGeneratorBuild(initialCompilation, driver, analyzersToUse, suppressorsToUse, optsProvider);

try
Comment thread
andreasohlund marked this conversation as resolved.
{
Expand Down Expand Up @@ -261,21 +261,6 @@ static bool TryGetTrackingNames(Type generatorType, out IReadOnlyCollection<stri
names = [];
return false;
}

class OptionsProvider(AnalyzerConfigOptions options) : AnalyzerConfigOptionsProvider
{
public override AnalyzerConfigOptions GetOptions(SyntaxTree tree) => options;
public override AnalyzerConfigOptions GetOptions(AdditionalText textFile) => options;
public override AnalyzerConfigOptions GlobalOptions => options;
}

internal sealed class DictionaryAnalyzerOptions(Dictionary<string, string> properties) : AnalyzerConfigOptions
{
public static DictionaryAnalyzerOptions Empty { get; } = new([]);

public override bool TryGetValue(string key, out string value)
=> properties.TryGetValue(key, out value!);
}
}

/// <summary>
Expand Down
22 changes: 22 additions & 0 deletions src/Tests/Analyzers/TestFlagAnalyzerTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
namespace Tests;

using System.Threading.Tasks;
using FakeAnalyzers;
using NUnit.Framework;
using Particular.AnalyzerTesting;

public class TestFlagAnalyzerTests
{
const string Code = """
public class [|MyClass|]
{
}
""";

[Test]
public Task ReportsDiagnosticWhenPropertyIsEnabled() =>
AnalyzerTest.ForAnalyzer<TestFlagAnalyzer>()
.WithProperty("build_property.TestFlag", "enabled")
.WithSource(Code)
.AssertDiagnostics(DiagnosticIds.TestFlagEnabled);
}
82 changes: 48 additions & 34 deletions src/Tests/SourceGenerators/BasicSourceGeneratorTest.cs
Original file line number Diff line number Diff line change
@@ -1,53 +1,67 @@
namespace Tests.SourceGenerators;

using System.Linq;
using System.Threading.Tasks;
using FakeAnalyzers;
using NUnit.Framework;
using Particular.AnalyzerTesting;

public class BasicSourceGeneratorTest
{
const string Source = $$"""
using System;

[AttributeUsage(AttributeTargets.All)]
public class MarkerAttribute : Attribute { }

[Marker]
public class Hello
{
[Marker]
private string there = "foo";

[Marker]
public DateTime Enjoy { get; set; }

public void Use()
{
_ = the;
_ = there;
}

[Marker]
private string the;

public void DoArguments([Marker] string test, [Marker] Hello results)
{
the = test;
}
}

""";

[Test]
public async Task BasicTest()
{
var source = $$"""
using System;

[AttributeUsage(AttributeTargets.All)]
public class MarkerAttribute : Attribute { }

[Marker]
public class Hello
{
[Marker]
private string there = "foo";

[Marker]
public DateTime Enjoy { get; set; }

public void Use()
{
_ = the;
_ = there;
}

[Marker]
private string the;

public void DoArguments([Marker] string test, [Marker] Hello results)
{
the = test;
}
}

""";

SourceGeneratorTest.ForIncrementalGenerator<SimpleSourceGenerator>()
.WithSource(source)
.WithSource(Source)
.Run()
.Approve()
.ToConsole()
.AssertRunsAreEqual()
.OutputSteps();
}
}

[Test]
public void AnalyzerSeesPropertyDuringSourceGeneratorRun()
{
var result = SourceGeneratorTest.ForIncrementalGenerator<SimpleSourceGenerator>()
.WithAnalyzer<TestFlagAnalyzer>()
.WithProperty("build_property.TestFlag", "enabled")
.SuppressCompilationErrors()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this suppress needed?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes see #31 (review)

I have confirmed that its still needed

.WithSource(Source)
.Run();

Assert.That(result.AnalyzerDiagnostics.Select(diagnostic => diagnostic.Id), Contains.Item(DiagnosticIds.TestFlagEnabled));
}
}
Loading