From 5354eabbf76ac9bfb3ef53795172772ae2eb4406 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 13 Nov 2020 17:14:54 +0100 Subject: [PATCH] Initial draft --- ComputeSharp.sln | 10 ++ .../AutoConstructorAttributeGenerator.cs | 127 ++++++++++++++++++ .../ComputeSharp.SourceGenerators.csproj | 14 ++ src/ComputeSharp/ComputeSharp.csproj | 5 + 4 files changed, 156 insertions(+) create mode 100644 src/ComputeSharp.SourceGenerators/AutoConstructorAttributeGenerator.cs create mode 100644 src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj diff --git a/ComputeSharp.sln b/ComputeSharp.sln index 4f97f672..b6780dc1 100644 --- a/ComputeSharp.sln +++ b/ComputeSharp.sln @@ -32,6 +32,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "_SolutionItems", "_Solution README.md = README.md EndProjectSection EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ComputeSharp.SourceGenerators", "src\ComputeSharp.SourceGenerators\ComputeSharp.SourceGenerators.csproj", "{EB52CB67-4162-4722-874B-44EA8DA5450E}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -112,6 +114,14 @@ Global {E889E6D6-A814-4950-AAC1-68F1ECFC5BD6}.Release|Any CPU.Build.0 = Release|Any CPU {E889E6D6-A814-4950-AAC1-68F1ECFC5BD6}.Release|x64.ActiveCfg = Release|Any CPU {E889E6D6-A814-4950-AAC1-68F1ECFC5BD6}.Release|x64.Build.0 = Release|Any CPU + {EB52CB67-4162-4722-874B-44EA8DA5450E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {EB52CB67-4162-4722-874B-44EA8DA5450E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {EB52CB67-4162-4722-874B-44EA8DA5450E}.Debug|x64.ActiveCfg = Debug|Any CPU + {EB52CB67-4162-4722-874B-44EA8DA5450E}.Debug|x64.Build.0 = Debug|Any CPU + {EB52CB67-4162-4722-874B-44EA8DA5450E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {EB52CB67-4162-4722-874B-44EA8DA5450E}.Release|Any CPU.Build.0 = Release|Any CPU + {EB52CB67-4162-4722-874B-44EA8DA5450E}.Release|x64.ActiveCfg = Release|Any CPU + {EB52CB67-4162-4722-874B-44EA8DA5450E}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/src/ComputeSharp.SourceGenerators/AutoConstructorAttributeGenerator.cs b/src/ComputeSharp.SourceGenerators/AutoConstructorAttributeGenerator.cs new file mode 100644 index 00000000..2af1cf1e --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/AutoConstructorAttributeGenerator.cs @@ -0,0 +1,127 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Text; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Text; + +namespace Mustache +{ + [Generator] + public class AutoConstructorAttributeGenerator : ISourceGenerator + { + /// + public void Initialize(GeneratorInitializationContext context) + { + //context.RegisterForSyntaxNotifications(() => new SyntaxReceiver()); + } + + /// + public void Execute(GeneratorExecutionContext context) + { + string attributeSource = @" + using System; + + namespace ComputeSharp + { + /// + /// A shader that indicates that a target shader type should get an automatic constructor for all fields. + /// + [AttributeUsage(AttributeTargets.Struct, AllowMultiple = false)] + internal sealed class AutoConstructorAttribute : Attribute + { + } + }"; + + // Add the GenerateConstructor attribute + context.AddSource("__ComputeSharp_AutoConstructorAttribute", SourceText.From(attributeSource, Encoding.UTF8)); + + // Ensure we have access to the local syntax receiver + //if (context.SyntaxReceiver is not SyntaxReceiver syntaxReceiver) return; + + // Create a new compilation with the new custom attribute + //CSharpParseOptions options = (CSharpParseOptions)((CSharpCompilation)context.Compilation).SyntaxTrees[0].Options; + //Compilation compilation = context.Compilation.AddSyntaxTrees(CSharpSyntaxTree.ParseText(SourceText.From(attributeSource, Encoding.UTF8), options)); + + // Get the new attribute from the compilation + //INamedTypeSymbol attributeSymbol = compilation.GetTypeByMetadataName("ComputeSharp.AutoConstructorAttribute")!; + + // Loop over the candidate struct declarations, and keep the ones that are actually annotated + foreach (var structSymbol in + //from structDeclaration in syntaxReceiver.CandidateTypes + from tree in context.Compilation.SyntaxTrees + from node in tree.GetRoot().DescendantNodes() + where node.IsKind(SyntaxKind.Attribute) && + node is + let semanticModel = compilation.GetSemanticModel(structDeclaration.SyntaxTree) + let symbol = semanticModel.GetDeclaredSymbol(structDeclaration) + let attributes = symbol.GetAttributes() + where attributes.Any(attribute => attribute.AttributeClass!.Equals(attributeSymbol, SymbolEqualityComparer.Default)) + select symbol) + { + string namespaceName = structSymbol.ContainingNamespace.ToDisplayString(); + + // Begin constructing the type + StringBuilder source = new(); + source.AppendLine($"namespace {namespaceName}"); + source.AppendLine("{"); + + // Visibility + source.Append(structSymbol.DeclaredAccessibility switch + { + Accessibility.Private => "private", + Accessibility.ProtectedAndInternal => "protected internal", + Accessibility.Protected => "protected", + Accessibility.Internal => "internal", + Accessibility.ProtectedOrInternal => "private protected", + Accessibility.Public => "public", + _ => throw new ArgumentException(), + }); + source.Append(" "); + + // Readonly + if (structSymbol.IsReadOnly) source.Append("readonly "); + + // End the type declaration + source.Append("partial struct"); + source.AppendLine("{"); + + // Constructor + source.AppendLine($"public {structSymbol.Name}("); + + // Parameters + var fieldSymbols = structSymbol.GetMembers().Where(symbol => symbol.Kind == SymbolKind.Field).Cast().ToImmutableArray(); + + source.AppendLine(string.Join($",{Environment.NewLine}", fieldSymbols.Select(field => $"{field.Type} {field.Name}"))); + + source.AppendLine(") { }"); + } + } + + /// + /// Created on demand before each generation pass + /// + private sealed class SyntaxReceiver : ISyntaxReceiver + { + /// + /// Gets the list of candidate struct declarations. + /// + public List CandidateTypes { get; } = new(); + + /// + public void OnVisitSyntaxNode(SyntaxNode syntaxNode) + { + // Track all structs with at least one attribute + if (syntaxNode is StructDeclarationSyntax structDeclarationSyntax && + structDeclarationSyntax.AttributeLists.Count > 0) + { + CandidateTypes.Add(structDeclarationSyntax); + } + } + } + } +} + diff --git a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj new file mode 100644 index 00000000..f9c83fae --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj @@ -0,0 +1,14 @@ + + + + netstandard2.0 + 9.0 + enable + + + + + + + + diff --git a/src/ComputeSharp/ComputeSharp.csproj b/src/ComputeSharp/ComputeSharp.csproj index 115ba122..469903e2 100644 --- a/src/ComputeSharp/ComputeSharp.csproj +++ b/src/ComputeSharp/ComputeSharp.csproj @@ -2,11 +2,16 @@ net5.0-windows10.0.19041.0 + preview enable +