Files
Misaki.HighPerformance/Misaki.HighPerformance.Mathematics.CodeGen/Generators/GeneratorBase.cs
2026-02-01 01:56:17 +09:00

103 lines
2.9 KiB
C#

using Microsoft.CodeAnalysis;
using Misaki.HighPerformance.Mathematics.CodeGen.Models;
using System.Text;
namespace Misaki.HighPerformance.Mathematics.CodeGen.Generators
{
internal abstract class GeneratorBase
{
protected const string INLINE_METHOD_ATTRIBUTE = "[global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]";
protected static readonly string[] s_matrixComponents = new[] { "c0", "c1", "c2", "c3" };
protected static readonly string[] s_vectorComponents = new[] { "x", "y", "z", "w" };
protected readonly StringBuilder sourceBuilder = new();
protected NumericTypeInfo typeInfo = null!;
public string Generate(NumericTypeInfo typeInfo)
{
this.typeInfo = typeInfo;
sourceBuilder.Clear();
if (!Validation(out var message))
{
return message ?? string.Empty;
}
Initialize();
GenerateHeader();
GenerateNamespaceStart();
GenerateTypeStart();
GenerateBody();
GenerateTypeEnd();
GenerateNamespaceEnd();
return sourceBuilder.ToString();
}
protected void StartRegion(string name)
{
sourceBuilder.AppendLine($@"
#region {name}");
}
protected void EndRegion()
{
sourceBuilder.AppendLine($@"
#endregion");
}
protected virtual bool Validation(out string? message)
{
message = null;
return true;
}
protected virtual void Initialize()
{
}
protected virtual void GenerateHeader()
{
sourceBuilder.AppendLine(@"// <auto-generated>
// This code is generated by tool. Do not edit manually.
// Update this file may introduce incorrect behavior and will be lost if the code is regenerated.
// To update this file, edit the generator in the Misaki.HighPerformance.Mathematics.CodeGen and recompile it.
// </auto-generated>
");
sourceBuilder.AppendLine("#nullable enable");
}
protected virtual void GenerateNamespaceStart()
{
sourceBuilder.Append($@"
namespace {typeInfo.TypeSymbol.ContainingNamespace.ToDisplayString()}
{{");
}
protected virtual void GenerateTypeStart()
{
sourceBuilder.Append($@"
public partial struct {typeInfo.TypeSymbol.Name} : global::System.IEquatable<{typeInfo.TypeSymbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)}>
{{");
}
protected abstract void GenerateBody();
protected virtual void GenerateTypeEnd()
{
sourceBuilder.Append($@"
}}");
}
protected virtual void GenerateNamespaceEnd()
{
sourceBuilder.Append($@"
}}");
}
}
}