using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.Contracts;
using ComputeSharp.__Internals;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
#pragma warning disable CS0618
namespace ComputeSharp.SourceGenerators;
///
public sealed partial class IShaderGenerator
{
///
private static partial class GetDispatchId
{
///
/// Creates a instance for the GetDispatchId method.
///
///The names of all instance fields within the current shader type.
/// The resulting instance for the GetDispatchId method.
public static MethodDeclarationSyntax GetSyntax(ImmutableArray delegateFieldNames)
{
// This code produces a method declaration as follows:
//
// readonly int global::ComputeSharp.__Internals.IShader.GetDispatchId()
// {
//
// }
return
MethodDeclaration(
PredefinedType(Token(SyntaxKind.IntKeyword)),
Identifier("GetDispatchId"))
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}")))
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
.WithBody(GetShaderHashCodeBody(delegateFieldNames));
}
///
/// Gets a instance with the logic to compute the hashcode of a given shader type.
///
/// The names of all instance fields within the current shader type.
/// The instance to hash the input shader.
[Pure]
private static BlockSyntax GetShaderHashCodeBody(ImmutableArray delegateFieldNames)
{
if (delegateFieldNames.Length == 0)
{
// return 0;
return
Block(ReturnStatement(
LiteralExpression(
SyntaxKind.NumericLiteralExpression,
Literal(0))));
}
List blockStatements = new(4);
// global::System.HashCode hashCode = default;
blockStatements.Add(LocalDeclarationStatement(
VariableDeclaration(IdentifierName("global::System.HashCode"))
.AddVariables(
VariableDeclarator(Identifier("hashCode"))
.WithInitializer(EqualsValueClause(
LiteralExpression(
SyntaxKind.DefaultLiteralExpression,
Token(SyntaxKind.DefaultKeyword)))))));
foreach (string fieldName in delegateFieldNames)
{
// hashCode.Add(delegateField.Method);
blockStatements.Add(ExpressionStatement(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("hashCode"),
IdentifierName("Add")))
.AddArgumentListArguments(Argument(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName(fieldName),
IdentifierName("Method"))))));
}
// return hashCode.ToHashCode();
blockStatements.Add(ReturnStatement(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("hashCode"),
IdentifierName("ToHashCode")))));
return Block(blockStatements);
}
}
}