diff --git a/src/ComputeSharp.SourceGenerators/Extensions/AttributeDataExtensions.cs b/src/ComputeSharp.SourceGenerators/Extensions/AttributeDataExtensions.cs
new file mode 100644
index 00000000..f51125ab
--- /dev/null
+++ b/src/ComputeSharp.SourceGenerators/Extensions/AttributeDataExtensions.cs
@@ -0,0 +1,37 @@
+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
index fadd122e..27ec7a6d 100644
--- a/src/ComputeSharp.SourceGenerators/FieldAttributeGenerator.cs
+++ b/src/ComputeSharp.SourceGenerators/FieldAttributeGenerator.cs
@@ -1,10 +1,10 @@
using System;
using System.Collections.Generic;
-using System.Collections.Immutable;
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;
@@ -26,7 +26,7 @@ namespace ComputeSharp.SourceGenerators
public void Execute(GeneratorExecutionContext context)
{
// Find all the [Field] usages
- var attributes = (
+ var attributes = new Queue>(
from tree in context.Compilation.SyntaxTrees
from structDeclaration in tree.GetRoot().DescendantNodes().OfType()
let semanticModel = context.Compilation.GetSemanticModel(structDeclaration.SyntaxTree)
@@ -34,7 +34,7 @@ namespace ComputeSharp.SourceGenerators
from attribute in structSymbol.GetAttributes()
where attribute.AttributeClass is { Name: nameof(FieldAttribute) }
group attribute by structSymbol into groups
- select groups).ToImmutableArray();
+ select groups);
foreach (IGrouping group in attributes)
{
@@ -42,7 +42,7 @@ namespace ComputeSharp.SourceGenerators
SemanticModel semanticModel = null!;// context.Compilation.GetSemanticModel(structDeclaration.SyntaxTree);
INamedTypeSymbol structDeclarationSymbol = null!;// semanticModel.GetDeclaredSymbol(structDeclaration)!;
- _ = GetFieldDeclarations(group).ToArray();
+ _ = GetProcessedFields(group);
// Extract the info on the type to process
var namespaceName = structDeclarationSymbol.ContainingNamespace.ToDisplayString(new(typeQualificationStyle: NameAndContainingTypesAndNamespaces));
@@ -87,14 +87,39 @@ namespace ComputeSharp.SourceGenerators
}
}
- private static IEnumerable GetFieldDeclarations(IEnumerable attributes)
+ ///
+ /// 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)
{
+ int 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 (!HlslKnownSizes.TryGetMappedSize(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(
@@ -102,11 +127,11 @@ namespace ComputeSharp.SourceGenerators
.AddVariables(VariableDeclarator(Identifier(fieldName))))
.AddAttributeLists(AttributeList(SingletonSeparatedList(
Attribute(IdentifierName(typeof(FieldOffsetAttribute).FullName)).AddArgumentListArguments(
- AttributeArgument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)))))))
+ AttributeArgument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(offset)))))))
.AddModifiers(Token(SyntaxKind.PublicKeyword));
// Add the XML tag, if a summary is present
- if (attribute.NamedArguments.FirstOrDefault(p => p.Key == nameof(FieldAttribute.Summary)).Value.Value is string summary)
+ if (attribute.TryGetNamedArgument(nameof(FieldAttribute.Summary), out string? summary))
{
fieldDeclaration =
fieldDeclaration.WithLeadingTrivia(
@@ -115,15 +140,29 @@ namespace ComputeSharp.SourceGenerators
List(new XmlNodeSyntax[]
{
XmlText().AddTextTokens(XmlTextLiteral(TriviaList(DocumentationCommentExterior("///")), " ", " ", TriviaList())),
- XmlExampleElement(SingletonList(XmlText().AddTextTokens(XmlTextLiteral("Foo bar baz"))))
+ XmlExampleElement(SingletonList(XmlText().AddTextTokens(XmlTextLiteral(summary!))))
.WithStartTag(XmlElementStartTag(XmlName(Identifier("summary"))))
.WithEndTag(XmlElementEndTag(XmlName(Identifier("summary")))),
XmlText().AddTextTokens(XmlTextNewLine("\n", false))
})))));
}
- yield return null!;
+ fieldDeclarations.Add(fieldDeclaration);
}
+
+ // 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(8)))
+ .WithNameEquals(NameEquals(IdentifierName(nameof(StructLayoutAttribute.Size)))),
+ AttributeArgument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(16)))
+ .WithNameEquals(NameEquals(IdentifierName(nameof(StructLayoutAttribute.Pack)))));
+
+ return (layoutAttribute, fieldDeclarations);
}
}
}
diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownSizes.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownSizes.cs
index d7c70573..b8f86680 100644
--- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownSizes.cs
+++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownSizes.cs
@@ -46,13 +46,13 @@ namespace ComputeSharp.SourceGenerators.Mappings
};
///
- /// Tries to get the mapped HLSL size and alignment for the input type name.
+ /// Tries to get the mapped HLSL size and packing for the input type name.
///
/// The input fully qualified type name.
/// The mapped name, if one is found.
- /// The HLSL size and alignment that can be used in an HLSL shader.
+ /// The HLSL size and packing that can be used in an HLSL shader.
[Pure]
- public static bool TryGetMappedSize(string name, out (int Size, int Alignment) mapped)
+ public static bool TryGetMappedSize(string name, out (int Size, int Pack) mapped)
{
return KnownSizes.TryGetValue(name, out mapped);
}