Skip to content
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using System.Diagnostics;
using System.Text;

namespace Generator
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,24 @@
<TargetFramework>netstandard2.0</TargetFramework>
<IncludeBuildOutput>false</IncludeBuildOutput>
<LangVersion>latest</LangVersion>
<Nullable>enable</Nullable>
<IsRoslynComponent>true</IsRoslynComponent>
<RunAnalyzersDuringLiveAnalysis>False</RunAnalyzersDuringLiveAnalysis>
<PackageScribanIncludeSource>true</PackageScribanIncludeSource>
<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
<PackageScribanIncludeSource>true</PackageScribanIncludeSource>
<PolySharpIncludeRuntimeSupportedAttributes>true</PolySharpIncludeRuntimeSupportedAttributes>
<NoWarn>$(NoWarn);RS2008</NoWarn>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="4.4.0" PrivateAssets="all" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="5.9.0" PrivateAssets="all" />
<PackageReference Include="Microsoft.CSharp" Version="4.7.0" />
<PackageReference Include="Scriban" Version="5.7.0" IncludeAssets="Build" />
<PackageReference Include="System.Threading.Tasks.Extensions" Version="4.5.4" />
<PackageReference Include="Scriban" Version="7.6.1" IncludeAssets="Build" />
<PackageReference Include="System.Threading.Tasks.Extensions" Version="4.6.3" />
<PackageReference Include="PolySharp" Version="1.17.1" PrivateAssets="all" IncludeAssets="runtime; build; native; contentfiles; analyzers" />
</ItemGroup>

<ItemGroup>
<None Remove="Templates\**\*.scriban" />
<EmbeddedResource Include="Templates\**\*.scriban" />
</ItemGroup>
</Project>
</Project>
Original file line number Diff line number Diff line change
@@ -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
{
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
{
"profiles": {
"Generator": {
"commandName": "Project",
"nativeDebugging": false
"commandName": "DebugRoslynComponent",
"targetProject": "..\\SourceGeneratorInCSharp\\SourceGeneratorInCSharp.csproj"
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,102 +4,101 @@
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
{
[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<ClassDeclarationSyntax> enumDeclarations = context.SyntaxProvider
.CreateSyntaxProvider(
predicate: static (s, _) => IsSyntaxTargetForGeneration(s),
transform: static (ctx, _) => GetTargetForGeneration(ctx));

IncrementalValueProvider<(Compilation, ImmutableArray<ClassDeclarationSyntax>)> 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<ServiceModel> 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<ClassDeclarationSyntax> 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);
}
}
Original file line number Diff line number Diff line change
@@ -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
{
Expand Down
Original file line number Diff line number Diff line change
@@ -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
{
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
// <auto-generated/>
namespace Microsoft.CodeAnalysis
{
internal sealed partial class EmbeddedAttribute : global::System.Attribute
{
}
}
Original file line number Diff line number Diff line change
@@ -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
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<TargetFramework>net11.0</TargetFramework>
<LangVersion>latest</LangVersion>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
Expand Down
27 changes: 17 additions & 10 deletions csharp-advanced-topics/SourceGeneratorInCSharp/Tests/Helper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<MetadataReference>();
.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();
}
}
}
Loading
Loading