Add incremental generation for GetDispatchId

このコミットが含まれているのは:
Sergio Pedri committed 2021-12-08 11:17:03 +01:00
1 親 86488b4563
コミット fd820a67c7
3ファイル変更
+354

検索条件に一致するファイルはありません

@@ -0,0 +1,113 @@
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.Contracts;
using System.Linq;
using ComputeSharp.__Internals;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
#pragma warning disable CS0618
namespace ComputeSharp.SourceGenerators;
/// <inheritdoc/>
public sealed partial class IShaderGenerator
{
/// <summary>
/// Extracts the names of all instance fields of a <see cref="System.Delegate"/> type.
/// </summary>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
/// <returns>The names of all <see cref="System.Delegate"/> instance fields within <paramref name="structDeclarationSymbol"/>.</returns>
[Pure]
private static ImmutableArray<string> GetDelegateFieldNames(INamedTypeSymbol structDeclarationSymbol)
{
return
structDeclarationSymbol
.GetMembers()
.OfType<IFieldSymbol>()
.Where(static member => member.Type is INamedTypeSymbol { TypeKind: TypeKind.Delegate, IsStatic: false })
.Select(static member => member.Name)
.ToImmutableArray();
}
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>GetDispatchId</c> method.
/// </summary>
///<param name="delegateFieldNames">The names of all <see cref="System.Delegate"/> instance fields within the current shader type.</param>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>GetDispatchId</c> method.</returns>
private static MethodDeclarationSyntax CreateGetDispatchIdMethod(ImmutableArray<string> delegateFieldNames)
{
// This code produces a method declaration as follows:
//
// readonly int global::ComputeSharp.__Internals.IShader.GetDispatchId()
// {
// <BODY>
// }
return
MethodDeclaration(
PredefinedType(Token(SyntaxKind.IntKeyword)),
Identifier("GetDispatchId"))
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}")))
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
.WithBody(GetShaderHashCodeBody(delegateFieldNames));
}
/// <summary>
/// Gets a <see cref="BlockSyntax"/> instance with the logic to compute the hashcode of a given shader type.
/// </summary>
/// <param name="delegateFieldNames">The names of all <see cref="System.Delegate"/> instance fields within the current shader type.</param>
/// <returns>The <see cref="BlockSyntax"/> instance to hash the input shader.</returns>
[Pure]
private static BlockSyntax GetShaderHashCodeBody(ImmutableArray<string> delegateFieldNames)
{
if (delegateFieldNames.Length == 0)
{
// return 0;
return
Block(ReturnStatement(
LiteralExpression(
SyntaxKind.NumericLiteralExpression,
Literal(0))));
}
List<StatementSyntax> 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);
}
}
+182
ファイルの表示
@@ -0,0 +1,182 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using ComputeSharp.SourceGenerators.Models;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace ComputeSharp.SourceGenerators;
/// <inheritdoc/>
public sealed partial class IShaderGenerator : IIncrementalGenerator
{
/// <inheritdoc/>
public void Initialize(IncrementalGeneratorInitializationContext context)
{
// Check whether [SkipLocalsInit] can be used
IncrementalValueProvider<bool> canUseSkipLocalsInit =
context.CompilationProvider
.Select(static (compilation, token) =>
compilation.Options is CSharpCompilationOptions { AllowUnsafe: true } &&
compilation.GetTypeByMetadataName("System.Runtime.CompilerServices.SkipLocalsInit") is not null);
// Get all declared struct types and their type symbols
IncrementalValuesProvider<(StructDeclarationSyntax Syntax, INamedTypeSymbol Symbol)> structDeclarations =
context.SyntaxProvider.CreateSyntaxProvider(
static (node, token) => node is StructDeclarationSyntax structDeclaration,
static (context, token) => (
(StructDeclarationSyntax)context.Node,
Symbol: (INamedTypeSymbol?)context.SemanticModel.GetDeclaredSymbol(context.Node, token)))
.Where(static pair => pair.Symbol is not null)!;
// Get the symbol for the IComputeShader interface
IncrementalValueProvider<INamedTypeSymbol> iComputeShaderSymbol =
context.CompilationProvider
.Select(static (compilation, token) => compilation.GetTypeByMetadataName(typeof(IComputeShader).FullName))!;
// Get the symbol for the IPixelShader<TPixel> interface
IncrementalValueProvider<INamedTypeSymbol> iPixelShaderSymbol =
context.CompilationProvider
.Select(static (compilation, token) => compilation.GetTypeByMetadataName(typeof(IPixelShader<>).FullName))!;
// Filter struct declarations that implement a shader interface, and also gather the shader type
IncrementalValuesProvider<(StructDeclarationSyntax Syntax, INamedTypeSymbol Symbol, Type Type)> shaderDeclarations =
structDeclarations
.Combine(iComputeShaderSymbol.Combine(iPixelShaderSymbol))
.Select(static (item, token) => (item.Left, Type: GetShaderType(item.Left.Symbol, item.Right.Left, item.Right.Right)))
.Where(static item => item.Type is not null)
.Select(static (item, token) => (item.Left.Syntax, item.Left.Symbol, item.Type!));
// Get the hierarchy info and delegate field names for each shader type
IncrementalValuesProvider<(HierarchyInfo Hierarchy, ImmutableArray<string> Delegates)> hierarchyInfoAndShaderFieldNames =
shaderDeclarations
.Select(static (item, token) => (HierarchyInfo.From(item.Symbol), GetDelegateFieldNames(item.Symbol)));
// Generate the GetDispatchId() methods
context.RegisterSourceOutput(hierarchyInfoAndShaderFieldNames.Combine(canUseSkipLocalsInit), static (context, item) =>
{
MethodDeclarationSyntax getDispatchIdMethod = CreateGetDispatchIdMethod(item.Left.Delegates);
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, getDispatchIdMethod, item.Right);
context.AddSource($"{item.Left.Hierarchy.FilenameHint}.GetDispatchId", SourceText.From(compilationUnit.ToFullString(), Encoding.UTF8));
});
}
/// <summary>
/// Gets the shader type for a given shader, if any.
/// </summary>
/// <param name="typeSymbol">The input <see cref="INamedTypeSymbol"/> instance to check.</param>
/// <param name="iComputeShaderSymbol">The <see cref="INamedTypeSymbol"/> instance for <see cref="IComputeShader"/>.</param>
/// <param name="iPixelShaderSymbol">The <see cref="INamedTypeSymbol"/> instance for <see cref="IPixelShader{TPixel}"/>.</param>
/// <returns>Either <see cref="IComputeShader"/> or <see cref="IPixelShader{TPixel}"/>, or <see langword="null"/>.</returns>
[Pure]
private static Type? GetShaderType(
INamedTypeSymbol typeSymbol,
INamedTypeSymbol iComputeShaderSymbol,
INamedTypeSymbol iPixelShaderSymbol)
{
foreach (INamedTypeSymbol interfaceSymbol in typeSymbol.Interfaces)
{
if (interfaceSymbol.Name == nameof(IComputeShader) &&
SymbolEqualityComparer.Default.Equals(interfaceSymbol, iComputeShaderSymbol))
{
return typeof(IComputeShader);
}
if (interfaceSymbol.IsGenericType &&
interfaceSymbol.Name == nameof(IPixelShader<byte>) &&
SymbolEqualityComparer.Default.Equals(interfaceSymbol, interfaceSymbol.ConstructUnboundGenericType()))
{
return typeof(IPixelShader<>);
}
}
return null;
}
/// <summary>
/// Creates a <see cref="CompilationUnitSyntax"/> instance wrapping the given method.
/// </summary>
/// <param name="hierarchyInfo">The <see cref="HierarchyInfo"/> instance for the current type.</param>
/// <param name="methodDeclaration">The <see cref="MethodDeclarationSyntax"/> item to insert.</param>
/// <param name="canUseSkipLocalsInit">Whether <c>[SkipLocalsInit]</c> can be used.</param>
/// <returns>A <see cref="CompilationUnitSyntax"/> object wrapping <paramref name="methodDeclaration"/>.</returns>
[Pure]
private static CompilationUnitSyntax GetCompilationUnitFromMethod(
HierarchyInfo hierarchyInfo,
MethodDeclarationSyntax methodDeclaration,
bool canUseSkipLocalsInit)
{
// Method attributes
List<AttributeListSyntax> attributes = new()
{
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("global::System.CodeDom.Compiler.GeneratedCode")).AddArgumentListArguments(
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IShaderGenerator).FullName))),
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IShaderGenerator).Assembly.GetName().Version.ToString())))))),
AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.DebuggerNonUserCode")))),
AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage")))),
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("global::System.ComponentModel.EditorBrowsable")).AddArgumentListArguments(
AttributeArgument(ParseExpression("global::System.ComponentModel.EditorBrowsableState.Never"))))),
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("global::System.Obsolete")).AddArgumentListArguments(
AttributeArgument(LiteralExpression(
SyntaxKind.StringLiteralExpression,
Literal("This method is not intended to be used directly by user code"))))))
};
// Add [SkipLocalsInit] if the target project allows it
if (canUseSkipLocalsInit)
{
attributes.Add(AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Runtime.CompilerServices.SkipLocalsInit")))));
}
// Create the partial shader type declaration with the given method implementation.
// This code produces a struct declaration as follows:
//
// partial struct <SHADER_TYPE>
// {
// <METHOD>
// }
StructDeclarationSyntax structDeclarationSyntax =
StructDeclaration(hierarchyInfo.Names[0])
.AddModifiers(Token(SyntaxKind.PartialKeyword))
.AddMembers(methodDeclaration.AddAttributeLists(attributes.ToArray()));
TypeDeclarationSyntax typeDeclarationSyntax = structDeclarationSyntax;
// Add all parent types in ascending order, if any
foreach (string parentType in hierarchyInfo.Names.AsSpan().Slice(1))
{
typeDeclarationSyntax =
ClassDeclaration(parentType)
.AddModifiers(Token(SyntaxKind.PartialKeyword))
.AddMembers(typeDeclarationSyntax);
}
// Create a static method to create the combined hashcode for a given shader type.
// This code takes a block syntax and produces a compilation unit as follows:
//
// #pragma warning disable
//
// namespace <NAMESPACE>;
//
// <TYPE_HIERARCHY>
return
CompilationUnit().AddMembers(
FileScopedNamespaceDeclaration(IdentifierName(hierarchyInfo.Namespace))
.AddMembers(typeDeclarationSyntax)
.WithNamespaceKeyword(Token(TriviaList(
Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))),
SyntaxKind.NamespaceKeyword,
TriviaList())))
.NormalizeWhitespace(eol: "\n");
}
}
+59
ファイルの表示
@@ -0,0 +1,59 @@
using System;
using System.Collections.Immutable;
using System.Diagnostics.Contracts;
using ComputeSharp.SourceGenerators.Extensions;
using Microsoft.CodeAnalysis;
using static Microsoft.CodeAnalysis.SymbolDisplayTypeQualificationStyle;
namespace ComputeSharp.SourceGenerators.Models;
/// <summary>
/// A model describing the hierarchy info for a specific type.
/// </summary>
/// <param name="FilenameHint">The filename hint for the current type.</param>
/// <param name="Namespace">Gets the namespace for the current type.</param>
/// <param name="Names">Gets the sequence of type definitions containing the current type.</param>
internal sealed record HierarchyInfo(string FilenameHint, string Namespace, ImmutableArray<string> Names)
{
/// <summary>
/// Creates a new <see cref="HierarchyInfo"/> instance from a given <see cref="INamedTypeSymbol"/>.
/// </summary>
/// <param name="typeSymbol">The input <see cref="INamedTypeSymbol"/> instance to gather info for.</param>
/// <returns>A <see cref="HierarchyInfo"/> instance describing <paramref name="typeSymbol"/>.</returns>
[Pure]
public static HierarchyInfo From(INamedTypeSymbol typeSymbol)
{
ImmutableArray<string>.Builder names = ImmutableArray.CreateBuilder<string>();
for (INamedTypeSymbol? parent = typeSymbol;
parent is not null;
parent = parent.ContainingType)
{
names.Add(parent.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
}
return new(
typeSymbol.GetGeneratedFileName(),
typeSymbol.ContainingNamespace.ToDisplayString(new(typeQualificationStyle: NameAndContainingTypesAndNamespaces)),
names.ToImmutable());
}
/// <inheritdoc/>
[Pure]
public bool Equals(HierarchyInfo? other)
{
return
other is not null &&
(ReferenceEquals(this, other) ||
(Namespace == other.Namespace &&
(Names == other.Names ||
Names.AsSpan().SequenceEqual(other.Names.AsSpan()))));
}
/// <inheritdoc/>
[Pure]
public override int GetHashCode()
{
return HashCode.Combine(Namespace, Names, Names[0]);
}
}