Switch [ShaderMethod] generator to incremental
このコミットが含まれているのは:
1 親
6269267bf0
コミット
d1fabb6fed
7ファイル変更
+236
-173
検索条件に一致するファイルはありません
+4
-4
@@ -20,9 +20,9 @@ public sealed partial class IShaderGenerator
|
||||
/// <summary>
|
||||
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>BuildHlslString</c> method.
|
||||
/// </summary>
|
||||
/// <param name="hlslSourceInfo">The input <see cref="HlslSourceInfo"/> instance to use.</param>
|
||||
/// <param name="hlslSourceInfo">The input <see cref="HlslShaderSourceInfo"/> instance to use.</param>
|
||||
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>BuildHlslString</c> method.</returns>
|
||||
public static MethodDeclarationSyntax GetSyntax(HlslSourceInfo hlslSourceInfo)
|
||||
public static MethodDeclarationSyntax GetSyntax(HlslShaderSourceInfo hlslSourceInfo)
|
||||
{
|
||||
ImmutableArray<StatementSyntax> bodyStatements = GenerateRenderMethodBody(hlslSourceInfo);
|
||||
|
||||
@@ -49,9 +49,9 @@ public sealed partial class IShaderGenerator
|
||||
/// <summary>
|
||||
/// Produces the series of statements to build the current HLSL source.
|
||||
/// </summary>
|
||||
/// <param name="hlslSourceInfo">The input <see cref="HlslSourceInfo"/> instance to use.</param>
|
||||
/// <param name="hlslSourceInfo">The input <see cref="HlslShaderSourceInfo"/> instance to use.</param>
|
||||
/// <returns>The series of statements to build the HLSL source to compile to execute the current shader.</returns>
|
||||
private static ImmutableArray<StatementSyntax> GenerateRenderMethodBody(HlslSourceInfo hlslSourceInfo)
|
||||
private static ImmutableArray<StatementSyntax> GenerateRenderMethodBody(HlslShaderSourceInfo hlslSourceInfo)
|
||||
{
|
||||
ImmutableArray<StatementSyntax>.Builder statements = ImmutableArray.CreateBuilder<StatementSyntax>();
|
||||
StringBuilder textBuilder = new();
|
||||
|
||||
@@ -36,7 +36,7 @@ public sealed partial class IShaderGenerator
|
||||
/// <param name="structDeclarationSymbol">The <see cref="INamedTypeSymbol"/> for <paramref name="structDeclaration"/>.</param>
|
||||
/// <param name="diagnostics">The resulting diagnostics from the processing operation.</param>
|
||||
/// <returns>The resulting info on the processed shader.</returns>
|
||||
public static HlslSourceInfo GetInfo(
|
||||
public static HlslShaderSourceInfo GetInfo(
|
||||
Compilation compilation,
|
||||
StructDeclarationSyntax structDeclaration,
|
||||
INamedTypeSymbol structDeclarationSymbol,
|
||||
@@ -508,7 +508,7 @@ public sealed partial class IShaderGenerator
|
||||
/// <param name="isSamplerUsed">Whether the static sampler is used by the shader.</param>
|
||||
/// <param name="executeMethod">The body of the entry point of the shader.</param>
|
||||
/// <returns>The series of statements to build the HLSL source to compile to execute the current shader.</returns>
|
||||
private static HlslSourceInfo GetHlslSourceInfo(
|
||||
private static HlslShaderSourceInfo GetHlslSourceInfo(
|
||||
ImmutableArray<(string Name, string Value)> definedConstants,
|
||||
ImmutableArray<(string Name, string Definition)> declaredTypes,
|
||||
ImmutableArray<(string MetadataName, string Name, string HlslType)> resourceFields,
|
||||
@@ -731,9 +731,9 @@ public sealed partial class IShaderGenerator
|
||||
/// <summary>
|
||||
/// Produces the non dynamic HLSL source (concatenating all generated HLSL source chunks).
|
||||
/// </summary>
|
||||
/// <param name="hlslSourceInfo">The input <see cref="HlslSourceInfo"/> instance to use.</param>
|
||||
/// <param name="hlslSourceInfo">The input <see cref="HlslShaderSourceInfo"/> instance to use.</param>
|
||||
/// <returns>The non dynamic HLSL source code.</returns>
|
||||
public static string GetNonDynamicHlslSource(HlslSourceInfo hlslSourceInfo)
|
||||
public static string GetNonDynamicHlslSource(HlslShaderSourceInfo hlslSourceInfo)
|
||||
{
|
||||
return
|
||||
hlslSourceInfo.HeaderAndThreadsX + "<THREADSX>" +
|
||||
|
||||
@@ -71,7 +71,7 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator
|
||||
|
||||
// Get the dispatch data, HLSL source and embedded bytecode info. This info is computed on the
|
||||
// same step as parts are shared in following sub-branches in the incremental generator pipeline.
|
||||
IncrementalValuesProvider<(Result<DispatchDataInfo> Dispatch, Result<HlslSourceInfo> Hlsl, Result<ThreadIdsInfo> ThreadIds)> shaderInfoWithErrors =
|
||||
IncrementalValuesProvider<(Result<DispatchDataInfo> Dispatch, Result<HlslShaderSourceInfo> Hlsl, Result<ThreadIdsInfo> ThreadIds)> shaderInfoWithErrors =
|
||||
shaderDeclarations
|
||||
.Combine(context.CompilationProvider)
|
||||
.Select(static (item, token) =>
|
||||
@@ -93,7 +93,7 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator
|
||||
dispatchDataDiagnostics);
|
||||
|
||||
// BuildHlslString() info
|
||||
HlslSourceInfo hlslSourceInfo = BuildHlslString.GetInfo(
|
||||
HlslShaderSourceInfo hlslSourceInfo = BuildHlslString.GetInfo(
|
||||
item.Right,
|
||||
item.Left.Syntax,
|
||||
item.Left.Symbol,
|
||||
@@ -107,7 +107,7 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator
|
||||
|
||||
return (
|
||||
dispatchDataInfo,
|
||||
new Result<HlslSourceInfo>(hlslSourceInfo, hlslSourceDiagnostics),
|
||||
new Result<HlslShaderSourceInfo>(hlslSourceInfo, hlslSourceDiagnostics),
|
||||
new Result<ThreadIdsInfo>(threadIds, threadIdsDiagnostics));
|
||||
});
|
||||
|
||||
@@ -117,10 +117,10 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator
|
||||
context.ReportDiagnostics(shaderInfoWithErrors.Select(static (item, token) => item.ThreadIds.Errors));
|
||||
|
||||
// Filter all items to enable caching at a coarse level, and remove diagnostics
|
||||
IncrementalValuesProvider<(DispatchDataInfo Dispatch, HlslSourceInfo Hlsl, ThreadIdsInfo ThreadIds)> shaderInfo =
|
||||
IncrementalValuesProvider<(DispatchDataInfo Dispatch, HlslShaderSourceInfo Hlsl, ThreadIdsInfo ThreadIds)> shaderInfo =
|
||||
shaderInfoWithErrors
|
||||
.Select(static (item, token) => (item.Dispatch.Value, item.Hlsl.Value, item.ThreadIds.Value))
|
||||
.WithComparers(DispatchDataInfo.Comparer.Default, HlslSourceInfo.Comparer.Default, ThreadIdsInfo.Comparer.Default);
|
||||
.WithComparers(DispatchDataInfo.Comparer.Default, HlslShaderSourceInfo.Comparer.Default, ThreadIdsInfo.Comparer.Default);
|
||||
|
||||
// Get a filtered sequence to enable caching
|
||||
IncrementalValuesProvider<DispatchDataInfo> dispatchDataInfo =
|
||||
@@ -142,10 +142,10 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator
|
||||
});
|
||||
|
||||
// Get the filtered sequence to enable caching
|
||||
IncrementalValuesProvider<(HierarchyInfo Hierarchy, HlslSourceInfo SourceInfo)> hlslSourceInfo =
|
||||
IncrementalValuesProvider<(HierarchyInfo Hierarchy, HlslShaderSourceInfo SourceInfo)> hlslSourceInfo =
|
||||
shaderInfo
|
||||
.Select(static (item, token) => (item.Dispatch.Hierarchy, item.Hlsl))
|
||||
.WithComparers(HierarchyInfo.Comparer.Default, HlslSourceInfo.Comparer.Default);
|
||||
.WithComparers(HierarchyInfo.Comparer.Default, HlslShaderSourceInfo.Comparer.Default);
|
||||
|
||||
// Generate the BuildHlslString() methods
|
||||
context.RegisterSourceOutput(hlslSourceInfo.Combine(canUseSkipLocalsInit), static (context, item) =>
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using ComputeSharp.SourceGenerators.Extensions;
|
||||
|
||||
namespace ComputeSharp.SourceGenerators.Models;
|
||||
|
||||
/// <summary>
|
||||
/// A model for extracted info on a processed HLSL method.
|
||||
/// </summary>
|
||||
/// <param name="MetadataName">The metadata name for the method.</param>
|
||||
/// <param name="EntryPoint">The meethod entry point.</param>
|
||||
/// <param name="DefinedTypes">The discovered declared types.</param>
|
||||
/// <param name="DefinedConstants">The discovered defined constants.</param>
|
||||
/// <param name="DependentMethods">The dependent captured methods.</param>
|
||||
internal sealed record HlslMethodSourceInfo(
|
||||
string MetadataName,
|
||||
string EntryPoint,
|
||||
ImmutableArray<(string Name, string Definition)> DefinedTypes,
|
||||
ImmutableArray<(string Name, string Value)> DefinedConstants,
|
||||
ImmutableArray<(string Signature, string Definition)> DependentMethods)
|
||||
{
|
||||
/// <summary>
|
||||
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="HlslMethodSourceInfo"/>.
|
||||
/// </summary>
|
||||
public sealed class Comparer : IEqualityComparer<HlslMethodSourceInfo>
|
||||
{
|
||||
/// <summary>
|
||||
/// The singleton <see cref="Comparer"/> instance.
|
||||
/// </summary>
|
||||
public static Comparer Default { get; } = new();
|
||||
|
||||
/// <inheritdoc/>
|
||||
public bool Equals(HlslMethodSourceInfo? x, HlslMethodSourceInfo? y)
|
||||
{
|
||||
if (x is null && y is null)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (x is null || y is null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (ReferenceEquals(x, y))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
return
|
||||
x.MetadataName == y.MetadataName &&
|
||||
x.EntryPoint == y.EntryPoint &&
|
||||
x.DefinedTypes.SequenceEqual(y.DefinedTypes) &&
|
||||
x.DefinedConstants.SequenceEqual(y.DefinedConstants) &&
|
||||
x.DependentMethods.SequenceEqual(y.DependentMethods);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public int GetHashCode(HlslMethodSourceInfo obj)
|
||||
{
|
||||
HashCode hashCode = default;
|
||||
|
||||
hashCode.Add(obj.MetadataName);
|
||||
hashCode.Add(obj.EntryPoint);
|
||||
hashCode.AddRange(obj.DefinedTypes);
|
||||
hashCode.AddRange(obj.DefinedConstants);
|
||||
hashCode.AddRange(obj.DependentMethods);
|
||||
|
||||
return hashCode.ToHashCode();
|
||||
}
|
||||
}
|
||||
}
|
||||
+5
-5
@@ -22,7 +22,7 @@ namespace ComputeSharp.SourceGenerators.Models;
|
||||
/// <param name="DefinedConstants">The names of defined constants.</param>
|
||||
/// <param name="MethodSignatures">The signatures for captured methods.</param>
|
||||
/// <param name="Delegates">The list of delegate fields.</param>
|
||||
internal sealed record HlslSourceInfo(
|
||||
internal sealed record HlslShaderSourceInfo(
|
||||
string HeaderAndThreadsX,
|
||||
string ThreadsY,
|
||||
string ThreadsZ,
|
||||
@@ -39,9 +39,9 @@ internal sealed record HlslSourceInfo(
|
||||
ImmutableArray<string> Delegates)
|
||||
{
|
||||
/// <summary>
|
||||
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="HlslSourceInfo"/>.
|
||||
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="HlslShaderSourceInfo"/>.
|
||||
/// </summary>
|
||||
public sealed class Comparer : IEqualityComparer<HlslSourceInfo>
|
||||
public sealed class Comparer : IEqualityComparer<HlslShaderSourceInfo>
|
||||
{
|
||||
/// <summary>
|
||||
/// The singleton <see cref="Comparer"/> instance.
|
||||
@@ -49,7 +49,7 @@ internal sealed record HlslSourceInfo(
|
||||
public static Comparer Default { get; } = new();
|
||||
|
||||
/// <inheritdoc/>
|
||||
public bool Equals(HlslSourceInfo? x, HlslSourceInfo? y)
|
||||
public bool Equals(HlslShaderSourceInfo? x, HlslShaderSourceInfo? y)
|
||||
{
|
||||
if (x is null && y is null)
|
||||
{
|
||||
@@ -84,7 +84,7 @@ internal sealed record HlslSourceInfo(
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public int GetHashCode(HlslSourceInfo obj)
|
||||
public int GetHashCode(HlslShaderSourceInfo obj)
|
||||
{
|
||||
HashCode hashCode = default;
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
|
||||
namespace ComputeSharp.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public sealed partial class ShaderMethodSourceGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// An <see cref="ISyntaxContextReceiver"/> that selects candidate nodes to process.
|
||||
/// </summary>
|
||||
private sealed class SyntaxReceiver : ISyntaxContextReceiver
|
||||
{
|
||||
/// <summary>
|
||||
/// The list of info gathered during exploration.
|
||||
/// </summary>
|
||||
private readonly List<Item> gatheredInfo = new();
|
||||
|
||||
/// <summary>
|
||||
/// Gets the collection of gathered info to process.
|
||||
/// </summary>
|
||||
public IReadOnlyCollection<Item> GatheredInfo => this.gatheredInfo;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void OnVisitSyntaxNode(GeneratorSyntaxContext context)
|
||||
{
|
||||
if (context.Node is MethodDeclarationSyntax { AttributeLists: { Count: > 0 } } methodDeclaration &&
|
||||
context.SemanticModel.GetDeclaredSymbol(methodDeclaration) is IMethodSymbol methodSymbol &&
|
||||
context.SemanticModel.Compilation.GetTypeByMetadataName(typeof(ShaderMethodAttribute).FullName) is INamedTypeSymbol attributeSymbol &&
|
||||
methodSymbol.GetAttributes().Any(a => SymbolEqualityComparer.Default.Equals(a.AttributeClass, attributeSymbol)))
|
||||
{
|
||||
this.gatheredInfo.Add(new Item(methodDeclaration, methodSymbol));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A model for a group of item representing a discovered method to process.
|
||||
/// </summary>
|
||||
/// <param name="MethodDeclaration">The <see cref="MethodDeclarationSyntax"/> instance for the target method declaration.</param>
|
||||
/// <param name="MethodSymbol">The <see cref="IMethodSymbol"/> instance for <paramref name="MethodDeclaration"/>.</param>
|
||||
public sealed record Item(MethodDeclarationSyntax MethodDeclaration, IMethodSymbol MethodSymbol);
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,18 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using ComputeSharp.__Internals;
|
||||
using ComputeSharp.SourceGenerators.Diagnostics;
|
||||
using ComputeSharp.SourceGenerators.Extensions;
|
||||
using ComputeSharp.SourceGenerators.Helpers;
|
||||
using ComputeSharp.SourceGenerators.Models;
|
||||
using ComputeSharp.SourceGenerators.SyntaxRewriters;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
using Microsoft.CodeAnalysis.Text;
|
||||
using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors;
|
||||
using static ComputeSharp.SourceGenerators.Helpers.SyntaxFactoryHelper;
|
||||
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
|
||||
|
||||
@@ -22,129 +23,164 @@ namespace ComputeSharp.SourceGenerators;
|
||||
/// <summary>
|
||||
/// A source generator for processing static methods referenced from compute shaders.
|
||||
/// </summary>
|
||||
[Generator]
|
||||
public sealed partial class ShaderMethodSourceGenerator : ISourceGenerator
|
||||
[Generator(LanguageNames.CSharp)]
|
||||
public sealed partial class ShaderMethodSourceGenerator : IIncrementalGenerator
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public void Initialize(GeneratorInitializationContext context)
|
||||
public void Initialize(IncrementalGeneratorInitializationContext context)
|
||||
{
|
||||
context.RegisterForSyntaxNotifications(static () => new SyntaxReceiver());
|
||||
}
|
||||
// Get all declared methods with the [ShaderMethod] attribute
|
||||
IncrementalValuesProvider<(MethodDeclarationSyntax Syntax, IMethodSymbol Symbol)> structDeclarations =
|
||||
context.SyntaxProvider
|
||||
.CreateSyntaxProvider(
|
||||
static (node, token) => node is MethodDeclarationSyntax { AttributeLists.Count: > 0 } methodDeclaration,
|
||||
static (context, token) => (
|
||||
Syntax: (MethodDeclarationSyntax)context.Node,
|
||||
Symbol: (IMethodSymbol?)context.SemanticModel.GetDeclaredSymbol(context.Node, token)))
|
||||
.Where(static item => item.Symbol is not null &&
|
||||
item.Symbol.GetAttributes().Any(static a => a.AttributeClass?.ToDisplayString() == typeof(ShaderMethodAttribute).FullName))!;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void Execute(GeneratorExecutionContext context)
|
||||
{
|
||||
// Get the syntax receiver with the candidate nodes
|
||||
if (context.SyntaxContextReceiver is not SyntaxReceiver syntaxReceiver)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (SyntaxReceiver.Item item in syntaxReceiver.GatheredInfo)
|
||||
{
|
||||
SemanticModelProvider semanticModel = new(context.Compilation);
|
||||
|
||||
try
|
||||
// Get the source info for each method
|
||||
IncrementalValuesProvider<Result<HlslMethodSourceInfo>> methodSourceInfoWithErrors =
|
||||
structDeclarations
|
||||
.Combine(context.CompilationProvider)
|
||||
.Select(static (item, token) =>
|
||||
{
|
||||
OnExecute(context, item.MethodDeclaration, semanticModel, item.MethodSymbol);
|
||||
}
|
||||
catch
|
||||
{
|
||||
context.ReportDiagnostic(ShaderMethodSourceGeneratorError, item.MethodDeclaration, item.MethodSymbol);
|
||||
}
|
||||
}
|
||||
HlslMethodSourceInfo sourceInfo = Execute.GetData(
|
||||
item.Right,
|
||||
item.Left.Syntax,
|
||||
item.Left.Symbol,
|
||||
out ImmutableArray<Diagnostic> diagnostics);
|
||||
|
||||
return new Result<HlslMethodSourceInfo>(sourceInfo, diagnostics);
|
||||
});
|
||||
|
||||
// Output the diagnostics
|
||||
context.ReportDiagnostics(methodSourceInfoWithErrors.Select(static (item, token) => item.Errors));
|
||||
|
||||
// Get the filtered sequence to enable caching
|
||||
IncrementalValuesProvider<HlslMethodSourceInfo> methodSourceInfo =
|
||||
methodSourceInfoWithErrors
|
||||
.Select(static (item, token) => item.Value)
|
||||
.WithComparer(HlslMethodSourceInfo.Comparer.Default);
|
||||
|
||||
// Generate the [ShaderMethodSource] attributes
|
||||
context.RegisterSourceOutput(methodSourceInfo, static (context, item) =>
|
||||
{
|
||||
CompilationUnitSyntax compilationUnit = Execute.GetSyntax(item);
|
||||
string filename = item.MetadataName.Replace('`', '-').Replace('+', '.');
|
||||
|
||||
context.AddSource(filename, SourceText.From(compilationUnit.ToFullString(), Encoding.UTF8));
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Processes a given target method.
|
||||
/// A helper with all logic to generate the attribute declarations.
|
||||
/// </summary>
|
||||
/// <param name="context">The input <see cref="GeneratorExecutionContext"/> instance to use.</param>
|
||||
/// <param name="methodDeclaration">The <see cref="MethodDeclarationSyntax"/> node to process.</param>
|
||||
/// <param name="semanticModel">The <see cref="SemanticModelProvider"/> with metadata on the types being processed.</param>
|
||||
/// <param name="methodDeclarationSymbol">The <see cref="IMethodSymbol"/> for <paramref name="methodDeclaration"/>.</param>
|
||||
private static void OnExecute(GeneratorExecutionContext context, MethodDeclarationSyntax methodDeclaration, SemanticModelProvider semanticModel, IMethodSymbol methodDeclarationSymbol)
|
||||
private static class Execute
|
||||
{
|
||||
// We need to sets to track all discovered custom types and static methods
|
||||
HashSet<INamedTypeSymbol> discoveredTypes = new(SymbolEqualityComparer.Default);
|
||||
Dictionary<IFieldSymbol, string> constantDefinitions = new(SymbolEqualityComparer.Default);
|
||||
|
||||
// Explore the syntax tree and extract the processed info
|
||||
var (invokeMethod, processedMethods) = GetProcessedMethods(context, methodDeclaration, semanticModel, discoveredTypes, constantDefinitions);
|
||||
var processedTypes = IShaderGenerator.BuildHlslString.GetDeclaredTypes(discoveredTypes);
|
||||
var processedConstants = IShaderGenerator.BuildHlslString.GetDefinedConstants(constantDefinitions);
|
||||
|
||||
// Create the compilation unit with the source attribute
|
||||
var source =
|
||||
CompilationUnit().AddAttributeLists(
|
||||
AttributeList(SingletonSeparatedList(
|
||||
Attribute(IdentifierName($"global::{typeof(ShaderMethodSourceAttribute).FullName}")).AddArgumentListArguments(
|
||||
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(methodDeclarationSymbol.GetFullMetadataName(true)))),
|
||||
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(invokeMethod))),
|
||||
AttributeArgument(NestedArrayExpression(processedTypes)),
|
||||
AttributeArgument(NestedArrayExpression(processedMethods)),
|
||||
AttributeArgument(NestedArrayExpression(processedConstants)))))
|
||||
.WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList()))
|
||||
.WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword))))
|
||||
.NormalizeWhitespace(eol: "\n")
|
||||
.ToFullString();
|
||||
|
||||
// Add the method source attribute
|
||||
context.AddSource(methodDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a sequence of processed methods from a target method declaration.
|
||||
/// </summary>
|
||||
/// <param name="context">The current generator context in use.</param>
|
||||
/// <param name="methodDeclaration">The <see cref="MethodDeclarationSyntax"/> instance for the current method.</param>
|
||||
/// <param name="semanticModel">The <see cref="SemanticModelProvider"/> instance for the method to process.</param>
|
||||
/// <param name="discoveredTypes">The collection of currently discovered types.</param>
|
||||
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
|
||||
/// <returns>A sequence of processed methods in <paramref name="methodDeclaration"/> (main method and all captured methods).</returns>
|
||||
[Pure]
|
||||
private static (string TargetMethod, IEnumerable<(string Signature, string Definition)> ProcessedMethods) GetProcessedMethods(
|
||||
GeneratorExecutionContext context,
|
||||
MethodDeclarationSyntax methodDeclaration,
|
||||
SemanticModelProvider semanticModel,
|
||||
ICollection<INamedTypeSymbol> discoveredTypes,
|
||||
IDictionary<IFieldSymbol, string> constantDefinitions)
|
||||
{
|
||||
Dictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods = new(SymbolEqualityComparer.Default);
|
||||
ImmutableArray<Diagnostic>.Builder diagnostics = ImmutableArray.CreateBuilder<Diagnostic>();
|
||||
|
||||
ShaderSourceRewriter shaderSourceRewriter = new(semanticModel, discoveredTypes, staticMethods, constantDefinitions, diagnostics);
|
||||
|
||||
foreach (Diagnostic diagnostic in diagnostics.ToImmutable())
|
||||
/// <summary>
|
||||
/// Processes a given target method.
|
||||
/// </summary>
|
||||
/// <param name="compilation">The input <see cref="Compilation"/> object currently in use.</param>
|
||||
/// <param name="methodDeclaration">The <see cref="MethodDeclarationSyntax"/> node to process.</param>
|
||||
/// <param name="methodSymbol">The <see cref="IMethodSymbol"/> instance for the current method.</param>
|
||||
/// <param name="diagnostics">The resulting diagnostics from the processing operation.</param>
|
||||
public static HlslMethodSourceInfo GetData(
|
||||
Compilation compilation,
|
||||
MethodDeclarationSyntax methodDeclaration,
|
||||
IMethodSymbol methodSymbol,
|
||||
out ImmutableArray<Diagnostic> diagnostics)
|
||||
{
|
||||
context.ReportDiagnostic(diagnostic);
|
||||
// We need to sets to track all discovered custom types and static methods
|
||||
HashSet<INamedTypeSymbol> discoveredTypes = new(SymbolEqualityComparer.Default);
|
||||
Dictionary<IFieldSymbol, string> constantDefinitions = new(SymbolEqualityComparer.Default);
|
||||
|
||||
// Explore the syntax tree and extract the processed info
|
||||
var semanticModel = new SemanticModelProvider(compilation);
|
||||
var (entryPoint, dependentMethods) = GetProcessedMethods(methodDeclaration, semanticModel, discoveredTypes, constantDefinitions, out diagnostics);
|
||||
var definedTypes = IShaderGenerator.BuildHlslString.GetDeclaredTypes(discoveredTypes);
|
||||
var definedConstants = IShaderGenerator.BuildHlslString.GetDefinedConstants(constantDefinitions);
|
||||
|
||||
return new(
|
||||
methodSymbol.GetFullMetadataName(includeParameters: true),
|
||||
entryPoint,
|
||||
definedTypes,
|
||||
definedConstants,
|
||||
dependentMethods);
|
||||
}
|
||||
|
||||
// Rewrite the method syntax tree
|
||||
var targetMethod = shaderSourceRewriter
|
||||
.Visit(methodDeclaration)!
|
||||
.WithIdentifier(Identifier(ShaderMethodSourceAttribute.InvokeMethodIdentifier))
|
||||
.WithoutTrivia()
|
||||
.NormalizeWhitespace(eol: "\n")
|
||||
.ToFullString();
|
||||
|
||||
List<(string, string)> processedMethods = new(shaderSourceRewriter.LocalFunctions.Count);
|
||||
|
||||
// Emit the extracted local functions
|
||||
foreach (var localFunction in shaderSourceRewriter.LocalFunctions)
|
||||
/// <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="SemanticModelProvider"/> instance for the method to process.</param>
|
||||
/// <param name="discoveredTypes">The collection of currently discovered types.</param>
|
||||
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
|
||||
/// <param name="diagnostics">The resulting diagnostics from the processing operation.</param>
|
||||
/// <returns>A sequence of processed methods in <paramref name="methodDeclaration"/> (main method and all captured methods).</returns>
|
||||
[Pure]
|
||||
private static (string TargetMethod, ImmutableArray<(string Signature, string Definition)> DependentMethods) GetProcessedMethods(
|
||||
MethodDeclarationSyntax methodDeclaration,
|
||||
SemanticModelProvider semanticModel,
|
||||
ICollection<INamedTypeSymbol> discoveredTypes,
|
||||
IDictionary<IFieldSymbol, string> constantDefinitions,
|
||||
out ImmutableArray<Diagnostic> diagnostics)
|
||||
{
|
||||
processedMethods.Add((
|
||||
localFunction.Value.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(),
|
||||
localFunction.Value.NormalizeWhitespace(eol: "\n").ToFullString()));
|
||||
Dictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods = new(SymbolEqualityComparer.Default);
|
||||
ImmutableArray<Diagnostic>.Builder builder = ImmutableArray.CreateBuilder<Diagnostic>();
|
||||
|
||||
ShaderSourceRewriter shaderSourceRewriter = new(semanticModel, discoveredTypes, staticMethods, constantDefinitions, builder);
|
||||
|
||||
diagnostics = builder.ToImmutable();
|
||||
|
||||
// Rewrite the method syntax tree
|
||||
var targetMethod = shaderSourceRewriter
|
||||
.Visit(methodDeclaration)!
|
||||
.WithIdentifier(Identifier(ShaderMethodSourceAttribute.InvokeMethodIdentifier))
|
||||
.WithoutTrivia()
|
||||
.NormalizeWhitespace(eol: "\n")
|
||||
.ToFullString();
|
||||
|
||||
ImmutableArray<(string, string)>.Builder methods = ImmutableArray.CreateBuilder<(string, string)>(shaderSourceRewriter.LocalFunctions.Count);
|
||||
|
||||
// Emit the extracted local functions
|
||||
foreach (var localFunction in shaderSourceRewriter.LocalFunctions)
|
||||
{
|
||||
methods.Add((
|
||||
localFunction.Value.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(),
|
||||
localFunction.Value.NormalizeWhitespace(eol: "\n").ToFullString()));
|
||||
}
|
||||
|
||||
// Emit the discovered static methods
|
||||
foreach (var staticMethod in staticMethods.Values)
|
||||
{
|
||||
methods.Add((
|
||||
staticMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(),
|
||||
staticMethod.NormalizeWhitespace(eol: "\n").ToFullString()));
|
||||
}
|
||||
|
||||
return (targetMethod, methods.ToImmutable());
|
||||
}
|
||||
|
||||
// Emit the discovered static methods
|
||||
foreach (var staticMethod in staticMethods.Values)
|
||||
/// <summary>
|
||||
/// Creates a <see cref="CompilationUnitSyntax"/> instance with the processed attribute.
|
||||
/// </summary>
|
||||
/// <param name="methodSourceInfo">The input <see cref="HlslMethodSourceInfo"/> instance to use.</param>
|
||||
public static CompilationUnitSyntax GetSyntax(HlslMethodSourceInfo methodSourceInfo)
|
||||
{
|
||||
processedMethods.Add((
|
||||
staticMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(),
|
||||
staticMethod.NormalizeWhitespace(eol: "\n").ToFullString()));
|
||||
return
|
||||
CompilationUnit().AddAttributeLists(
|
||||
AttributeList(SingletonSeparatedList(
|
||||
Attribute(IdentifierName($"global::{typeof(ShaderMethodSourceAttribute).FullName}")).AddArgumentListArguments(
|
||||
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(methodSourceInfo.MetadataName))),
|
||||
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(methodSourceInfo.EntryPoint))),
|
||||
AttributeArgument(NestedArrayExpression(methodSourceInfo.DefinedTypes)),
|
||||
AttributeArgument(NestedArrayExpression(methodSourceInfo.DependentMethods)),
|
||||
AttributeArgument(NestedArrayExpression(methodSourceInfo.DefinedConstants)))))
|
||||
.WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList()))
|
||||
.WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword))))
|
||||
.NormalizeWhitespace(eol: "\n");
|
||||
}
|
||||
|
||||
return (targetMethod, processedMethods);
|
||||
}
|
||||
}
|
||||
新しいイシューから参照
ユーザーをブロックする