using System; using System.Collections.Immutable; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Text.RegularExpressions; using System.Threading; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Models; using ComputeSharp.SourceGenerators.Dxc; using ComputeSharp.SourceGenerators.Models; using Microsoft.CodeAnalysis; using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; namespace ComputeSharp.SourceGenerators; /// partial class ComputeShaderDescriptorGenerator { /// /// A helper with all logic to generate the HlslBytecode property. /// private static partial class HlslBytecode { /// /// The shared cache of values. /// private static readonly DynamicCache HlslBytecodeCache = new(); /// /// Gets the instance for the input shader info. /// /// The instance for the shader to compile. /// The used to cancel the operation, if needed. /// The instance for the current shader. public static unsafe HlslBytecodeInfo GetBytecode(ref HlslBytecodeInfoKey key, CancellationToken token) { static unsafe HlslBytecodeInfo GetInfo(HlslBytecodeInfoKey key, CancellationToken token) { // Skip even attempting to compile if compilation is disabled (see comments in D2D1 generator) if (!key.IsCompilationEnabled) { return HlslBytecodeInfo.Missing.Instance; } try { token.ThrowIfCancellationRequested(); // Try to load dxcompiler.dll and dxil.dll DxcLibraryLoader.LoadNativeDxcLibraries(); token.ThrowIfCancellationRequested(); // Compile the shader bytecode byte[] bytecode = DxcShaderCompiler.Instance.Compile(key.HlslSource.AsSpan(), key.CompileOptions, token); token.ThrowIfCancellationRequested(); return new HlslBytecodeInfo.Success(Unsafe.As>(ref bytecode)); } catch (Win32Exception e) { return new HlslBytecodeInfo.Win32Error(e.NativeErrorCode, FixupExceptionMessage(e.Message)); } catch (DxcCompilationException e) { return new HlslBytecodeInfo.CompilerError(FixupExceptionMessage(e.Message)); } } return HlslBytecodeCache.GetOrCreate(ref key, GetInfo, token); } /// /// Extracts the compile options for the current shader. /// /// The collection of produced instances. /// The input instance to process. /// The requested compile options to use to compile the shader, if present. public static CompileOptions GetCompileOptions(ImmutableArrayBuilder diagnostics, INamedTypeSymbol structDeclarationSymbol) { // If a [CompileOptions] annotation is present, return the explicit options if (structDeclarationSymbol.TryGetAttributeWithFullyQualifiedMetadataName("ComputeSharp.CompileOptionsAttribute", out AttributeData? attributeData) || structDeclarationSymbol.ContainingAssembly.TryGetAttributeWithFullyQualifiedMetadataName("ComputeSharp.CompileOptionsAttribute", out attributeData)) { return (CompileOptions)attributeData.ConstructorArguments[0].Value!; } return CompileOptions.Default; } /// /// Gets any diagnostics from a processed instance. /// /// The input instance to process. /// The source instance. /// The collection of produced instances. public static void GetInfoDiagnostics( INamedTypeSymbol structDeclarationSymbol, HlslBytecodeInfo info, ImmutableArrayBuilder diagnostics) { DiagnosticInfo? diagnostic = null; if (info is HlslBytecodeInfo.Win32Error win32Error) { diagnostic = DiagnosticInfo.Create( HlslBytecodeFailedWithWin32Exception, structDeclarationSymbol, [structDeclarationSymbol, win32Error.HResult, win32Error.Message]); } else if (info is HlslBytecodeInfo.CompilerError dxcError) { diagnostic = DiagnosticInfo.Create( HlslBytecodeFailedWithDxcCompilationException, structDeclarationSymbol, [structDeclarationSymbol, dxcError.Message]); } if (diagnostic is not null) { diagnostics.Add(diagnostic); } } /// /// Fixes up an exception message to improve the way it's displayed in VS. /// /// The input exception message. /// The updated exception message. private static string FixupExceptionMessage(string message) { // Add square brackets around error headers message = Regex.Replace(message, @"^(error|warning):", static m => $"[{m.Groups[1].Value}]:", RegexOptions.Multiline); // Remove lines with notes message = Regex.Replace(message, @"^note:.+", string.Empty, RegexOptions.Multiline); // Remove syntax error indicators message = Regex.Replace(message, @"^ +\^", string.Empty, RegexOptions.Multiline); return message.NormalizeToSingleLine(); } } }