From 06b12f5a6cde323359df924a09ca19769f200837 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 30 Aug 2021 17:12:09 +0200 Subject: [PATCH] Switched source generators to global:: type names --- .../AutoConstructorGenerator.cs | 5 +- .../ComputeSharp.SourceGenerators.csproj | 2 +- ...erGenerator.CreateBuildHlslStringMethod.cs | 32 +++++------ ...aderGenerator.CreateGetDispatchIdMethod.cs | 8 +-- ...rGenerator.CreateLoadDispatchDataMethod.cs | 36 ++++++------ ...erator.CreateLoadDispatchMetadataMethod.cs | 34 +++++------ .../IShaderGenerator.cs | 57 +++++-------------- .../ShaderMethodSourceGenerator.cs | 2 +- ...ComputeSharp.Tests.SourceGenerators.csproj | 8 +-- 9 files changed, 75 insertions(+), 109 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.cs b/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.cs index a0456aed..1aac7f97 100644 --- a/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.cs @@ -62,7 +62,7 @@ public sealed partial class AutoConstructorGenerator : ISourceGenerator var fields = ( from fieldSymbol in structDeclarationSymbol.GetMembers().OfType() where !fieldSymbol.IsConst && !fieldSymbol.IsStatic && !fieldSymbol.IsFixedSizeBuffer - let typeName = fieldSymbol.Type!.ToDisplayString() + let typeName = fieldSymbol.Type!.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) let fieldFullType = ParseTypeName(typeName) select (Type: fieldFullType, Identifier: Identifier(fieldSymbol.Name))).ToImmutableArray(); @@ -100,7 +100,8 @@ public sealed partial class AutoConstructorGenerator : ISourceGenerator // From this, we can finally generate the source code to output. var source = CompilationUnit().AddMembers( - NamespaceDeclaration(IdentifierName(namespaceName)).AddMembers(typeDeclarationSyntax)) + FileScopedNamespaceDeclaration(IdentifierName(namespaceName)).AddMembers(typeDeclarationSyntax) + .WithNamespaceKeyword(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.NamespaceKeyword, TriviaList()))) .NormalizeWhitespace(eol: "\n") .ToFullString(); diff --git a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj index 73a454d8..ff44f286 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj +++ b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj @@ -69,7 +69,7 @@ - + diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs index cc339834..b4cc7f6f 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs @@ -29,8 +29,7 @@ public sealed partial class IShaderGenerator StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, out string? implicitTextureType, - out bool isSamplerUsed, - out bool isHashSetDirectiveNeeded) + out bool isSamplerUsed) { // Properties are not supported DetectAndReportPropertyDeclarations(context, structDeclarationSymbol); @@ -71,15 +70,14 @@ public sealed partial class IShaderGenerator accessesStaticSampler, sharedBuffers, processedMethods, - entryPoint, - out isHashSetDirectiveNeeded); + entryPoint); implicitTextureType = pixelShaderTextureType; isSamplerUsed = accessesStaticSampler; // This code produces a method declaration as follows: // - // readonly void IShader.BuildHlslString(ref ArrayPoolStringBuilder builder, int threadsX, int threadsY, int threadsZ) + // readonly void global::ComputeSharp.__Internals.IShader.BuildHlslString(ref global::ComputeSharp.__Internals.ArrayPoolStringBuilder builder, int threadsX, int threadsY, int threadsZ) // { // // } @@ -87,10 +85,10 @@ public sealed partial class IShaderGenerator MethodDeclaration( PredefinedType(Token(SyntaxKind.VoidKeyword)), Identifier("BuildHlslString")) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName(nameof(IShader)))) + .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}"))) .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) .AddParameterListParameters( - Parameter(Identifier("builder")).AddModifiers(Token(SyntaxKind.OutKeyword)).WithType(IdentifierName("ArrayPoolStringBuilder")), + Parameter(Identifier("builder")).AddModifiers(Token(SyntaxKind.OutKeyword)).WithType(IdentifierName("global::ComputeSharp.__Internals.ArrayPoolStringBuilder")), Parameter(Identifier("threadsX")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), Parameter(Identifier("threadsY")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), Parameter(Identifier("threadsZ")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword)))) @@ -474,7 +472,6 @@ public sealed partial class IShaderGenerator /// The sequence of shared buffers declared by the shader. /// The sequence of processed methods used by the shader. /// The body of the entry point of the shader. - /// Indicates whether or not the directive for is needed. /// The series of statements to build the HLSL source to compile to execute the current shader. private static IEnumerable GenerateRenderMethodBody( IEnumerable<(string Name, string Value)> definedConstants, @@ -486,8 +483,7 @@ public sealed partial class IShaderGenerator bool isSamplerUsed, IEnumerable<(string Name, string Type, int? Count)> sharedBuffers, IEnumerable<(string Signature, string Definition)> processedMethods, - string executeMethod, - out bool isHashSetDirectiveNeeded) + string executeMethod) { List statements = new(); StringBuilder textBuilder = new(); @@ -545,10 +541,10 @@ public sealed partial class IShaderGenerator { void DeclareMapping(int index, string name, IEnumerable items) { - // HashSet = new(); + // global::System.Collections.Generic.HashSet = new(); statements.Insert(index, LocalDeclarationStatement(VariableDeclaration( - GenericName(Identifier("HashSet")) + GenericName(Identifier("global::System.Collections.Generic.HashSet")) .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.StringKeyword)))) .AddVariables( VariableDeclarator(Identifier(name)) @@ -580,9 +576,9 @@ public sealed partial class IShaderGenerator // Go through all existing delegate fields, if any foreach (var (fieldSymbol, fieldName, fieldType) in instanceFields.Where(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate)) { - // ShaderMethodSourceAttribute __Attribute = ShaderMethodSourceAttribute.GetForDelegate(, ""); + // global::ComputeSharp.__Internals.ShaderMethodSourceAttribute __Attribute = global::ComputeSharp.__Internals.ShaderMethodSourceAttribute.GetForDelegate(, ""); statements.Add( - LocalDeclarationStatement(VariableDeclaration(IdentifierName(nameof(ShaderMethodSourceAttribute))) + LocalDeclarationStatement(VariableDeclaration(IdentifierName($"global::ComputeSharp.__Internals.{nameof(ShaderMethodSourceAttribute)}")) .AddVariables( VariableDeclarator(Identifier($"__{fieldName}Attribute")) .WithInitializer( @@ -590,7 +586,7 @@ public sealed partial class IShaderGenerator InvocationExpression( MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, - IdentifierName(nameof(ShaderMethodSourceAttribute)), + IdentifierName($"global::ComputeSharp.__Internals.{nameof(ShaderMethodSourceAttribute)}"), IdentifierName(nameof(ShaderMethodSourceAttribute.GetForDelegate)))) .AddArgumentListArguments( Argument(IdentifierName(fieldName)), @@ -601,8 +597,6 @@ public sealed partial class IShaderGenerator } } - isHashSetDirectiveNeeded = capturedDelegates > 0; - // Header AppendLineAndLF("// ================================================"); AppendLineAndLF("// AUTO GENERATED"); @@ -800,7 +794,7 @@ public sealed partial class IShaderGenerator FlushText(); - // builder = ArrayPoolStringBuilder.Create(); + // builder = global::ComputeSharp.__Internals.ArrayPoolStringBuilder.Create(); statements.Insert( prologueStatements, ExpressionStatement( @@ -810,7 +804,7 @@ public sealed partial class IShaderGenerator InvocationExpression( MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("ArrayPoolStringBuilder"), + IdentifierName("global::ComputeSharp.__Internals.ArrayPoolStringBuilder"), IdentifierName("Create"))) .AddArgumentListArguments( Argument(LiteralExpression( diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.cs index 092fb425..bbbf4452 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.cs @@ -20,7 +20,7 @@ public sealed partial class IShaderGenerator { // This code produces a method declaration as follows: // - // readonly int IShader.GetDispatchId() + // readonly int global::ComputeSharp.__Internals.IShader.GetDispatchId() // { // // } @@ -28,7 +28,7 @@ public sealed partial class IShaderGenerator MethodDeclaration( PredefinedType(Token(SyntaxKind.IntKeyword)), Identifier("GetDispatchId")) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName(nameof(IShader)))) + .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}"))) .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) .WithBody(GetShaderHashCodeBody(structDeclarationSymbol)); } @@ -59,9 +59,9 @@ public sealed partial class IShaderGenerator List blockStatements = new(4); - // HashCode hashCode = default; + // global::System.HashCode hashCode = default; blockStatements.Add(LocalDeclarationStatement( - VariableDeclaration(IdentifierName("HashCode")) + VariableDeclaration(IdentifierName("global::System.HashCode")) .AddVariables( VariableDeclarator(Identifier("hashCode")) .WithInitializer(EqualsValueClause( diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs index bc16e5ac..e8751e13 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs @@ -28,7 +28,7 @@ public sealed partial class IShaderGenerator { // This code produces a method declaration as follows: // - // readonly void IShader.LoadDispatchData(ref TDataLoader loader, GraphicsDevice device, int x, int y, int z) + // readonly void global::ComputeSharp.__Internals.IShader.LoadDispatchData(ref TDataLoader loader, global::ComputeSharp.GraphicsDevice device, int x, int y, int z) // { // // } @@ -36,14 +36,14 @@ public sealed partial class IShaderGenerator MethodDeclaration( PredefinedType(Token(SyntaxKind.VoidKeyword)), Identifier("LoadDispatchData")) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName(nameof(IShader)))) + .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}"))) .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) .AddTypeParameterListParameters(TypeParameter(Identifier("TDataLoader"))) .AddParameterListParameters( Parameter(Identifier("loader")) .AddModifiers(Token(SyntaxKind.RefKeyword)) .WithType(IdentifierName("TDataLoader")), - Parameter(Identifier("device")).WithType(IdentifierName("GraphicsDevice")), + Parameter(Identifier("device")).WithType(IdentifierName("global::ComputeSharp.GraphicsDevice")), Parameter(Identifier("x")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), Parameter(Identifier("y")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), Parameter(Identifier("z")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword)))) @@ -58,7 +58,7 @@ public sealed partial class IShaderGenerator /// The collection of discovered resources in the current shader type. /// The total number of 32 bit root constants being loaded for the current shader type. /// The sequence of instances to load shader dispatch data. - private static IEnumerable GetDispatchDataLoadingStatements(GeneratorExecutionContext context, INamedTypeSymbol structDeclarationSymbol, out IReadOnlyCollection discoveredResources, out int root32BitConstantsCount) + private static IEnumerable GetDispatchDataLoadingStatements(GeneratorExecutionContext context, INamedTypeSymbol structDeclarationSymbol, out IReadOnlyCollection discoveredResources, out int root32BitConstantsCount) { List statements = new(); List resources = new(); @@ -128,11 +128,11 @@ public sealed partial class IShaderGenerator context.ReportDiagnostic(ShaderDispatchDataSizeExceeded, structDeclarationSymbol, structDeclarationSymbol); } - // Span span0 = stackalloc uint[]; + // global::System.Span span0 = stackalloc uint[]; statements.Insert(0, LocalDeclarationStatement( VariableDeclaration( - GenericName(Identifier("Span")) + GenericName(Identifier("global::System.Span")) .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.UIntKeyword)))) .AddVariables( VariableDeclarator(Identifier("span0")) @@ -169,11 +169,11 @@ public sealed partial class IShaderGenerator if (resourceOffset > 0) { - // Span span1 = stackalloc ulong[]; + // global::System.Span span1 = stackalloc ulong[]; statements.Insert(1, LocalDeclarationStatement( VariableDeclaration( - GenericName(Identifier("Span")) + GenericName(Identifier("global::System.Span")) .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ULongKeyword)))) .AddVariables( VariableDeclarator(Identifier("span1")) @@ -257,8 +257,8 @@ public sealed partial class IShaderGenerator statements.Add(ExpressionStatement( AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, - ParseExpression($"Unsafe.Add(ref r1, {resourceOffset++})"), - ParseExpression($"GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle({fieldName}, device)")))); + ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {resourceOffset++})"), + ParseExpression($"global::ComputeSharp.__Internals.GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle({fieldName}, device)")))); } else if (HlslKnownTypes.IsKnownHlslType(typeName)) { @@ -291,17 +291,17 @@ public sealed partial class IShaderGenerator if (HlslKnownTypes.IsNonLinearMatrixType(typeName, out string? elementName, out int rows, out int columns)) { string - rowTypeName = $"ComputeSharp.{elementName}{columns}", + rowTypeName = $"global::ComputeSharp.{elementName}{columns}", rowLocalName = $"__{string.Join("_", fieldPath)}__row0"; - statements.Add(ParseStatement($"ref {rowTypeName} {rowLocalName} = ref Unsafe.As<{typeName}, {rowTypeName}>(ref Unsafe.AsRef(in {string.Join(".", fieldPath)}));")); + statements.Add(ParseStatement($"ref {rowTypeName} {rowLocalName} = ref global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in {string.Join(".", fieldPath)}));")); // Generate the loading code for each individual row, with proper alignment. // This will result in the following (assuming Float2x3 m): // - // ref Float3 __m__row0 = ref Unsafe.As(ref Unsafe.AsRef(in m)); - // Unsafe.As(ref Unsafe.AddByteOffset(ref r0, (nint)rawDataOffset)) =, Unsafe.Add(ref __m__row0, 0); - // Unsafe.As(ref Unsafe.AddByteOffset(ref r0, (nint)(rawDataOffset + 16))) = Unsafe.Add(ref __m__row0, 1); + // ref global::ComputeSharp.Float3 __m__row0 = ref global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in m)); + // global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)rawDataOffset)) =, global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 0); + // global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)(rawDataOffset + 16))) = global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 1); for (int j = 0; j < rows; j++) { rawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16); @@ -309,8 +309,8 @@ public sealed partial class IShaderGenerator statements.Add(ExpressionStatement( AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, - ParseExpression($"Unsafe.As(ref Unsafe.AddByteOffset(ref r0, (nint){rawDataOffset}))"), - ParseExpression($"Unsafe.Add(ref {rowLocalName}, {j})")))); + ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){rawDataOffset}))"), + ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.Add(ref {rowLocalName}, {j})")))); rawDataOffset += fieldPack * columns; } @@ -329,7 +329,7 @@ public sealed partial class IShaderGenerator statements.Add(ExpressionStatement( AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, - ParseExpression($"Unsafe.As(ref Unsafe.AddByteOffset(ref r0, (nint){rawDataOffset}))"), + ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){rawDataOffset}))"), ParseExpression($"{string.Join(".", fieldPath)}")))); rawDataOffset += fieldSize; diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs index 087413ef..fc8c779e 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs @@ -22,7 +22,7 @@ public sealed partial class IShaderGenerator { // This code produces a method declaration as follows: // - // readonly void IShader.LoadDispatchMetadata(ref TMetadataLoader loader, out IntPtr result) + // readonly void global::ComputeSharp.__Internals.IShader.LoadDispatchMetadata(ref TMetadataLoader loader, out global::System.IntPtr result) // { // // } @@ -30,7 +30,7 @@ public sealed partial class IShaderGenerator MethodDeclaration( PredefinedType(Token(SyntaxKind.VoidKeyword)), Identifier("LoadDispatchMetadata")) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName(nameof(IShader)))) + .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}"))) .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) .AddTypeParameterListParameters(TypeParameter(Identifier("TMetadataLoader"))) .AddParameterListParameters( @@ -39,7 +39,7 @@ public sealed partial class IShaderGenerator .WithType(IdentifierName("TMetadataLoader")), Parameter(Identifier("result")) .AddModifiers(Token(SyntaxKind.OutKeyword)) - .WithType(IdentifierName(typeof(IntPtr).Name))) + .WithType(IdentifierName($"global::System.{typeof(IntPtr).Name}"))) .WithBody(Block(GetDispatchMetadataLoadingStatements(implicitTextureType, discoveredResources, root32BitConstantsCount, isSamplerUsed))); } @@ -57,11 +57,11 @@ public sealed partial class IShaderGenerator int root32BitConstantsCount, bool isSamplerUsed) { - // Span span0 = stackalloc byte[5]; + // global::System.Span span0 = stackalloc byte[5]; yield return LocalDeclarationStatement( VariableDeclaration( - GenericName(Identifier("Span")) + GenericName(Identifier("global::System.Span")) .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword)))) .AddVariables( VariableDeclarator(Identifier("span0")) @@ -75,17 +75,17 @@ public sealed partial class IShaderGenerator // Compute the total number of resources (discovered ones and the implicit target texture, if present) int totalResourcesCount = discoveredResources.Count + (implicitTextureType is not null ? 1 : 0); - // Span span1 = stackalloc ResourceDescriptor[]; + // Span span1 = stackalloc global::ComputeSharp.__Internals.ResourceDescriptor[]; yield return LocalDeclarationStatement( VariableDeclaration( - GenericName(Identifier("Span")) - .AddTypeArgumentListArguments(IdentifierName("ResourceDescriptor"))) + GenericName(Identifier("global::System.Span")) + .AddTypeArgumentListArguments(IdentifierName("global::ComputeSharp.__Internals.ResourceDescriptor"))) .AddVariables( VariableDeclarator(Identifier("span1")) .WithInitializer(EqualsValueClause( StackAllocArrayCreationExpression( - ArrayType(IdentifierName("ResourceDescriptor")) + ArrayType(IdentifierName("global::ComputeSharp.__Internals.ResourceDescriptor")) .AddRankSpecifiers( ArrayRankSpecifier(SingletonSeparatedList( LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(totalResourcesCount)))))))))); @@ -104,10 +104,10 @@ public sealed partial class IShaderGenerator SyntaxKind.NumericLiteralExpression, Literal(0))))))))); - // ref ResourceDescriptor r1 = ref span1[0]; + // ref global::ComputeSharp.__Internals.ResourceDescriptor r1 = ref span1[0]; yield return LocalDeclarationStatement( - VariableDeclaration(RefType(IdentifierName("ResourceDescriptor"))) + VariableDeclaration(RefType(IdentifierName("global::ComputeSharp.__Internals.ResourceDescriptor"))) .AddVariables( VariableDeclarator(Identifier("r1")) .WithInitializer(EqualsValueClause( @@ -119,8 +119,8 @@ public sealed partial class IShaderGenerator Literal(0))))))))); // Serialized shader metadata - yield return ParseStatement($"Unsafe.WriteUnaligned(ref Unsafe.Add(ref r0, 0), {root32BitConstantsCount});"); - yield return ParseStatement($"Unsafe.WriteUnaligned(ref Unsafe.Add(ref r0, 4), {isSamplerUsed.ToString().ToLowerInvariant()});"); + yield return ParseStatement($"global::System.Runtime.CompilerServices.Unsafe.WriteUnaligned(ref global::System.Runtime.CompilerServices.Unsafe.Add(ref r0, 0), {root32BitConstantsCount});"); + yield return ParseStatement($"global::System.Runtime.CompilerServices.Unsafe.WriteUnaligned(ref global::System.Runtime.CompilerServices.Unsafe.Add(ref r0, 4), {isSamplerUsed.ToString().ToLowerInvariant()});"); int constantBufferOffset = 1, @@ -131,7 +131,7 @@ public sealed partial class IShaderGenerator // Add the implicit texture descriptor, if needed if (implicitTextureType is not null) { - yield return ParseStatement($"ResourceDescriptor.Create(1, {readWriteResourceOffset++}, out Unsafe.Add(ref r1, {resourceOffset++}));"); + yield return ParseStatement($"global::ComputeSharp.__Internals.ResourceDescriptor.Create(1, {readWriteResourceOffset++}, out global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {resourceOffset++}));"); } // Populate the sequence of resource descriptors @@ -139,15 +139,15 @@ public sealed partial class IShaderGenerator { if (HlslKnownTypes.IsConstantBufferType(resource)) { - yield return ParseStatement($"ResourceDescriptor.Create(2, {constantBufferOffset++}, out Unsafe.Add(ref r1, {resourceOffset++}));"); + yield return ParseStatement($"global::ComputeSharp.__Internals.ResourceDescriptor.Create(2, {constantBufferOffset++}, out global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {resourceOffset++}));"); } else if (HlslKnownTypes.IsReadOnlyTypedResourceType(resource)) { - yield return ParseStatement($"ResourceDescriptor.Create(0, {readOnlyResourceOffset++}, out Unsafe.Add(ref r1, {resourceOffset++}));"); + yield return ParseStatement($"global::ComputeSharp.__Internals.ResourceDescriptor.Create(0, {readOnlyResourceOffset++}, out global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {resourceOffset++}));"); } else { - yield return ParseStatement($"ResourceDescriptor.Create(1, {readWriteResourceOffset++}, out Unsafe.Add(ref r1, {resourceOffset++}));"); + yield return ParseStatement($"global::ComputeSharp.__Internals.ResourceDescriptor.Create(1, {readWriteResourceOffset++}, out global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {resourceOffset++}));"); } } diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs index d82d2cdd..a86963e6 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs @@ -59,7 +59,7 @@ public sealed partial class IShaderGenerator : ISourceGenerator MethodDeclarationSyntax getDispatchIdMethod = CreateGetDispatchIdMethod(structDeclarationSymbol), loadDispatchDataMethod = CreateLoadDispatchDataMethod(context, structDeclarationSymbol, out var discoveredResources, out int root32BitConstants), - buildHlslStringMethod = CreateBuildHlslStringMethod(context, structDeclaration, structDeclarationSymbol, out string? implicitTextureType, out bool isSamplerUsed, out bool isHashSetDirectiveNeeded), + buildHlslStringMethod = CreateBuildHlslStringMethod(context, structDeclaration, structDeclarationSymbol, out string? implicitTextureType, out bool isSamplerUsed), loadDispatchMetadataMethod = CreateLoadDispatchMetadataMethod(implicitTextureType, discoveredResources, root32BitConstants, isSamplerUsed); // Reorder the method declarations to respect the order in the interface definition @@ -75,16 +75,16 @@ public sealed partial class IShaderGenerator : ISourceGenerator List attributes = new() { AttributeList(SingletonSeparatedList( - Attribute(IdentifierName("GeneratedCode")).AddArgumentListArguments( + Attribute(IdentifierName("global::System.CodeDom.Compiler.GeneratedCode")).AddArgumentListArguments( AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IShaderGenerator).FullName))), AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IShaderGenerator).Assembly.GetName().Version.ToString())))))), - AttributeList(SingletonSeparatedList(Attribute(IdentifierName("DebuggerNonUserCode")))), - AttributeList(SingletonSeparatedList(Attribute(IdentifierName("ExcludeFromCodeCoverage")))), + AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.DebuggerNonUserCode")))), + AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage")))), AttributeList(SingletonSeparatedList( - Attribute(IdentifierName("EditorBrowsable")).AddArgumentListArguments( - AttributeArgument(ParseExpression("EditorBrowsableState.Never"))))), + Attribute(IdentifierName("global::System.ComponentModel.EditorBrowsable")).AddArgumentListArguments( + AttributeArgument(ParseExpression("global::System.ComponentModel.EditorBrowsableState.Never"))))), AttributeList(SingletonSeparatedList( - Attribute(IdentifierName("Obsolete")).AddArgumentListArguments( + Attribute(IdentifierName("global::System.Obsolete")).AddArgumentListArguments( AttributeArgument(LiteralExpression( SyntaxKind.StringLiteralExpression, Literal("This method is not intended to be used directly by user code")))))) @@ -93,7 +93,7 @@ public sealed partial class IShaderGenerator : ISourceGenerator // Add [SkipLocalsInit] if the target project allows it if (context.Compilation.Options is CSharpCompilationOptions { AllowUnsafe: true }) { - attributes.Add(AttributeList(SingletonSeparatedList(Attribute(IdentifierName("SkipLocalsInit"))))); + attributes.Add(AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Runtime.CompilerServices.SkipLocalsInit"))))); } string namespaceName = structDeclarationSymbol.ContainingNamespace.ToDisplayString(new(typeQualificationStyle: NameAndContainingTypesAndNamespaces)); @@ -125,44 +125,17 @@ public sealed partial class IShaderGenerator : ISourceGenerator .WithoutTrivia(); } - // Prepare the necessary using directives - List usingDirectives = new() - { - UsingDirective(IdentifierName("System")), - UsingDirective(IdentifierName("System.CodeDom.Compiler")), - UsingDirective(IdentifierName("System.ComponentModel")), - UsingDirective(IdentifierName("System.Diagnostics")), - UsingDirective(IdentifierName("System.Diagnostics.CodeAnalysis")), - UsingDirective(IdentifierName("System.Runtime.CompilerServices")), - UsingDirective(IdentifierName("ComputeSharp")), - UsingDirective(IdentifierName("ComputeSharp.__Internals")) - }; - - if (isHashSetDirectiveNeeded) - { - usingDirectives.Insert(2, UsingDirective(IdentifierName("System.Collections.Generic"))); - } - // Create a static method to create the combined hashcode for a given shader type. // This code takes a block syntax and produces a compilation unit as follows: // - // using System; - // using System.CodeDom.Compiler; - // using System.ComponentModel; - // using System.Diagnostics; - // using System.Diagnostics.CodeAnalysis; - // using System.Runtime.CompilerServices; - // using ComputeSharp.__Internals; - // // #pragma warning disable // - // namespace - // { - // - // } + // namespace ; + // + // var source = - CompilationUnit().AddUsings(usingDirectives.ToArray()).AddMembers( - NamespaceDeclaration(IdentifierName(namespaceName)).AddMembers(typeDeclarationSyntax) + CompilationUnit().AddMembers( + FileScopedNamespaceDeclaration(IdentifierName(namespaceName)).AddMembers(typeDeclarationSyntax) .WithNamespaceKeyword(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.NamespaceKeyword, TriviaList()))) .NormalizeWhitespace(eol: "\n") .ToFullString(); @@ -200,15 +173,13 @@ public sealed partial class IShaderGenerator : ISourceGenerator /// The for . /// The implicit texture type, if available (if the shader is a pixel shader). /// Whether or not the current shader type requires a static sampler to be available. - /// Indicates whether or not the directive for is needed. /// The resulting instance for the BuildHlslString method. private static partial MethodDeclarationSyntax CreateBuildHlslStringMethod( GeneratorExecutionContext context, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, out string? implicitTextureType, - out bool isSamplerUsed, - out bool isHashSetDirectiveNeeded); + out bool isSamplerUsed); /// /// Creates a instance for the LoadDispatchMetadata method. diff --git a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs index 9ab3bdee..a48b54fc 100644 --- a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs @@ -77,7 +77,7 @@ public sealed partial class ShaderMethodSourceGenerator : ISourceGenerator var source = CompilationUnit().AddAttributeLists( AttributeList(SingletonSeparatedList( - Attribute(IdentifierName(typeof(ShaderMethodSourceAttribute).FullName)).AddArgumentListArguments( + Attribute(IdentifierName($"global::ComputeSharp.__Internals.{typeof(ShaderMethodSourceAttribute).FullName}")).AddArgumentListArguments( AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(methodDeclarationSymbol.GetFullMetadataName(true)))), AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(invokeMethod))), AttributeArgument(NestedArrayExpression(processedTypes)), diff --git a/tests/ComputeSharp.Tests.SourceGenerators/ComputeSharp.Tests.SourceGenerators.csproj b/tests/ComputeSharp.Tests.SourceGenerators/ComputeSharp.Tests.SourceGenerators.csproj index b896c7ef..ee310721 100644 --- a/tests/ComputeSharp.Tests.SourceGenerators/ComputeSharp.Tests.SourceGenerators.csproj +++ b/tests/ComputeSharp.Tests.SourceGenerators/ComputeSharp.Tests.SourceGenerators.csproj @@ -6,10 +6,10 @@ - - - - + + + +