Added initial ShaderMethodSourceGenerator type
このコミットが含まれているのは:
1 親
85967771cf
コミット
dea3a477ef
3ファイル変更
+143
-2
検索条件に一致するファイルはありません
@@ -1,4 +1,5 @@
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Microsoft.CodeAnalysis;
|
||||
|
||||
@@ -48,10 +49,18 @@ namespace ComputeSharp.SourceGenerators.Extensions
|
||||
/// Gets the full metadata name for a given <see cref="IMethodSymbol"/> instance.
|
||||
/// </summary>
|
||||
/// <param name="symbol">The input <see cref="IMethodSymbol"/> instance.</param>
|
||||
/// <param name="includeParameters">Whether or not to also include parameter types.</param>
|
||||
/// <returns>The full metadata name for <paramref name="symbol"/>.</returns>
|
||||
[Pure]
|
||||
public static string GetFullMetadataName(this IMethodSymbol symbol)
|
||||
public static string GetFullMetadataName(this IMethodSymbol symbol, bool includeParameters = false)
|
||||
{
|
||||
if (includeParameters)
|
||||
{
|
||||
var parameters = $"{string.Join(", ", symbol.Parameters.Select(static p => ((INamedTypeSymbol)p.Type).GetFullMetadataName()))}";
|
||||
|
||||
return $"{symbol.ToDisplayString(FullyQualifiedWithoutGlobalAndParametersFormat)}({parameters})";
|
||||
}
|
||||
|
||||
return symbol.ToDisplayString(FullyQualifiedWithoutGlobalAndParametersFormat);
|
||||
}
|
||||
|
||||
@@ -70,5 +79,21 @@ namespace ComputeSharp.SourceGenerators.Extensions
|
||||
|
||||
return $"[{nameof(ComputeSharp)}]_[{typeof(TGenerator).Name}]_[{fixedName}]";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a valid filename for a target symbol and generator type.
|
||||
/// </summary>
|
||||
/// <typeparam name="TGenerator">The generator type processing the input symbol.</typeparam>
|
||||
/// <param name="symbol">The symbol being processed.</param>
|
||||
/// <returns>A filename in the form "[ComputeSharp]_[<TGENERATOR>]_[<SYMBOL_FULLNAME>]"</returns>
|
||||
[Pure]
|
||||
public static string GetGeneratedFileName<TGenerator>(this IMethodSymbol symbol)
|
||||
{
|
||||
string
|
||||
metadataName = symbol.GetFullMetadataName(true),
|
||||
fixedName = metadataName.Replace('`', '-').Replace('+', '.');
|
||||
|
||||
return $"[{nameof(ComputeSharp)}]_[{typeof(TGenerator).Name}]_[{fixedName}]";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -192,7 +192,7 @@ namespace ComputeSharp.SourceGenerators
|
||||
/// </summary>
|
||||
/// <param name="types">The sequence of discovered custom types.</param>
|
||||
/// <returns>A sequence of custom type definitions to add to the shader source.</returns>
|
||||
public static IEnumerable<string> GetProcessedTypes(IEnumerable<INamedTypeSymbol> types)
|
||||
internal static IEnumerable<string> GetProcessedTypes(IEnumerable<INamedTypeSymbol> types)
|
||||
{
|
||||
foreach (var type in HlslKnownTypes.GetCustomTypes(types))
|
||||
{
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.Diagnostics;
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using ComputeSharp.SourceGenerators.Extensions;
|
||||
using ComputeSharp.SourceGenerators.Mappings;
|
||||
using ComputeSharp.SourceGenerators.SyntaxRewriters;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
using Microsoft.CodeAnalysis.Text;
|
||||
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
|
||||
|
||||
#pragma warning disable CS0618
|
||||
|
||||
namespace ComputeSharp.SourceGenerators
|
||||
{
|
||||
[Generator]
|
||||
public class ShaderMethodSourceGenerator : ISourceGenerator
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public void Initialize(GeneratorInitializationContext context)
|
||||
{
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void Execute(GeneratorExecutionContext context)
|
||||
{
|
||||
Debugger.Launch();
|
||||
|
||||
// Find all the [ShaderMethod] usages and retrieve the target methods
|
||||
ImmutableArray<MethodDeclarationSyntax> methods = (
|
||||
from tree in context.Compilation.SyntaxTrees
|
||||
from attribute in tree.GetRoot().DescendantNodes().OfType<AttributeSyntax>()
|
||||
let symbol = context.Compilation.GetSemanticModel(attribute.SyntaxTree)
|
||||
let typeInfo = symbol.GetTypeInfo(attribute)
|
||||
where typeInfo.Type is { Name: nameof(ShaderMethodAttribute) }
|
||||
select attribute.FirstAncestorOrSelf<MethodDeclarationSyntax>()).ToImmutableArray();
|
||||
|
||||
foreach (MethodDeclarationSyntax methodDeclaration in methods)
|
||||
{
|
||||
SemanticModel semanticModel = context.Compilation.GetSemanticModel(methodDeclaration.SyntaxTree);
|
||||
IMethodSymbol methodDeclarationSymbol = semanticModel.GetDeclaredSymbol(methodDeclaration)!;
|
||||
|
||||
// We need to sets to track all discovered custom types and static methods
|
||||
HashSet<INamedTypeSymbol> discoveredTypes = new(SymbolEqualityComparer.Default);
|
||||
Dictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods = new(SymbolEqualityComparer.Default);
|
||||
|
||||
// Explore the syntax tree and extract the processed info
|
||||
var processedMethods = GetProcessedMethods(methodDeclaration, semanticModel, discoveredTypes, staticMethods).ToArray();
|
||||
var processedTypes = IComputeShaderSourceGenerator.GetProcessedTypes(discoveredTypes).ToArray();
|
||||
|
||||
// Helper that converts a sequence of strings into an array expression.
|
||||
// That is, this applies the following transformation:
|
||||
// - { "S1", "S2" } => new string[] { "S1", "S2" }
|
||||
static ArrayCreationExpressionSyntax ArrayExpression(IEnumerable<string> values)
|
||||
{
|
||||
return
|
||||
ArrayCreationExpression(
|
||||
ArrayType(PredefinedType(Token(SyntaxKind.StringKeyword)))
|
||||
.AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(OmittedArraySizeExpression()))))
|
||||
.WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression)
|
||||
.AddExpressions(values.Select(static value => LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(value))).ToArray()));
|
||||
}
|
||||
|
||||
// Create the compilation unit with the source attribute
|
||||
var source =
|
||||
CompilationUnit().AddAttributeLists(
|
||||
AttributeList(SingletonSeparatedList(
|
||||
Attribute(IdentifierName(typeof(ShaderMethodSourceAttribute).FullName)).AddArgumentListArguments(
|
||||
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(methodDeclarationSymbol.GetFullMetadataName(true)))),
|
||||
AttributeArgument(ArrayExpression(processedTypes)),
|
||||
AttributeArgument(ArrayExpression(processedMethods)))))
|
||||
.WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList()))
|
||||
.WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword))))
|
||||
.NormalizeWhitespace()
|
||||
.ToFullString();
|
||||
|
||||
// Add the method source attribute
|
||||
context.AddSource(methodDeclarationSymbol.GetGeneratedFileName<ShaderMethodSourceAttribute>(), SourceText.From(source, Encoding.UTF8));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a sequence of processed methods from a target method declaration.
|
||||
/// </summary>
|
||||
/// <param name="methodDeclaration">The <see cref="MethodDeclarationSyntax"/> instance for the current method.</param>
|
||||
/// <param name="semanticModel">The <see cref="SemanticModel"/> instance for the method to process.</param>
|
||||
/// <param name="discoveredTypes">The collection of currently discovered types.</param>
|
||||
/// <param name="staticMethods">The set of discovered and processed static methods.</param>
|
||||
/// <returns>A sequence of processed methods in <paramref name="methodDeclaration"/>.</returns>
|
||||
[Pure]
|
||||
private static IEnumerable<string> GetProcessedMethods(
|
||||
MethodDeclarationSyntax methodDeclaration,
|
||||
SemanticModel semanticModel,
|
||||
ICollection<INamedTypeSymbol> discoveredTypes,
|
||||
IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods)
|
||||
{
|
||||
ShaderSourceRewriter shaderSourceRewriter = new(semanticModel, discoveredTypes, staticMethods);
|
||||
|
||||
// Rewrite the method syntax tree
|
||||
var processedMethod = shaderSourceRewriter.Visit(methodDeclaration)!.WithoutTrivia();
|
||||
|
||||
yield return processedMethod.NormalizeWhitespace().ToFullString();
|
||||
|
||||
// Emit the extracted local functions
|
||||
foreach (var localFunction in shaderSourceRewriter.LocalFunctions)
|
||||
{
|
||||
yield return localFunction.Value.NormalizeWhitespace().ToFullString();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
新しいイシューから参照
ユーザーをブロックする