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.Helpers.SyntaxFactoryHelper;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
#pragma warning disable CS0618, RS1024
namespace ComputeSharp.SourceGenerators;
///
/// A source generator for processing static methods referenced from compute shaders.
///
[Generator(LanguageNames.CSharp)]
public sealed partial class ShaderMethodSourceGenerator : IIncrementalGenerator
{
///
public void Initialize(IncrementalGeneratorInitializationContext context)
{
// 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))!;
// Get the source info for each method
IncrementalValuesProvider> methodSourceInfoWithErrors =
structDeclarations
.Combine(context.CompilationProvider)
.Select(static (item, token) =>
{
HlslMethodSourceInfo sourceInfo = Execute.GetData(
item.Right,
item.Left.Syntax,
item.Left.Symbol,
out ImmutableArray diagnostics);
return new Result(sourceInfo, diagnostics);
});
// Output the diagnostics
context.ReportDiagnostics(methodSourceInfoWithErrors.Select(static (item, token) => item.Errors));
// Get the filtered sequence to enable caching
IncrementalValuesProvider 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));
});
}
///
/// A helper with all logic to generate the attribute declarations.
///
private static class Execute
{
///
/// Processes a given target method.
///
/// The input object currently in use.
/// The node to process.
/// The instance for the current method.
/// The resulting diagnostics from the processing operation.
public static HlslMethodSourceInfo GetData(
Compilation compilation,
MethodDeclarationSyntax methodDeclaration,
IMethodSymbol methodSymbol,
out ImmutableArray diagnostics)
{
// We need to sets to track all discovered custom types and static methods
HashSet discoveredTypes = new(SymbolEqualityComparer.Default);
Dictionary 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);
}
///
/// Gets a sequence of processed methods from a target method declaration.
///
/// The instance for the current method.
/// The instance for the method to process.
/// The collection of currently discovered types.
/// The collection of discovered constant definitions.
/// The resulting diagnostics from the processing operation.
/// A sequence of processed methods in (main method and all captured methods).
[Pure]
private static (string TargetMethod, ImmutableArray<(string Signature, string Definition)> DependentMethods) GetProcessedMethods(
MethodDeclarationSyntax methodDeclaration,
SemanticModelProvider semanticModel,
ICollection discoveredTypes,
IDictionary constantDefinitions,
out ImmutableArray diagnostics)
{
Dictionary staticMethods = new(SymbolEqualityComparer.Default);
ImmutableArray.Builder builder = ImmutableArray.CreateBuilder();
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());
}
///
/// Creates a instance with the processed attribute.
///
/// The input instance to use.
public static CompilationUnitSyntax GetSyntax(HlslMethodSourceInfo methodSourceInfo)
{
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");
}
}
}