using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.Contracts;
using System.Text;
using ComputeSharp.__Internals;
using ComputeSharp.SourceGenerators.Diagnostics;
using ComputeSharp.SourceGenerators.Extensions;
using ComputeSharp.SourceGenerators.Helpers;
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;
#pragma warning disable CS0618, RS1024
namespace ComputeSharp.SourceGenerators;
///
/// A source generator for processing static methods referenced from compute shaders.
///
[Generator]
public sealed partial class ShaderMethodSourceGenerator : ISourceGenerator
{
///
public void Initialize(GeneratorInitializationContext context)
{
context.RegisterForSyntaxNotifications(static () => new SyntaxReceiver());
}
///
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
{
OnExecute(context, item.MethodDeclaration, semanticModel, item.MethodSymbol);
}
catch
{
context.ReportDiagnostic(ShaderMethodSourceGeneratorError, item.MethodDeclaration, item.MethodSymbol);
}
}
}
///
/// Processes a given target method.
///
/// The input instance to use.
/// The node to process.
/// The with metadata on the types being processed.
/// The for .
private static void OnExecute(GeneratorExecutionContext context, MethodDeclarationSyntax methodDeclaration, SemanticModelProvider semanticModel, IMethodSymbol methodDeclarationSymbol)
{
// 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 (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));
}
///
/// Gets a sequence of processed methods from a target method declaration.
///
/// The current generator context in use.
/// 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.
/// A sequence of processed methods in (main method and all captured methods).
[Pure]
private static (string TargetMethod, IEnumerable<(string Signature, string Definition)> ProcessedMethods) GetProcessedMethods(
GeneratorExecutionContext context,
MethodDeclarationSyntax methodDeclaration,
SemanticModelProvider semanticModel,
ICollection discoveredTypes,
IDictionary constantDefinitions)
{
Dictionary staticMethods = new(SymbolEqualityComparer.Default);
ImmutableArray.Builder diagnostics = ImmutableArray.CreateBuilder();
ShaderSourceRewriter shaderSourceRewriter = new(semanticModel, discoveredTypes, staticMethods, constantDefinitions, diagnostics);
foreach (Diagnostic diagnostic in diagnostics.ToImmutable())
{
context.ReportDiagnostic(diagnostic);
}
// 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)
{
processedMethods.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)
{
processedMethods.Add((
staticMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(),
staticMethod.NormalizeWhitespace(eol: "\n").ToFullString()));
}
return (targetMethod, processedMethods);
}
}