diff --git a/csharp-advanced-topics/SourceGeneratorInCSharp/Generator/Diagnostics/DiagnosticsDescriptors.cs b/csharp-advanced-topics/SourceGeneratorInCSharp/Generator/Diagnostics/DiagnosticsDescriptors.cs
index f78feceeb0..3966191426 100644
--- a/csharp-advanced-topics/SourceGeneratorInCSharp/Generator/Diagnostics/DiagnosticsDescriptors.cs
+++ b/csharp-advanced-topics/SourceGeneratorInCSharp/Generator/Diagnostics/DiagnosticsDescriptors.cs
@@ -5,10 +5,10 @@ namespace Generator.Diagnostics
public static class DiagnosticsDescriptors
{
public static readonly DiagnosticDescriptor ClassWithWrongNameMessage
- = new("ERR001", // id
- "Worng name", // title
- "The class '{0}' must be contains 'Model' prefix", // message
- "Generator", // category
+ = new("ERR001", // id
+ "Wrong name", // title
+ "The class '{0}' must contain 'Model' in its name", // message
+ "Generator", // category
DiagnosticSeverity.Error,
true);
}
diff --git a/csharp-advanced-topics/SourceGeneratorInCSharp/Generator/ExampleGenerator.cs b/csharp-advanced-topics/SourceGeneratorInCSharp/Generator/ExampleGenerator.cs
index 382417cde3..f66c7beabd 100644
--- a/csharp-advanced-topics/SourceGeneratorInCSharp/Generator/ExampleGenerator.cs
+++ b/csharp-advanced-topics/SourceGeneratorInCSharp/Generator/ExampleGenerator.cs
@@ -1,6 +1,5 @@
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
-using System.Diagnostics;
using System.Text;
namespace Generator
diff --git a/csharp-advanced-topics/SourceGeneratorInCSharp/Generator/Generator.csproj b/csharp-advanced-topics/SourceGeneratorInCSharp/Generator/Generator.csproj
index 9970e6eb36..fce7dea8d7 100644
--- a/csharp-advanced-topics/SourceGeneratorInCSharp/Generator/Generator.csproj
+++ b/csharp-advanced-topics/SourceGeneratorInCSharp/Generator/Generator.csproj
@@ -3,21 +3,24 @@
netstandard2.0
false
latest
+ enable
true
- False
- true
true
+ true
+ true
+ $(NoWarn);RS2008
-
+
-
-
+
+
+
-
\ No newline at end of file
+
diff --git a/csharp-advanced-topics/SourceGeneratorInCSharp/Generator/Helper/SourceGenerationHelper.cs b/csharp-advanced-topics/SourceGeneratorInCSharp/Generator/Helper/SourceGenerationHelper.cs
index ffeacb22be..a4365ca086 100644
--- a/csharp-advanced-topics/SourceGeneratorInCSharp/Generator/Helper/SourceGenerationHelper.cs
+++ b/csharp-advanced-topics/SourceGeneratorInCSharp/Generator/Helper/SourceGenerationHelper.cs
@@ -1,16 +1,13 @@
-using System;
-using System.Collections.Generic;
-using System.Text;
-
-namespace Generator.Helper
+namespace Generator.Helper
{
- public class SourceGenerationHelper
+ public static class SourceGenerationHelper
{
public const string Attribute = """
namespace Generator
{
[System.AttributeUsage(System.AttributeTargets.Class)]
- public class GenerateServiceAttribute : System.Attribute
+ [Microsoft.CodeAnalysis.Embedded]
+ internal sealed class GenerateServiceAttribute : System.Attribute
{
}
}
diff --git a/csharp-advanced-topics/SourceGeneratorInCSharp/Generator/Properties/launchSettings.json b/csharp-advanced-topics/SourceGeneratorInCSharp/Generator/Properties/launchSettings.json
index 40a93bd045..86c4572371 100644
--- a/csharp-advanced-topics/SourceGeneratorInCSharp/Generator/Properties/launchSettings.json
+++ b/csharp-advanced-topics/SourceGeneratorInCSharp/Generator/Properties/launchSettings.json
@@ -1,8 +1,8 @@
{
"profiles": {
"Generator": {
- "commandName": "Project",
- "nativeDebugging": false
+ "commandName": "DebugRoslynComponent",
+ "targetProject": "..\\SourceGeneratorInCSharp\\SourceGeneratorInCSharp.csproj"
}
}
}
\ No newline at end of file
diff --git a/csharp-advanced-topics/SourceGeneratorInCSharp/Generator/ServiceGenerator.cs b/csharp-advanced-topics/SourceGeneratorInCSharp/Generator/ServiceGenerator.cs
index 13a42e0c07..16d002e31e 100644
--- a/csharp-advanced-topics/SourceGeneratorInCSharp/Generator/ServiceGenerator.cs
+++ b/csharp-advanced-topics/SourceGeneratorInCSharp/Generator/ServiceGenerator.cs
@@ -4,9 +4,7 @@
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Scriban;
-using System.Collections.Immutable;
using System.IO;
-using System.Linq;
using System.Text;
namespace Generator
@@ -14,92 +12,93 @@ namespace Generator
[Generator]
public sealed class ServiceGenerator : IIncrementalGenerator
{
+ private static readonly Template ServiceTemplate =
+ Template.Parse(GetEmbeddedResource("Generator.Templates.Service.scriban"));
+
public void Initialize(IncrementalGeneratorInitializationContext context)
{
- context.RegisterPostInitializationOutput(ctx => ctx.AddSource(
- "GenerateServiceAttribute.g.cs",
- SourceText.From(SourceGenerationHelper.Attribute, Encoding.UTF8)));
-
- IncrementalValuesProvider enumDeclarations = context.SyntaxProvider
- .CreateSyntaxProvider(
- predicate: static (s, _) => IsSyntaxTargetForGeneration(s),
- transform: static (ctx, _) => GetTargetForGeneration(ctx));
-
- IncrementalValueProvider<(Compilation, ImmutableArray)> compilationAndEnums
- = context.CompilationProvider.Combine(enumDeclarations.Collect());
-
- context.RegisterSourceOutput(compilationAndEnums,
- (spc, source) => Execute(source.Item1, source.Item2, spc));
+ context.RegisterPostInitializationOutput(ctx =>
+ {
+ ctx.AddEmbeddedAttributeDefinition();
+ ctx.AddSource(
+ "GenerateServiceAttribute.g.cs",
+ SourceText.From(SourceGenerationHelper.Attribute, Encoding.UTF8));
+ });
+
+ IncrementalValuesProvider models = context.SyntaxProvider
+ .ForAttributeWithMetadataName(
+ "Generator.GenerateServiceAttribute",
+ predicate: static (node, _) => IsSyntaxTargetForGeneration(node),
+ transform: static (ctx, _) => GetTargetForGeneration(ctx));
+
+ context.RegisterSourceOutput(models,
+ static (spc, model) => Execute(model, spc));
}
public static bool IsSyntaxTargetForGeneration(SyntaxNode syntaxNode)
- {
- return syntaxNode is ClassDeclarationSyntax classDeclarationSyntax &&
- classDeclarationSyntax.AttributeLists.Count > 0 &&
- classDeclarationSyntax.AttributeLists
- .Any(al => al.Attributes
- .Any(a => a.Name.ToString() == "GenerateService"));
- }
+ => syntaxNode is ClassDeclarationSyntax;
- public static ClassDeclarationSyntax GetTargetForGeneration(GeneratorSyntaxContext context)
+ public static ServiceModel GetTargetForGeneration(GeneratorAttributeSyntaxContext context)
{
- var classDeclarationSyntax = (ClassDeclarationSyntax)context.Node;
-
- return classDeclarationSyntax;
+ var symbol = context.TargetSymbol;
+ var location = context.TargetNode is ClassDeclarationSyntax classSyntax
+ ? classSyntax.Identifier.GetLocation()
+ : symbol.Locations[0];
+
+ return new ServiceModel(
+ ClassName: symbol.Name,
+ ClassNamespace: symbol.ContainingNamespace.ToDisplayString(),
+ ClassAssembly: symbol.ContainingAssembly.Name,
+ Location: LocationInfo.From(location));
}
- public void Execute(Compilation compilation, ImmutableArray classes, SourceProductionContext context)
+
+ public static void Execute(ServiceModel model, SourceProductionContext context)
{
- foreach (var classSyntax in classes)
+ if (!model.ClassName.Contains("Model"))
{
- // Converting the class to a semantic model to access much more meaningful data.
- var model = compilation.GetSemanticModel(classSyntax.SyntaxTree);
-
- // Parse to declared symbol, so you can access each part of code separately,
- // such as interfaces, methods, members, contructor parameters etc.
- var symbol = model.GetDeclaredSymbol(classSyntax);
-
- var className = symbol.Name;
-
- if (!className.Contains("Model"))
- {
- var error = Diagnostic.Create(DiagnosticsDescriptors.ClassWithWrongNameMessage,
- classSyntax.Identifier.GetLocation(),
- className);
-
- context.ReportDiagnostic(error);
+ var error = Diagnostic.Create(DiagnosticsDescriptors.ClassWithWrongNameMessage,
+ model.Location.ToLocation(),
+ model.ClassName);
- return;
- }
+ context.ReportDiagnostic(error);
- var classNamespace = symbol.ContainingNamespace?.ToDisplayString();
-
- var classAssembly = symbol.ContainingAssembly?.Name;
-
- // Get the template string
- var text = GetEmbededResource("Generator.Templates.Service.scriban");
-
- var template = Template.Parse(text);
-
- var sourceCode = template.Render(new {
- ClassName = className,
- ClassNamespace = classNamespace,
- ClassAssembly = classAssembly
- });
-
- context.AddSource(
- $"{className}{"Service"}.g.cs",
- SourceText.From(sourceCode, Encoding.UTF8)
- );
+ return;
}
+
+ var sourceCode = ServiceTemplate.Render(new
+ {
+ model.ClassName,
+ model.ClassNamespace,
+ model.ClassAssembly
+ });
+
+ context.AddSource(
+ $"{model.ClassName}Service.g.cs",
+ SourceText.From(sourceCode, Encoding.UTF8));
}
- private string GetEmbededResource(string path)
+ private static string GetEmbeddedResource(string path)
{
- using var stream = GetType().Assembly.GetManifestResourceStream(path);
-
+ using var stream = typeof(ServiceGenerator).Assembly.GetManifestResourceStream(path)!;
using var streamReader = new StreamReader(stream);
return streamReader.ReadToEnd();
}
}
+
+ public readonly record struct ServiceModel(
+ string ClassName,
+ string ClassNamespace,
+ string ClassAssembly,
+ LocationInfo Location);
+
+ public readonly record struct LocationInfo(string FilePath, TextSpan Span, LinePositionSpan LineSpan)
+ {
+ public Location ToLocation() => Location.Create(FilePath, Span, LineSpan);
+
+ public static LocationInfo From(Location location)
+ => new(location.SourceTree?.FilePath ?? string.Empty,
+ location.SourceSpan,
+ location.GetLineSpan().Span);
+ }
}
diff --git a/csharp-advanced-topics/SourceGeneratorInCSharp/Generator/Templates/Service.scriban b/csharp-advanced-topics/SourceGeneratorInCSharp/Generator/Templates/Service.scriban
index e360051e2b..455431d581 100644
--- a/csharp-advanced-topics/SourceGeneratorInCSharp/Generator/Templates/Service.scriban
+++ b/csharp-advanced-topics/SourceGeneratorInCSharp/Generator/Templates/Service.scriban
@@ -1,6 +1,8 @@
+using System.Collections.Generic;
+using System.Linq;
using {{class_namespace}};
-namespace {{class_assembly}}.Services
+namespace {{class_assembly}}.Services
{
public partial class {{class_name}}Service
{
diff --git a/csharp-advanced-topics/SourceGeneratorInCSharp/SourceGeneratorInCSharp/Generated/Generator/Generator.ServiceGenerator/GenerateServiceAttribute.g.cs b/csharp-advanced-topics/SourceGeneratorInCSharp/SourceGeneratorInCSharp/Generated/Generator/Generator.ServiceGenerator/GenerateServiceAttribute.g.cs
index 0330213162..fe2f8920d0 100644
--- a/csharp-advanced-topics/SourceGeneratorInCSharp/SourceGeneratorInCSharp/Generated/Generator/Generator.ServiceGenerator/GenerateServiceAttribute.g.cs
+++ b/csharp-advanced-topics/SourceGeneratorInCSharp/SourceGeneratorInCSharp/Generated/Generator/Generator.ServiceGenerator/GenerateServiceAttribute.g.cs
@@ -1,8 +1,8 @@
-
-namespace Generator
+namespace Generator
{
[System.AttributeUsage(System.AttributeTargets.Class)]
- public class GenerateServiceAttribute : System.Attribute
+ [Microsoft.CodeAnalysis.Embedded]
+ internal sealed class GenerateServiceAttribute : System.Attribute
{
}
}
\ No newline at end of file
diff --git a/csharp-advanced-topics/SourceGeneratorInCSharp/SourceGeneratorInCSharp/Generated/Generator/Generator.ServiceGenerator/Microsoft.CodeAnalysis.EmbeddedAttribute.cs b/csharp-advanced-topics/SourceGeneratorInCSharp/SourceGeneratorInCSharp/Generated/Generator/Generator.ServiceGenerator/Microsoft.CodeAnalysis.EmbeddedAttribute.cs
new file mode 100644
index 0000000000..b81feb1436
--- /dev/null
+++ b/csharp-advanced-topics/SourceGeneratorInCSharp/SourceGeneratorInCSharp/Generated/Generator/Generator.ServiceGenerator/Microsoft.CodeAnalysis.EmbeddedAttribute.cs
@@ -0,0 +1,7 @@
+//
+namespace Microsoft.CodeAnalysis
+{
+ internal sealed partial class EmbeddedAttribute : global::System.Attribute
+ {
+ }
+}
\ No newline at end of file
diff --git a/csharp-advanced-topics/SourceGeneratorInCSharp/SourceGeneratorInCSharp/Generated/Generator/Generator.ServiceGenerator/PersonModelService.g.cs b/csharp-advanced-topics/SourceGeneratorInCSharp/SourceGeneratorInCSharp/Generated/Generator/Generator.ServiceGenerator/PersonModelService.g.cs
index 0ccc5db397..27c61f80f6 100644
--- a/csharp-advanced-topics/SourceGeneratorInCSharp/SourceGeneratorInCSharp/Generated/Generator/Generator.ServiceGenerator/PersonModelService.g.cs
+++ b/csharp-advanced-topics/SourceGeneratorInCSharp/SourceGeneratorInCSharp/Generated/Generator/Generator.ServiceGenerator/PersonModelService.g.cs
@@ -1,6 +1,8 @@
-using SourceGeneratorInCSharp.Models;
+using System.Collections.Generic;
+using System.Linq;
+using SourceGeneratorInCSharp.Models;
-namespace SourceGeneratorInCSharp.Services
+namespace SourceGeneratorInCSharp.Services
{
public partial class PersonModelService
{
diff --git a/csharp-advanced-topics/SourceGeneratorInCSharp/SourceGeneratorInCSharp/SourceGeneratorInCSharp.csproj b/csharp-advanced-topics/SourceGeneratorInCSharp/SourceGeneratorInCSharp/SourceGeneratorInCSharp.csproj
index ac308ca315..b40267757d 100644
--- a/csharp-advanced-topics/SourceGeneratorInCSharp/SourceGeneratorInCSharp/SourceGeneratorInCSharp.csproj
+++ b/csharp-advanced-topics/SourceGeneratorInCSharp/SourceGeneratorInCSharp/SourceGeneratorInCSharp.csproj
@@ -2,7 +2,7 @@
Exe
- net7.0
+ net11.0
latest
enable
enable
diff --git a/csharp-advanced-topics/SourceGeneratorInCSharp/Tests/Helper.cs b/csharp-advanced-topics/SourceGeneratorInCSharp/Tests/Helper.cs
index bd8fda8a65..ea9defc6eb 100644
--- a/csharp-advanced-topics/SourceGeneratorInCSharp/Tests/Helper.cs
+++ b/csharp-advanced-topics/SourceGeneratorInCSharp/Tests/Helper.cs
@@ -6,27 +6,34 @@ namespace Tests
{
public static class Helper
{
- public static string GetGeneratedOutput(string sourceCode)
+ public static CSharpCompilation CreateCompilation(string sourceCode)
{
var syntaxTree = CSharpSyntaxTree.ParseText(sourceCode);
var references = AppDomain.CurrentDomain.GetAssemblies()
.Where(assembly => !assembly.IsDynamic)
- .Select(assembly => MetadataReference.CreateFromFile(assembly.Location))
- .Cast();
+ .Select(assembly => MetadataReference.CreateFromFile(assembly.Location));
- var compilation = CSharpCompilation.Create("SourceGeneratorTests",
- new[] { syntaxTree },
+ return CSharpCompilation.Create("SourceGeneratorTests",
+ [syntaxTree],
references,
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
+ }
- // Source Generator to test
- var generator = new ServiceGenerator();
+ public static GeneratorRunResult RunGenerator(string sourceCode)
+ {
+ GeneratorDriver driver = CSharpGeneratorDriver.Create(new ServiceGenerator());
- CSharpGeneratorDriver.Create(generator)
- .RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics);
+ driver = driver.RunGenerators(CreateCompilation(sourceCode));
- return outputCompilation.SyntaxTrees.Skip(1).LastOrDefault()?.ToString();
+ return driver.GetRunResult().Results.Single();
+ }
+
+ public static string? GetGeneratedOutput(string sourceCode, string hintName)
+ {
+ return RunGenerator(sourceCode).GeneratedSources
+ .SingleOrDefault(source => source.HintName == hintName)
+ .SourceText?.ToString();
}
}
}
diff --git a/csharp-advanced-topics/SourceGeneratorInCSharp/Tests/SourceGeneratorsUnitTest.cs b/csharp-advanced-topics/SourceGeneratorInCSharp/Tests/SourceGeneratorsUnitTest.cs
index ce51957fa0..df0497114c 100644
--- a/csharp-advanced-topics/SourceGeneratorInCSharp/Tests/SourceGeneratorsUnitTest.cs
+++ b/csharp-advanced-topics/SourceGeneratorInCSharp/Tests/SourceGeneratorsUnitTest.cs
@@ -1,30 +1,36 @@
-namespace Tests
+using Generator;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CSharp;
+
+namespace Tests
{
[TestClass]
public class SourceGeneratorsUnitTest
{
- [TestMethod]
- public void WhenGeneratePersonModelService_ThenReturnCorrectOutput()
- {
- var input = """
- using Generator.Attributes;
+ private const string PersonModelSource = """
+ using Generator;
- namespace SourceGeneratorInCSharp.Models
+ namespace SourceGeneratorInCSharp.Models
+ {
+ [GenerateService]
+ public class PersonModel
{
- [GenerateService]
- public class PersonModel
- {
- public int Id { get; set; }
+ public int Id { get; set; }
- public string? Name { get; set; }
- }
+ public string? Name { get; set; }
}
- """;
+ }
+ """;
+ [TestMethod]
+ public void WhenGeneratePersonModelService_ThenReturnCorrectOutput()
+ {
var expectedResult = """
+ using System.Collections.Generic;
+ using System.Linq;
using SourceGeneratorInCSharp.Models;
- namespace SourceGeneratorTests.Services
+ namespace SourceGeneratorTests.Services
{
public partial class PersonModelService
{
@@ -58,9 +64,58 @@ public virtual void Delete(int id)
}
""";
- var output = Helper.GetGeneratedOutput(input);
+ var output = Helper.GetGeneratedOutput(PersonModelSource, "PersonModelService.g.cs");
+
+ Assert.AreEqual(expectedResult.ReplaceLineEndings(), output?.ReplaceLineEndings().TrimEnd());
+ }
+
+ [TestMethod]
+ public void WhenClassNameHasNoModel_ThenReportErr001()
+ {
+ var input = """
+ using Generator;
+
+ [GenerateService]
+ public class Person
+ {
+ public int Id { get; set; }
+ }
+ """;
+
+ var result = Helper.RunGenerator(input);
+
+ var diagnostic = result.Diagnostics.Single();
+ Assert.AreEqual("ERR001", diagnostic.Id);
+ Assert.IsEmpty(result.GeneratedSources.Where(s => s.HintName == "PersonService.g.cs"));
+ }
+
+ [TestMethod]
+ public void WhenUnrelatedCodeChanges_ThenGeneratedServiceIsCached()
+ {
+ var compilation = Helper.CreateCompilation(PersonModelSource);
+
+ GeneratorDriver driver = CSharpGeneratorDriver.Create(
+ [new ServiceGenerator().AsSourceGenerator()],
+ driverOptions: new GeneratorDriverOptions(
+ IncrementalGeneratorOutputKind.None,
+ trackIncrementalGeneratorSteps: true));
+
+ driver = driver.RunGenerators(compilation);
+
+ var edited = compilation.AddSyntaxTrees(
+ CSharpSyntaxTree.ParseText("public class Unrelated { }"));
+
+ driver = driver.RunGenerators(edited);
+
+ var reasons = driver.GetRunResult().Results.Single()
+ .TrackedOutputSteps
+ .SelectMany(step => step.Value)
+ .SelectMany(run => run.Outputs)
+ .Select(output => output.Reason)
+ .ToList();
- Assert.AreEqual(expectedResult, output);
+ Assert.IsNotEmpty(reasons);
+ Assert.IsTrue(reasons.All(reason => reason == IncrementalStepRunReason.Cached));
}
}
}
diff --git a/csharp-advanced-topics/SourceGeneratorInCSharp/Tests/Tests.csproj b/csharp-advanced-topics/SourceGeneratorInCSharp/Tests/Tests.csproj
index 1ae70f7d87..e37916f3e9 100644
--- a/csharp-advanced-topics/SourceGeneratorInCSharp/Tests/Tests.csproj
+++ b/csharp-advanced-topics/SourceGeneratorInCSharp/Tests/Tests.csproj
@@ -1,7 +1,7 @@
- net7.0
+ net11.0
enable
enable
@@ -10,11 +10,14 @@
-
-
-
-
-
+
+ runtime; build; native; contentfiles; analyzers; buildtransitive
+ all
+
+
+
+
+