From 18e1c2c5e0290903e372f97fb5efc5dc649eba42 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 29 Nov 2020 23:34:49 +0100 Subject: [PATCH] Removed unnecessaary source generator --- .../HlslBokehBlurProcessor{TPixel}.cs | 1 - .../Attributes/FieldAttribute.cs | 39 --- .../Attributes/Internals/IsExternalInit.cs | 20 -- .../Extensions/AttributeDataExtensions.cs | 37 --- .../FieldAttributeGenerator.cs | 224 ------------------ 5 files changed, 321 deletions(-) delete mode 100644 src/ComputeSharp.Core/Attributes/FieldAttribute.cs delete mode 100644 src/ComputeSharp.Core/Attributes/Internals/IsExternalInit.cs delete mode 100644 src/ComputeSharp.SourceGenerators/Extensions/AttributeDataExtensions.cs delete mode 100644 src/ComputeSharp.SourceGenerators/FieldAttributeGenerator.cs diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs index f1d13b89..68c19fd3 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs @@ -6,7 +6,6 @@ using System.Diagnostics.Contracts; using System.Numerics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -using ComputeSharp.ImageProcessing.Primitives; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Advanced; using SixLabors.ImageSharp.PixelFormats; diff --git a/src/ComputeSharp.Core/Attributes/FieldAttribute.cs b/src/ComputeSharp.Core/Attributes/FieldAttribute.cs deleted file mode 100644 index 98ee33d2..00000000 --- a/src/ComputeSharp.Core/Attributes/FieldAttribute.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System; - -namespace ComputeSharp -{ - /// - /// An attribute that indicates a field to declare in a custom struct type to use in a shader. - /// This is necessary to be used instead of manually declare fields, so that the fields can be - /// declared with the right offset into the type data, as HLSL requires precise alignment for values. - /// - [AttributeUsage(AttributeTargets.Struct, AllowMultiple = true)] - public sealed class FieldAttribute : Attribute - { - /// - /// Creates a new instance with the specified parameters. - /// - /// The name of the field to declare. - /// The type of field to declare. - public FieldAttribute(string name, Type type) - { - Name = name; - Type = type; - } - - /// - /// Gets the name of the field to declare. - /// - public string Name { get; } - - /// - /// Gets the type of the field to declare. - /// - public Type Type { get; } - - /// - /// Gets the optional summary for the field to declare. - /// - public string? Summary { get; init; } - } -} \ No newline at end of file diff --git a/src/ComputeSharp.Core/Attributes/Internals/IsExternalInit.cs b/src/ComputeSharp.Core/Attributes/Internals/IsExternalInit.cs deleted file mode 100644 index ac4cc2ef..00000000 --- a/src/ComputeSharp.Core/Attributes/Internals/IsExternalInit.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -#if !NET5_0 - -using System.ComponentModel; - -namespace System.Runtime.CompilerServices -{ - /// - /// Reserved to be used by the compiler for tracking metadata. - /// This class should not be used by developers in source code. - /// - [EditorBrowsable(EditorBrowsableState.Never)] - internal static class IsExternalInit - { - } -} - -#endif \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/Extensions/AttributeDataExtensions.cs b/src/ComputeSharp.SourceGenerators/Extensions/AttributeDataExtensions.cs deleted file mode 100644 index f51125ab..00000000 --- a/src/ComputeSharp.SourceGenerators/Extensions/AttributeDataExtensions.cs +++ /dev/null @@ -1,37 +0,0 @@ -using System.Diagnostics.Contracts; -using Microsoft.CodeAnalysis; - -namespace ComputeSharp.SourceGenerators.Extensions -{ - /// - /// A with some extension methods for the type. - /// - internal static class AttributeDataExtension - { - /// - /// Tries to get a named argument from a given instance. - /// - /// The type of value to retrieve. - /// The input instance to get the value from. - /// The name of the argument to retrieve. - /// The resulting value, if found. - /// Whether or not the requested argument was found. - [Pure] - public static bool TryGetNamedArgument(this AttributeData attributeData, string key, out T? value) - { - foreach (var argument in attributeData.NamedArguments) - { - if (argument.Key.Equals(key)) - { - value = (T?)argument.Value.Value; - - return true; - } - } - - value = default; - - return false; - } - } -} diff --git a/src/ComputeSharp.SourceGenerators/FieldAttributeGenerator.cs b/src/ComputeSharp.SourceGenerators/FieldAttributeGenerator.cs deleted file mode 100644 index 8e0d189f..00000000 --- a/src/ComputeSharp.SourceGenerators/FieldAttributeGenerator.cs +++ /dev/null @@ -1,224 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics.Contracts; -using System.Linq; -using System.Runtime.InteropServices; -using System.Text; -using ComputeSharp.SourceGenerators.Extensions; -using ComputeSharp.SourceGenerators.Mappings; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Text; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; -using static Microsoft.CodeAnalysis.SymbolDisplayTypeQualificationStyle; - -namespace ComputeSharp.SourceGenerators -{ - [Generator] - public class FieldAttributeGenerator : ISourceGenerator - { - /// - public void Initialize(GeneratorInitializationContext context) - { - } - - /// - public void Execute(GeneratorExecutionContext context) - { - // Find all the [Field] usages - var attributes = new Queue>( - from tree in context.Compilation.SyntaxTrees - from structDeclaration in tree.GetRoot().DescendantNodes().OfType() - let semanticModel = context.Compilation.GetSemanticModel(structDeclaration.SyntaxTree) - let structSymbol = semanticModel.GetDeclaredSymbol(structDeclaration) - from attribute in structSymbol.GetAttributes() - where attribute.AttributeClass is { Name: nameof(FieldAttribute) } - group attribute by structDeclaration into groups - select groups); - - // Get an incremental map of discovered types - var discoveredTypes = HlslKnownSizes.KnownSizes.ToDictionary(static p => p.Key, static p => p.Value); - - while (attributes.Count > 0) - { - var group = attributes.Dequeue(); - - SemanticModel semanticModel = context.Compilation.GetSemanticModel(group.Key.SyntaxTree); - INamedTypeSymbol structDeclarationSymbol = semanticModel.GetDeclaredSymbol(group.Key)!; - - // Check if a type has all the dependent types resolved already. If this is not the - // case, add the type at the back of the queue and continue. The other types will be - // processed first, and the current one will be picked up again when more info is available. - if (!AreDependentTypesDiscovered(structDeclarationSymbol, group, discoveredTypes.Keys)) - { - attributes.Enqueue(group); - - continue; - } - - // Process the type and generate the necessary fields - var generatedTypeInfo = GetProcessedFields(group, discoveredTypes, out int size, out int pack); - - // Add the current type to the target map - discoveredTypes.Add(structDeclarationSymbol.GetFullMetadataName(), (size, pack)); - - // Extract the info on the type to process - var namespaceName = structDeclarationSymbol.ContainingNamespace.ToDisplayString(new(typeQualificationStyle: NameAndContainingTypesAndNamespaces)); - var structName = group.Key.Identifier.Text; - var structModifiers = group.Key.Modifiers; - - // Declare the partial type with the right layout attribute to track the size and - // the HLSL packing, and add the generated field declarations requested by the user. - var structDeclarationSyntax = - StructDeclaration(structName).WithModifiers(structModifiers) - .AddAttributeLists(AttributeList(SingletonSeparatedList(generatedTypeInfo.Layout))) - .AddMembers(generatedTypeInfo.Fields.ToArray()); - - TypeDeclarationSyntax typeDeclarationSyntax = structDeclarationSyntax; - - // Add all parent types in ascending order, if any - foreach (var parentType in group.Key.Ancestors().OfType()) - { - typeDeclarationSyntax = parentType - .WithMembers(SingletonList(typeDeclarationSyntax)) - .WithConstraintClauses(List()) - .WithBaseList(null) - .WithoutTrivia(); - } - - // Create the compilation unit with the namespace and target member. - var source = - CompilationUnit().AddMembers( - NamespaceDeclaration(IdentifierName(namespaceName)).AddMembers(typeDeclarationSyntax)) - .NormalizeWhitespace() - .ToFullString(); - - // Add the partial type - context.AddSource(structDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8)); - } - } - - /// - /// Checks whether all dependent types for a target type have been discovered, - /// and whether the target type can be processed to generate the target fields. - /// - /// The symbol of the target type to process. - /// The collection of attributes (of type ). - /// The map of currently discovered types. - /// Whether or not the current type can be processed. - [Pure] - private static bool AreDependentTypesDiscovered( - INamedTypeSymbol targetTypeSymbol, - IEnumerable attributes, - IReadOnlyCollection discoveredTypes) - { - foreach (var attribute in attributes) - { - INamedTypeSymbol fieldType = (INamedTypeSymbol)attribute.ConstructorArguments[1].Value!; - - // The current type can be processed if all the declared fields have been discovered - // (so if they're of a known primitive type) or are of a type that comes from a separate - // assembly. If a type has not been discovered, then that one will need to be processed first - // to ensure the necessary size/pack info will be available during generation. If the type comes - // from a separate assembly, the generator will assume that type will already contain the necessary - // layout annotation, which will be read directly while processing that specific field. - if (!discoveredTypes.Contains(fieldType.GetFullMetadataName()) && - fieldType.ContainingAssembly.Identity.Equals(targetTypeSymbol.ContainingAssembly.Identity)) - { - return false; - } - } - - return true; - } - - /// - /// Gets a sequence of field declarations for a given type. - /// - /// The input sequence of data instances. - /// An attribute for the layout of the kind, and the sequence of field declarations. - private static (AttributeSyntax Layout, IEnumerable Fields) GetProcessedFields( - IEnumerable attributes, - IReadOnlyDictionary discoveredTypes, - out int size, - out int pack) - { - size = 0; - pack = 0; - - List fieldDeclarations = new(); - - foreach (var attribute in attributes) - { - // Extract the field info - string fieldName = (string)attribute.ConstructorArguments[0].Value!; - INamedTypeSymbol fieldType = (INamedTypeSymbol)attribute.ConstructorArguments[1].Value!; - - // Get the size and pack for the current field - if (!discoveredTypes.TryGetValue(fieldType.GetFullMetadataName(), out var mapping)) - { - var structLayout = fieldType.GetAttributes().First(a => a.AttributeClass is { Name: nameof(StructLayoutAttribute) }); - - _ = structLayout.TryGetNamedArgument(nameof(StructLayoutAttribute.Size), out mapping.Size); - _ = structLayout.TryGetNamedArgument(nameof(StructLayoutAttribute.Pack), out mapping.Pack); - } - - // Calculate the target offset - int - adjustment = size % mapping.Pack, - offset = size + adjustment; - - size += adjustment + mapping.Size; - pack = Math.Max(pack, mapping.Pack); - - // Create the field declaration - var fieldDeclaration = - FieldDeclaration( - VariableDeclaration(IdentifierName(fieldType.GetFullMetadataName())) - .AddVariables(VariableDeclarator(Identifier(fieldName)))) - .AddAttributeLists(AttributeList(SingletonSeparatedList( - Attribute(IdentifierName(typeof(FieldOffsetAttribute).FullName)).AddArgumentListArguments( - AttributeArgument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(offset))))))) - .AddModifiers(Token(SyntaxKind.PublicKeyword)); - - // Add the XML tag, if a summary is present - if (attribute.TryGetNamedArgument(nameof(FieldAttribute.Summary), out string? summary)) - { - fieldDeclaration = - fieldDeclaration.WithLeadingTrivia( - TriviaList(Trivia(DocumentationCommentTrivia( - SyntaxKind.SingleLineDocumentationCommentTrivia, - List(new XmlNodeSyntax[] - { - XmlText().AddTextTokens(XmlTextLiteral(TriviaList(DocumentationCommentExterior("///")), " ", " ", TriviaList())), - XmlExampleElement(SingletonList(XmlText().AddTextTokens(XmlTextLiteral(summary!)))) - .WithStartTag(XmlElementStartTag(XmlName(Identifier("summary")))) - .WithEndTag(XmlElementEndTag(XmlName(Identifier("summary")))), - XmlText().AddTextTokens(XmlTextNewLine("\n", false)) - }))))); - } - - fieldDeclarations.Add(fieldDeclaration); - } - - // Add the trailing padding, if needed - size += size % pack; - - // Get the attribute for the layout of the entire type - var layoutAttribute = - Attribute(IdentifierName(typeof(StructLayoutAttribute).FullName)).AddArgumentListArguments( - AttributeArgument(MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName(typeof(LayoutKind).FullName), - IdentifierName(nameof(LayoutKind.Explicit)))), - AttributeArgument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(size))) - .WithNameEquals(NameEquals(IdentifierName(nameof(StructLayoutAttribute.Size)))), - AttributeArgument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(pack))) - .WithNameEquals(NameEquals(IdentifierName(nameof(StructLayoutAttribute.Pack))))); - - return (layoutAttribute, fieldDeclarations); - } - } -} -