генерация пре-генерируемого репозитория методов работает

This commit is contained in:
2025-02-04 22:10:48 +03:00
parent f0f8460632
commit cfd68aeac9
11 changed files with 62 additions and 17 deletions
@@ -1,5 +1,7 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis;
@@ -31,7 +33,6 @@ namespace {Namespace}
public void Initialize(IncrementalGeneratorInitializationContext context)
{
// Filter classes annotated with the [Report] attribute. Only filtered Syntax Nodes can trigger code generation.
var provider = context.SyntaxProvider
.CreateSyntaxProvider(
@@ -82,12 +83,15 @@ namespace {Namespace}
private void GenerateCode(SourceProductionContext context, Compilation compilation,
ImmutableArray<InterfaceDeclarationSyntax> classDeclarations)
{
var methods = new List<(string, IMethodSymbol)>();
// Go through all filtered class declarations.
foreach (var classDeclarationSyntax in classDeclarations)
{
// We need to get semantic model of the class to retrieve metadata.
var semanticModel = compilation.GetSemanticModel(classDeclarationSyntax.SyntaxTree);
// Symbols allow us to get the compile-time information.
if (semanticModel.GetDeclaredSymbol(classDeclarationSyntax) is not INamedTypeSymbol classSymbol)
continue;
@@ -100,7 +104,7 @@ namespace {Namespace}
// Go through all class members with a particular type (property) to generate method lines.
var methodBody = classSymbol.GetMembers()
.OfType<IMethodSymbol>();
Console.WriteLine(methodBody.Select(i => i.ToDisplayString()));
methods.AddRange(methodBody.Select(i => (namespaceName + "." + className, i)));
var originalName = className;
// Build up the source code
@@ -119,8 +123,47 @@ partial class {className} (int id, ISerialisationModule.IFrontendSerialisationMo
}}
";
// Add the source code to the compilation.
// context.AddSource($"{className}.g.cs", SourceText.From(code, Encoding.UTF8));
}
var methodsStringed = methods.Select(i =>
$"typeof({i.Item1}).GetMethod(\"{i.Item2.Name}\", [{string.Join(", ", i.Item2.Parameters.Select(p => $"typeof({p.Type.ToDisplayString()})"))}])")
.ToList();
var coCodegenRepoCode = @$"// <auto-generated/>
using System.Collections.Generic;
using System.Reflection;
namespace mROA.Codegen;
public class CoCodegenMethodRepository :IMethodRepository
{{
private readonly List<MethodInfo> _methods = [
{string.Join(", \r\n\t\t", methodsStringed)}
];
public MethodInfo GetMethod(int id)
{{
if (_methods.Count <= id)
return null;
return _methods[id];
}}
public int RegisterMethod(MethodInfo method)
{{
_methods.Add(method);
return _methods.Count - 1;
}}
public IEnumerable<MethodInfo> GetMethods()
{{
return _methods;
}}
}}
";
context.AddSource($"CoCodegenMethodRepository.g.cs", SourceText.From(coCodegenRepoCode, Encoding.UTF8));
}
}