diff --git a/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md
new file mode 100644
index 00000000..054a5960
--- /dev/null
+++ b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md
@@ -0,0 +1,2 @@
+; Shipped analyzer releases
+; https://github.com/dotnet/roslyn-analyzers/blob/master/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md
\ No newline at end of file
diff --git a/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Unshipped.md b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Unshipped.md
new file mode 100644
index 00000000..6d879574
--- /dev/null
+++ b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Unshipped.md
@@ -0,0 +1,43 @@
+; Unshipped analyzer release
+; https://github.com/dotnet/roslyn-analyzers/blob/master/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md
+
+### New Rules
+
+Rule ID | Category | Severity | Notes
+--------|----------|----------|-------
+CMPS0001 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPS0002 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPS0003 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPS0004 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPS0005 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPS0006 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPS0007 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPS0008 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPS0009 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPS0010 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPS0011 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPS0012 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPS0013 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPS0014 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPS0015 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPS0016 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPS0017 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPS0018 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPS0019 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPS0020 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPS0021 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPS0022 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPS0023 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPS0024 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPS0025 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPS0026 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPS0027 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPS0028 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPS0029 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPS0030 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPS0031 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPS0032 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPS0033 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPS0034 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPS0035 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPS0036 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
\ No newline at end of file
diff --git a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj
index b044bc0e..b968ac10 100644
--- a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj
+++ b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj
@@ -48,7 +48,7 @@
-
+
diff --git a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs
new file mode 100644
index 00000000..50676fd5
--- /dev/null
+++ b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs
@@ -0,0 +1,511 @@
+using Microsoft.CodeAnalysis;
+
+namespace ComputeSharp.SourceGenerators.Diagnostics
+{
+ ///
+ /// A container for all instances for errors reported by analyzers in this project.
+ ///
+ internal static class DiagnosticDescriptors
+ {
+ ///
+ /// Gets a for an invalid shader field.
+ ///
+ /// Format: "The compute shader of type {0} contains a field \"{1}\" of an invalid type {2}".
+ ///
+ ///
+ public static DiagnosticDescriptor InvalidShaderField { get; } = new(
+ id: "CMPS0001",
+ title: "Invalid shader field",
+ messageFormat: "The compute shader of type {0} contains a field \"{1}\" of an invalid type {2}",
+ category: typeof(IComputeShader).FullName,
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "A type representing a compute shader contains a field of a type that is not supported in HLSL.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for an invalid group shared field type.
+ ///
+ /// Format: "The compute shader of type {0} contains a group shared field \"{1}\" of an invalid type {2}".
+ ///
+ ///
+ public static DiagnosticDescriptor InvalidGroupSharedFieldType { get; } = new(
+ id: "CMPS0002",
+ title: "Invalid group shared field type",
+ messageFormat: "The compute shader of type {0} contains a group shared field \"{1}\" of an invalid type {2} (it must be an array)",
+ category: typeof(IComputeShader).FullName,
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "A group shared field must be of an array type.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for an invalid group shared field element type.
+ ///
+ /// Format: "The compute shader of type {0} contains a group shared field \"{1}\" of an invalid element type {2}".
+ ///
+ ///
+ public static DiagnosticDescriptor InvalidGroupSharedFieldElementType { get; } = new(
+ id: "CMPS0003",
+ title: "Invalid group shared field element type",
+ messageFormat: "The compute shader of type {0} contains a group shared field \"{1}\" of an invalid type {2} (it must be a primitive or unmanaged type)",
+ category: typeof(IComputeShader).FullName,
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "A group shared field element must be of a primitive or unmanaged type.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for an invalid group shared field declaration.
+ ///
+ /// Format: "The compute shader of type {0} contains a group shared field \"{1}\" that is not static".
+ ///
+ ///
+ public static DiagnosticDescriptor InvalidGroupSharedFieldDeclaration { get; } = new(
+ id: "CMPS0004",
+ title: "Invalid group shared field declaration",
+ messageFormat: "The compute shader of type {0} contains a group shared field \"{1}\" that is not static",
+ category: typeof(IComputeShader).FullName,
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "A group shared field must be static.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for a shader with no resources.
+ ///
+ /// Format: "The compute shader of type {0} contains no resources to work on".
+ ///
+ ///
+ public static DiagnosticDescriptor MissingShaderResources { get; } = new(
+ id: "CMPS0005",
+ title: "Missing shader resources",
+ messageFormat: "The compute shader of type {0} contains no resources to work on",
+ category: typeof(IComputeShader).FullName,
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "A compute shader must contain at least one resource.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for an invalid usage.
+ ///
+ /// Format: "The ThreadIds type is used in method {0} of type {1}".
+ ///
+ ///
+ public static DiagnosticDescriptor InvalidThreadIdsUsage { get; } = new(
+ id: "CMPS0006",
+ title: "Invalid ThreadIds usage",
+ messageFormat: "The ThreadIds type can only be used within the main body of a compute shader",
+ category: typeof(IComputeShader).FullName,
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "The ThreadIds type can only be used within the main body of a compute shader.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for an invalid usage.
+ ///
+ /// Format: "The GroupIds type is used in method {0} of type {1}".
+ ///
+ ///
+ public static DiagnosticDescriptor InvalidGroupIdsUsage { get; } = new(
+ id: "CMPS0007",
+ title: "Invalid GroupIds usage",
+ messageFormat: "The GroupIds type can only be used within the main body of a compute shader",
+ category: typeof(IComputeShader).FullName,
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "The GroupIds type can only be used within the main body of a compute shader.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for an invalid usage.
+ ///
+ /// Format: "The GroupSize type is used in method {0} of type {1}".
+ ///
+ ///
+ public static DiagnosticDescriptor InvalidGroupSizeUsage { get; } = new(
+ id: "CMPS0008",
+ title: "Invalid GroupSize usage",
+ messageFormat: "The GroupSize type can only be used within the main body of a compute shader",
+ category: typeof(IComputeShader).FullName,
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "The GroupSize type can only be used within the main body of a compute shader.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for an invalid usage.
+ ///
+ /// Format: "The WarpIds type is used in method {0} of type {1}".
+ ///
+ ///
+ public static DiagnosticDescriptor InvalidWarpIdsUsage { get; } = new(
+ id: "CMPS0009",
+ title: "Invalid WarpIds usage",
+ messageFormat: "The WarpIds type can only be used within the main body of a compute shader",
+ category: typeof(IComputeShader).FullName,
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "The WarpIds type can only be used within the main body of a compute shader.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for an invalid object creation expression.
+ ///
+ /// Format: "The type {0} cannot be created in a compute shader".
+ ///
+ ///
+ public static DiagnosticDescriptor InvalidObjectCreationExpression { get; } = new(
+ id: "CMPS0010",
+ title: "Invalid object creation expression",
+ messageFormat: "The type {0} cannot be created in a compute shader (only unmanaged types are supported)",
+ category: typeof(IComputeShader).FullName,
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "Only unmanaged value type objects can be created in a compute shader.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for an anonymous object creation expression.
+ ///
+ public static DiagnosticDescriptor AnonymousObjectCreationExpression { get; } = new(
+ id: "CMPS0011",
+ title: "Anonymous object creation expression",
+ messageFormat: "An anonymous object cannot be created in a compute shader",
+ category: typeof(IComputeShader).FullName,
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "An anonymous object cannot be created in a compute shader.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for an async modifier on a method or function.
+ ///
+ public static DiagnosticDescriptor AsyncModifierOnMethodOrFunction { get; } = new(
+ id: "CMPS0012",
+ title: "Async modifier on method or function",
+ messageFormat: "The async modifier cannot be used in methods or functions used in a compute shader",
+ category: typeof(IComputeShader).FullName,
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "The async modifier cannot be used in methods or functions used in a compute shader.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for an await expression.
+ ///
+ public static DiagnosticDescriptor AwaitExpression { get; } = new(
+ id: "CMPS0013",
+ title: "Await expression",
+ messageFormat: "The await expression cannot be used in a compute shader",
+ category: typeof(IComputeShader).FullName,
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "The await expression cannot be used in a compute shader.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for a checked expression.
+ ///
+ public static DiagnosticDescriptor CheckedExpression { get; } = new(
+ id: "CMPS0014",
+ title: "Checked expression",
+ messageFormat: "A checked expression cannot be used in a compute shader",
+ category: typeof(IComputeShader).FullName,
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "A checked expression cannot be used in a compute shader.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for a checked statement.
+ ///
+ public static DiagnosticDescriptor CheckedStatement { get; } = new(
+ id: "CMPS0015",
+ title: "Checked statement",
+ messageFormat: "A checked statement cannot be used in a compute shader",
+ category: typeof(IComputeShader).FullName,
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "A checked statement cannot be used in a compute shader.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for a fixed statement.
+ ///
+ public static DiagnosticDescriptor FixedStatement { get; } = new(
+ id: "CMPS0016",
+ title: "Fixed statement",
+ messageFormat: "A fixed statement cannot be used in a compute shader",
+ category: typeof(IComputeShader).FullName,
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "A fixed statement cannot be used in a compute shader.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for a foreach statement.
+ ///
+ public static DiagnosticDescriptor ForEachStatement { get; } = new(
+ id: "CMPS0017",
+ title: "Foreach statement",
+ messageFormat: "A foreach statement cannot be used in a compute shader",
+ category: typeof(IComputeShader).FullName,
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "A foreach statement cannot be used in a compute shader.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for a lock statement.
+ ///
+ public static DiagnosticDescriptor LockStatement { get; } = new(
+ id: "CMPS0018",
+ title: "Foreach statement",
+ messageFormat: "A lock statement cannot be used in a compute shader",
+ category: typeof(IComputeShader).FullName,
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "A lock statement cannot be used in a compute shader.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for a query statement.
+ ///
+ public static DiagnosticDescriptor QueryExpression { get; } = new(
+ id: "CMPS0019",
+ title: "Foreach statement",
+ messageFormat: "A LINQ query expression cannot be used in a compute shader",
+ category: typeof(IComputeShader).FullName,
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "A LINQ query expression cannot be used in a compute shader.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for a range expression.
+ ///
+ public static DiagnosticDescriptor RangeExpression { get; } = new(
+ id: "CMPS0020",
+ title: "Range expression",
+ messageFormat: "A range expression cannot be used in a compute shader",
+ category: typeof(IComputeShader).FullName,
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "A range expression cannot be used in a compute shader.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for a recursive pattern.
+ ///
+ public static DiagnosticDescriptor RecursivePattern { get; } = new(
+ id: "CMPS0021",
+ title: "Recursive pattern",
+ messageFormat: "A recursive pattern cannot be used in a compute shader",
+ category: typeof(IComputeShader).FullName,
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "A recursive pattern cannot be used in a compute shader.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for a ref type.
+ ///
+ public static DiagnosticDescriptor RefType { get; } = new(
+ id: "CMPS0022",
+ title: "Ref type",
+ messageFormat: "A compute shader cannot have a ref type declaration",
+ category: typeof(IComputeShader).FullName,
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "A compute shader cannot have a ref type declaration.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for a relational pattern.
+ ///
+ public static DiagnosticDescriptor RelationalPattern { get; } = new(
+ id: "CMPS0023",
+ title: "Relational pattern",
+ messageFormat: "A relational pattern cannot be used in a compute shader",
+ category: typeof(IComputeShader).FullName,
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "A relational pattern cannot be used in a compute shader.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for a sizeof expression.
+ ///
+ public static DiagnosticDescriptor SizeOfExpression { get; } = new(
+ id: "CMPS0024",
+ title: "Sizeof expression",
+ messageFormat: "A sizeof expression cannot be used in a compute shader",
+ category: typeof(IComputeShader).FullName,
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "A sizeof expression cannot be used in a compute shader.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for a stackalloc expression.
+ ///
+ public static DiagnosticDescriptor StackAllocArrayCreationExpression { get; } = new(
+ id: "CMPS0025",
+ title: "Stackalloc expression",
+ messageFormat: "A stackalloc expression cannot be used in a compute shader",
+ category: typeof(IComputeShader).FullName,
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "A stackalloc expression cannot be used in a compute shader.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for a throw expression or statement.
+ ///
+ public static DiagnosticDescriptor ThrowExpressionOrStatement { get; } = new(
+ id: "CMPS0026",
+ title: "Throw expression or statement",
+ messageFormat: "Throw expressions and statements cannot be used in a compute shader",
+ category: typeof(IComputeShader).FullName,
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "Throw expressions and statements cannot be used in a compute shader.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for a try statement.
+ ///
+ public static DiagnosticDescriptor TryStatement { get; } = new(
+ id: "CMPS0027",
+ title: "Try statement",
+ messageFormat: "A try statement cannot be used in a compute shader",
+ category: typeof(IComputeShader).FullName,
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "A try statement cannot be used in a compute shader.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for a tuple type.
+ ///
+ public static DiagnosticDescriptor TupleType { get; } = new(
+ id: "CMPS0028",
+ title: "Tuple type",
+ messageFormat: "A compute shader cannot have a tuple type declaration",
+ category: typeof(IComputeShader).FullName,
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "A compute shader cannot have a tuple type declaration.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for a using statement or declaration.
+ ///
+ public static DiagnosticDescriptor UsingStatementOrDeclaration { get; } = new(
+ id: "CMPS0029",
+ title: "Using statement or declaration",
+ messageFormat: "Using statements and declarations cannot be used in a compute shader",
+ category: typeof(IComputeShader).FullName,
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "Using statements and declarations cannot be used in a compute shader.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for a yield statement.
+ ///
+ public static DiagnosticDescriptor YieldStatement { get; } = new(
+ id: "CMPS0030",
+ title: "Yield statement",
+ messageFormat: "A yield statement cannot be used in a compute shader",
+ category: typeof(IComputeShader).FullName,
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "A yield statement cannot be used in a compute shader.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for an invalid object declaration.
+ ///
+ /// Format: "A variable of type {0} cannot be declared in a compute shader".
+ ///
+ ///
+ public static DiagnosticDescriptor InvalidObjectDeclaration { get; } = new(
+ id: "CMPS0031",
+ title: "Invalid object declaration",
+ messageFormat: "A variable of type {0} cannot be declared in a compute shader (only unmanaged types are supported)",
+ category: typeof(IComputeShader).FullName,
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "Only unmanaged value type objects can be declared in a compute shader.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for a pointer type.
+ ///
+ public static DiagnosticDescriptor PointerType { get; } = new(
+ id: "CMPS0032",
+ title: "Pointer type",
+ messageFormat: "A compute shader cannot have a pointer type declaration",
+ category: typeof(IComputeShader).FullName,
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "A compute shader cannot have a pointer type declaration.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for a function pointer type.
+ ///
+ public static DiagnosticDescriptor FunctionPointer { get; } = new(
+ id: "CMPS0033",
+ title: "Function pointer type",
+ messageFormat: "A compute shader cannot have a function pointer type declaration",
+ category: typeof(IComputeShader).FullName,
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "A compute shader cannot have a function pointer type declaration.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for an unsafe statement.
+ ///
+ public static DiagnosticDescriptor UnsafeStatement { get; } = new(
+ id: "CMPS0034",
+ title: "Unsafe statement",
+ messageFormat: "A compute shader cannot have an unsafe statement",
+ category: typeof(IComputeShader).FullName,
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "A compute shader cannot have an unsafe statement.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for an unsafe modifier on a method or function.
+ ///
+ public static DiagnosticDescriptor UnsafeModifierOnMethodOrFunction { get; } = new(
+ id: "CMPS0035",
+ title: "Unsafe modifier on method or function",
+ messageFormat: "The unsafe modifier cannot be used in methods or functions used in a compute shader",
+ category: typeof(IComputeShader).FullName,
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "The unsafe modifier cannot be used in methods or functions used in a compute shader.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for a string literal.
+ ///
+ public static DiagnosticDescriptor StringLiteralExpression { get; } = new(
+ id: "CMPS0036",
+ title: "String literal expression",
+ messageFormat: "String literal expressions cannot be used in a compute shader",
+ category: typeof(IComputeShader).FullName,
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "String literal expressions cannot be used in a compute shader.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+ }
+}
diff --git a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticsExtensions.cs b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticsExtensions.cs
new file mode 100644
index 00000000..e9509100
--- /dev/null
+++ b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticsExtensions.cs
@@ -0,0 +1,43 @@
+using System.Linq;
+using Microsoft.CodeAnalysis;
+
+namespace ComputeSharp.SourceGenerators.Diagnostics
+{
+ ///
+ /// Extension methods for , specifically for reporting diagnostics.
+ ///
+ internal static class DiagnosticsExtensions
+ {
+ ///
+ /// Adds a new diagnostics to the current compilation.
+ ///
+ /// The instance currently in use.
+ /// The input for the diagnostics to create.
+ /// The source to attach the diagnostics to.
+ /// The optional arguments for the formatted message to include.
+ public static void ReportDiagnostic(
+ this GeneratorExecutionContext context,
+ DiagnosticDescriptor descriptor,
+ ISymbol symbol,
+ params object[] args)
+ {
+ context.ReportDiagnostic(Diagnostic.Create(descriptor, symbol.Locations.FirstOrDefault(), args));
+ }
+
+ ///
+ /// Adds a new diagnostics to the current compilation.
+ ///
+ /// The instance currently in use.
+ /// The input for the diagnostics to create.
+ /// The source to attach the diagnostics to.
+ /// The optional arguments for the formatted message to include.
+ public static void ReportDiagnostic(
+ this GeneratorExecutionContext context,
+ DiagnosticDescriptor descriptor,
+ SyntaxNode node,
+ params object[] args)
+ {
+ context.ReportDiagnostic(Diagnostic.Create(descriptor, node.GetLocation(), args));
+ }
+ }
+}
diff --git a/src/ComputeSharp.SourceGenerators/Extensions/ISymbolExtensions.cs b/src/ComputeSharp.SourceGenerators/Extensions/ISymbolExtensions.cs
index e08f19e8..e84e89ad 100644
--- a/src/ComputeSharp.SourceGenerators/Extensions/ISymbolExtensions.cs
+++ b/src/ComputeSharp.SourceGenerators/Extensions/ISymbolExtensions.cs
@@ -31,12 +31,12 @@ namespace ComputeSharp.SourceGenerators.Extensions
.WithParameterOptions(SymbolDisplayParameterOptions.None);
///
- /// Gets the full metadata name for a given instance.
+ /// Gets the full metadata name for a given instance.
///
- /// The input instance.
+ /// The input instance.
/// The full metadata name for .
[Pure]
- public static string GetFullMetadataName(this INamedTypeSymbol symbol)
+ public static string GetFullMetadataName(this ITypeSymbol symbol)
{
static StringBuilder BuildFrom(ISymbol? symbol, StringBuilder builder)
{
diff --git a/src/ComputeSharp.SourceGenerators/Extensions/SyntaxNodeExtensions.cs b/src/ComputeSharp.SourceGenerators/Extensions/SyntaxNodeExtensions.cs
index 77831764..86418169 100644
--- a/src/ComputeSharp.SourceGenerators/Extensions/SyntaxNodeExtensions.cs
+++ b/src/ComputeSharp.SourceGenerators/Extensions/SyntaxNodeExtensions.cs
@@ -44,7 +44,20 @@ namespace ComputeSharp.SourceGenerators.Extensions
public static TRoot ReplaceAndTrackType(this TRoot node, TypeSyntax targetType, SyntaxNode sourceType, SemanticModel semanticModel, ICollection discoveredTypes)
where TRoot : SyntaxNode
{
- ITypeSymbol typeSymbol = semanticModel.GetTypeInfo(sourceType).Type!;
+ // Skip immediately for function pointers
+ if (sourceType is FunctionPointerTypeSyntax)
+ {
+ return node.ReplaceNode(targetType, ParseTypeName("void*"));
+ }
+
+ // Handle the various possible type kinds
+ ITypeSymbol typeSymbol = sourceType switch
+ {
+ RefTypeSyntax refType => semanticModel.GetTypeInfo(refType.Type).Type!,
+ PointerTypeSyntax pointerType => semanticModel.GetTypeInfo(pointerType.ElementType).Type!,
+ _ => semanticModel.GetTypeInfo(sourceType).Type!
+ };
+
string typeName = typeSymbol.ToDisplayString(ISymbolExtensions.FullyQualifiedWithoutGlobalFormat);
discoveredTypes.Add((INamedTypeSymbol)typeSymbol);
diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs
index 028d7ed4..e7bc5c2d 100644
--- a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs
+++ b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs
@@ -141,9 +141,11 @@ namespace ComputeSharp.SourceGenerators
foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType())
{
- if (fieldSymbol.IsStatic) continue;
+ if (fieldSymbol.Type is not INamedTypeSymbol { IsStatic: false } typeSymbol)
+ {
+ continue;
+ }
- INamedTypeSymbol typeSymbol = (INamedTypeSymbol)fieldSymbol.Type;
string typeName = typeSymbol.GetFullMetadataName();
if (HlslKnownTypes.IsTypedResourceType(typeName))
diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs
index 127677c7..b5dad985 100644
--- a/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs
+++ b/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs
@@ -120,11 +120,10 @@ namespace ComputeSharp.SourceGenerators
{
foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType())
{
- if (fieldSymbol.IsStatic) continue;
-
- INamedTypeSymbol typeSymbol = (INamedTypeSymbol)fieldSymbol.Type;
-
- if (typeSymbol.TypeKind != TypeKind.Delegate) continue;
+ if (fieldSymbol.Type is not INamedTypeSymbol { TypeKind: TypeKind.Delegate, IsStatic: false } typeSymbol)
+ {
+ continue;
+ }
// hash += hash << 5;
yield return ExpressionStatement(ParseExpression($"hash += hash << 5"));
diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs
index 05ec04c3..c7e4f57f 100644
--- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs
+++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs
@@ -4,6 +4,7 @@ using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using ComputeSharp.__Internals;
+using ComputeSharp.SourceGenerators.Diagnostics;
using ComputeSharp.SourceGenerators.Extensions;
using ComputeSharp.SourceGenerators.Mappings;
using ComputeSharp.SourceGenerators.SyntaxRewriters;
@@ -13,6 +14,7 @@ using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
using static ComputeSharp.SourceGenerators.Helpers.SyntaxFactoryHelper;
+using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors;
#pragma warning disable CS0618
@@ -49,9 +51,9 @@ namespace ComputeSharp.SourceGenerators
Dictionary constantDefinitions = new(SymbolEqualityComparer.Default);
// Explore the syntax tree and extract the processed info
- var processedMembers = GetProcessedMembers(structDeclarationSymbol, discoveredTypes).ToArray();
- var sharedBuffers = GetGroupSharedMembers(structDeclarationSymbol, discoveredTypes).ToArray();
- var (entryPoint, localFunctions) = GetProcessedMethods(structDeclaration, structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods, constantDefinitions);
+ var processedMembers = GetProcessedMembers(context, structDeclarationSymbol, discoveredTypes).ToArray();
+ var sharedBuffers = GetGroupSharedMembers(context, structDeclarationSymbol, discoveredTypes).ToArray();
+ var (entryPoint, localFunctions) = GetProcessedMethods(context, structDeclaration, structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods, constantDefinitions);
var processedTypes = GetProcessedTypes(discoveredTypes).ToArray();
var processedMethods = localFunctions.Concat(staticMethods.Values).Select(static method => method.NormalizeWhitespace().ToFullString()).ToArray();
var processedConstants = GetProcessedConstants(constantDefinitions);
@@ -82,17 +84,59 @@ namespace ComputeSharp.SourceGenerators
///
/// Gets a sequence of captured members and their mapped names.
///
+ /// The current generator context in use.
/// The input instance to process.
/// The collection of currently discovered types.
/// A sequence of captured members in .
[Pure]
- private static IEnumerable> GetProcessedMembers(INamedTypeSymbol structDeclarationSymbol, ICollection types)
+ private static IEnumerable> GetProcessedMembers(
+ GeneratorExecutionContext context,
+ INamedTypeSymbol structDeclarationSymbol,
+ ICollection types)
{
+ bool hlslResourceFound = false;
+
foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType())
{
if (fieldSymbol.IsStatic) continue;
- INamedTypeSymbol typeSymbol = (INamedTypeSymbol)fieldSymbol.Type;
+ AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) });
+
+ // Group shared fields must be static
+ if (attribute is not null)
+ {
+ context.ReportDiagnostic(InvalidGroupSharedFieldDeclaration, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name);
+ }
+
+ // Captured fields must be named type symbols
+ if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol)
+ {
+ context.ReportDiagnostic(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type);
+
+ continue;
+ }
+
+ string metadataName = typeSymbol.GetFullMetadataName();
+
+ // Allowed fields must be either resources, unmanaged values or delegates
+ if (HlslKnownTypes.IsTypedResourceType(metadataName))
+ {
+ hlslResourceFound = true;
+
+ // Track the type of items in the current buffer
+ if (HlslKnownTypes.IsStructuredBufferType(metadataName))
+ {
+ types.Add((INamedTypeSymbol)typeSymbol.TypeArguments[0]);
+ }
+ }
+ else if (!typeSymbol.IsUnmanagedType &&
+ typeSymbol.TypeKind != TypeKind.Delegate)
+ {
+ // Shaders can only capture valid HLSL resource types or unmanaged types
+ context.ReportDiagnostic(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, typeSymbol);
+
+ continue;
+ }
string typeName = HlslKnownTypes.GetMappedName(typeSymbol);
@@ -100,32 +144,50 @@ namespace ComputeSharp.SourceGenerators
// Yield back the current mapping for the name (if the name used a reserved keyword)
yield return new[] { fieldSymbol.Name, mapping ?? fieldSymbol.Name, typeName };
+ }
- // Track the type of items in the current buffer
- if (HlslKnownTypes.IsTypedResourceType(typeSymbol.GetFullMetadataName()) &&
- typeSymbol.TypeArguments.Length == 1)
- {
- types.Add((INamedTypeSymbol)typeSymbol.TypeArguments[0]);
- }
+ if (!hlslResourceFound)
+ {
+ context.ReportDiagnostic(MissingShaderResources, structDeclarationSymbol, structDeclarationSymbol);
}
}
///
/// Gets a sequence of captured members and their mapped names.
///
+ /// The current generator context in use.
/// The input instance to process.
/// The collection of currently discovered types.
/// A sequence of captured members in .
[Pure]
- private static IEnumerable<(string Name, string Type, int? Count)> GetGroupSharedMembers(INamedTypeSymbol structDeclarationSymbol, ICollection types)
+ private static IEnumerable<(string Name, string Type, int? Count)> GetGroupSharedMembers(
+ GeneratorExecutionContext context,
+ INamedTypeSymbol structDeclarationSymbol,
+ ICollection types)
{
foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType())
{
if (!fieldSymbol.IsStatic) continue;
- AttributeData attribute = fieldSymbol.GetAttributes().First(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) });
+ AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) });
+
+ if (attribute is null) continue;
+
+ if (fieldSymbol.Type is not IArrayTypeSymbol typeSymbol)
+ {
+ context.ReportDiagnostic(InvalidGroupSharedFieldType, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type);
+
+ continue;
+ }
+
+ if (!typeSymbol.ElementType.IsUnmanagedType)
+ {
+ context.ReportDiagnostic(InvalidGroupSharedFieldElementType, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type);
+
+ continue;
+ }
+
int? bufferSize = (int?)attribute.ConstructorArguments.FirstOrDefault().Value;
- IArrayTypeSymbol typeSymbol = (IArrayTypeSymbol)fieldSymbol.Type;
string typeName = HlslKnownTypes.GetMappedElementName(typeSymbol);
@@ -140,6 +202,7 @@ namespace ComputeSharp.SourceGenerators
///
/// Gets a sequence of processed methods declared within a given type.
///
+ /// The current generator context in use.
/// The type symbol for the shader type.
/// The instance for the current type.
/// The instance for the type to process.
@@ -149,6 +212,7 @@ namespace ComputeSharp.SourceGenerators
/// A sequence of processed methods in , and the entry point.
[Pure]
private static (string EntryPoint, IEnumerable Methods) GetProcessedMethods(
+ GeneratorExecutionContext context,
StructDeclarationSyntax structDeclaration,
INamedTypeSymbol structDeclarationSymbol,
SemanticModel semanticModel,
@@ -168,16 +232,27 @@ namespace ComputeSharp.SourceGenerators
foreach (MethodDeclarationSyntax methodDeclaration in methodDeclarations)
{
IMethodSymbol methodDeclarationSymbol = semanticModel.GetDeclaredSymbol(methodDeclaration)!;
- ShaderSourceRewriter shaderSourceRewriter = new(structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods, constantDefinitions);
+ bool isShaderEntryPoint =
+ methodDeclarationSymbol.Name == nameof(IComputeShader.Execute) &&
+ methodDeclarationSymbol.ReturnsVoid &&
+ methodDeclarationSymbol.TypeParameters.Length == 0 &&
+ methodDeclarationSymbol.Parameters.Length == 0;
+
+ // Create the source rewriter for the current method
+ ShaderSourceRewriter shaderSourceRewriter = new(
+ structDeclarationSymbol,
+ semanticModel,
+ discoveredTypes,
+ staticMethods,
+ constantDefinitions,
+ context,
+ isShaderEntryPoint);
// Rewrite the method syntax tree
MethodDeclarationSyntax? processedMethod = shaderSourceRewriter.Visit(methodDeclaration)!.WithoutTrivia();
// If the method is the shader entry point, do additional processing
- if (methodDeclarationSymbol.Name == nameof(IComputeShader.Execute) &&
- methodDeclarationSymbol.ReturnsVoid &&
- methodDeclarationSymbol.TypeParameters.Length == 0 &&
- methodDeclarationSymbol.Parameters.Length == 0)
+ if (isShaderEntryPoint)
{
processedMethod = new ExecuteMethodRewriter(shaderSourceRewriter).Visit(processedMethod)!;
diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs
index c6716afd..f9e79082 100644
--- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs
+++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs
@@ -66,6 +66,23 @@ namespace ComputeSharp.SourceGenerators.Mappings
typeof(WarpIds)
};
+ ///
+ /// Checks whether or not a given type name matches a structured buffer type.
+ ///
+ /// The input type name to check.
+ /// Whether or not represents a structured buffer type.
+ public static bool IsStructuredBufferType(string typeName)
+ {
+ switch (typeName)
+ {
+ case "ComputeSharp.ConstantBuffer`1":
+ case "ComputeSharp.ReadOnlyBuffer`1":
+ case "ComputeSharp.ReadWriteBuffer`1":
+ return true;
+ default: return false;
+ };
+ }
+
///
/// Checks whether or not a given type name matches a typed resource type.
///
@@ -195,10 +212,12 @@ namespace ComputeSharp.SourceGenerators.Mappings
{
if (KnownTypes.ContainsKey(type.GetFullMetadataName())) return;
- customTypes.Add(type);
+ if (!customTypes.Add(type)) return;
foreach (var field in type.GetMembers().OfType())
{
+ if (field.IsStatic) continue;
+
ExploreTypes((INamedTypeSymbol)field.Type, customTypes);
}
}
@@ -238,6 +257,8 @@ namespace ComputeSharp.SourceGenerators.Mappings
// Only add other custom types as dependencies, and ignore HLSL types
foreach (var field in type.GetMembers().OfType())
{
+ if (field.IsStatic) continue;
+
INamedTypeSymbol fieldType = (INamedTypeSymbol)field.Type;
if (!KnownTypes.ContainsKey(fieldType.GetFullMetadataName()))
diff --git a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs
index 6d817f4b..2bdf88e4 100644
--- a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs
+++ b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs
@@ -48,7 +48,7 @@ namespace ComputeSharp.SourceGenerators
Dictionary constantDefinitions = new(SymbolEqualityComparer.Default);
// Explore the syntax tree and extract the processed info
- var (invokeMethod, processedMethods) = GetProcessedMethods(methodDeclaration, semanticModel, discoveredTypes, staticMethods, constantDefinitions);
+ var (invokeMethod, processedMethods) = GetProcessedMethods(context, methodDeclaration, semanticModel, discoveredTypes, staticMethods, constantDefinitions);
var processedTypes = IComputeShaderSourceGenerator.GetProcessedTypes(discoveredTypes).ToArray();
var processedConstants = IComputeShaderSourceGenerator.GetProcessedConstants(constantDefinitions);
@@ -75,6 +75,7 @@ namespace ComputeSharp.SourceGenerators
///
/// Gets a sequence of processed methods from a target method declaration.
///
+ /// The current generator context in use.
/// The instance for the current method.
/// The instance for the method to process.
/// The collection of currently discovered types.
@@ -83,13 +84,14 @@ namespace ComputeSharp.SourceGenerators
/// A sequence of processed methods in .
[Pure]
private static (string InvokeMethod, IEnumerable Methods) GetProcessedMethods(
+ GeneratorExecutionContext context,
MethodDeclarationSyntax methodDeclaration,
SemanticModel semanticModel,
ICollection discoveredTypes,
IDictionary staticMethods,
IDictionary constantDefinitions)
{
- ShaderSourceRewriter shaderSourceRewriter = new(semanticModel, discoveredTypes, staticMethods, constantDefinitions);
+ ShaderSourceRewriter shaderSourceRewriter = new(semanticModel, discoveredTypes, staticMethods, constantDefinitions, context);
// Rewrite the method syntax tree
var processedMethod = shaderSourceRewriter
diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs
index 5c40b29d..38cf34f3 100644
--- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs
+++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs
@@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
+using ComputeSharp.SourceGenerators.Diagnostics;
using ComputeSharp.SourceGenerators.Extensions;
using ComputeSharp.SourceGenerators.Mappings;
using Microsoft.CodeAnalysis;
@@ -9,6 +10,7 @@ using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Operations;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
+using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors;
namespace ComputeSharp.SourceGenerators.SyntaxRewriters
{
@@ -52,11 +54,26 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
///
private readonly List implicitVariables;
+ ///
+ /// The current generator context in use.
+ ///
+ private readonly GeneratorExecutionContext context;
+
+ ///
+ /// Whether or not the current instance is processing a shader entry point.
+ ///
+ private readonly bool isEntryPoint;
+
///
/// The current tree being visited.
///
private MethodDeclarationSyntax? currentMethod;
+ ///
+ /// The current depth inside local declarations.
+ ///
+ private int localFunctionDepth;
+
///
/// Creates a new instance with the specified parameters.
///
@@ -65,12 +82,16 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
/// The set of discovered custom types.
/// The set of discovered and processed static methods.
/// The collection of discovered constant definitions.
+ /// The current generator context in use.
+ /// Whether or not the current instance is processing a shader entry point.
public ShaderSourceRewriter(
INamedTypeSymbol shaderType,
SemanticModel semanticModel,
ICollection discoveredTypes,
IDictionary staticMethods,
- IDictionary constantDefinitions)
+ IDictionary constantDefinitions,
+ GeneratorExecutionContext context,
+ bool isEntryPoint)
{
this.shaderType = shaderType;
this.semanticModel = semanticModel;
@@ -79,6 +100,8 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
this.constantDefinitions = constantDefinitions;
this.localFunctions = new();
this.implicitVariables = new();
+ this.context = context;
+ this.isEntryPoint = isEntryPoint;
}
///
@@ -88,11 +111,13 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
/// The set of discovered custom types.
/// The set of discovered and processed static methods.
/// The collection of discovered constant definitions.
+ /// The current generator context in use.
public ShaderSourceRewriter(
SemanticModel semanticModel,
ICollection discoveredTypes,
IDictionary staticMethods,
- IDictionary constantDefinitions)
+ IDictionary constantDefinitions,
+ GeneratorExecutionContext context)
{
this.semanticModel = semanticModel;
this.discoveredTypes = discoveredTypes;
@@ -100,6 +125,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
this.constantDefinitions = constantDefinitions;
this.implicitVariables = new();
this.localFunctions = new();
+ this.context = context;
}
///
@@ -129,6 +155,16 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
var updatedNode = (MethodDeclarationSyntax?)base.Visit(node);
+ if (node!.Modifiers.Any(m => m.IsKind(SyntaxKind.AsyncKeyword)))
+ {
+ this.context.ReportDiagnostic(AsyncModifierOnMethodOrFunction, node);
+ }
+
+ if (node!.Modifiers.Any(m => m.IsKind(SyntaxKind.UnsafeKeyword)))
+ {
+ this.context.ReportDiagnostic(UnsafeModifierOnMethodOrFunction, node);
+ }
+
if (updatedNode is not null)
{
var implicitBlock = Block(this.implicitVariables.Select(static v => LocalDeclarationStatement(v)).ToArray());
@@ -176,6 +212,11 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
{
var updatedNode = ((LocalDeclarationStatementSyntax)base.VisitLocalDeclarationStatement(node)!);
+ if (this.semanticModel.GetOperation(node) is IOperation { Kind: OperationKind.UsingDeclaration })
+ {
+ this.context.ReportDiagnostic(UsingStatementOrDeclaration, node);
+ }
+
return updatedNode.ReplaceAndTrackType(updatedNode.Declaration.Type, node.Declaration.Type, this.semanticModel, this.discoveredTypes);
}
@@ -184,6 +225,11 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
{
var updatedNode = (ObjectCreationExpressionSyntax)base.VisitObjectCreationExpression(node)!;
+ if (this.semanticModel.GetTypeInfo(node).Type is ITypeSymbol { IsUnmanagedType: false } type)
+ {
+ this.context.ReportDiagnostic(InvalidObjectCreationExpression, node, type);
+ }
+
updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node, this.semanticModel, this.discoveredTypes);
// New objects use the default HLSL cast syntax, eg. (float4)0
@@ -195,11 +241,26 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
return InvocationExpression(updatedNode.Type, updatedNode.ArgumentList);
}
+ ///
+ public override SyntaxNode? VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node)
+ {
+ var updatedNode = (AnonymousObjectCreationExpressionSyntax)base.VisitAnonymousObjectCreationExpression(node)!;
+
+ this.context.ReportDiagnostic(DiagnosticDescriptors.AnonymousObjectCreationExpression, node);
+
+ return updatedNode;
+ }
+
///
public override SyntaxNode VisitImplicitObjectCreationExpression(ImplicitObjectCreationExpressionSyntax node)
{
var updatedNode = (ImplicitObjectCreationExpressionSyntax)base.VisitImplicitObjectCreationExpression(node)!;
+ if (this.semanticModel.GetTypeInfo(node).Type is ITypeSymbol { IsUnmanagedType: false } type)
+ {
+ this.context.ReportDiagnostic(InvalidObjectCreationExpression, node, type);
+ }
+
TypeSyntax explicitType = IdentifierName("").ReplaceAndTrackType(node, this.semanticModel, this.discoveredTypes);
// Mutate the syntax like with explicit object creation expressions
@@ -255,6 +316,10 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
return updatedNode.WithToken(Literal(updatedNode.Token.ValueText + "L", 0d));
}
}
+ else if (updatedNode.IsKind(SyntaxKind.StringLiteralExpression))
+ {
+ this.context.ReportDiagnostic(StringLiteralExpression, node);
+ }
return updatedNode;
}
@@ -285,12 +350,26 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
///
public override SyntaxNode? VisitLocalFunctionStatement(LocalFunctionStatementSyntax node)
{
+ this.localFunctionDepth++;
+
var updatedNode =
((LocalFunctionStatementSyntax)base.VisitLocalFunctionStatement(node)!)
.WithBlockBody()
.WithAttributeLists(List())
.WithIdentifier(Identifier($"__{this.currentMethod!.Identifier.Text}__{node.Identifier.Text}"));
+ if (node.Modifiers.Any(m => m.IsKind(SyntaxKind.AsyncKeyword)))
+ {
+ this.context.ReportDiagnostic(AsyncModifierOnMethodOrFunction, node);
+ }
+
+ if (node.Modifiers.Any(m => m.IsKind(SyntaxKind.UnsafeKeyword)))
+ {
+ this.context.ReportDiagnostic(UnsafeModifierOnMethodOrFunction, node);
+ }
+
+ this.localFunctionDepth--;
+
// HLSL doesn't support local functions, so we first process them as usual and then remove
// them from the current syntax tree completely. These will be added to the shader source
// as external static method with a special name to avoid conflicts with other methods.
@@ -331,6 +410,24 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
if (mapping == $"__{nameof(GroupIds)}__get_Index") IsGroupIdsIndexUsed = true;
else if (typeName == typeof(GroupIds).FullName) IsGroupIdsUsed = true;
else if (typeName == typeof(WarpIds).FullName) IsWarpIdsUsed = true;
+
+ // Check that the dispatch info types are only used from the main shader body
+ if (!this.isEntryPoint || this.localFunctionDepth > 0)
+ {
+ DiagnosticDescriptor? descriptor = typeName switch
+ {
+ _ when typeName == typeof(ThreadIds).FullName => DiagnosticDescriptors.InvalidThreadIdsUsage,
+ _ when typeName == typeof(GroupIds).FullName => DiagnosticDescriptors.InvalidGroupIdsUsage,
+ _ when typeName == typeof(GroupSize).FullName => DiagnosticDescriptors.InvalidGroupSizeUsage,
+ _ when typeName == typeof(WarpIds).FullName => DiagnosticDescriptors.InvalidWarpIdsUsage,
+ _ => null
+ };
+
+ if (descriptor is not null)
+ {
+ this.context.ReportDiagnostic(descriptor, node);
+ }
+ }
}
// Static and instance members are handled differently, with static members being
@@ -436,7 +533,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
if (!this.staticMethods.ContainsKey(method))
{
- ShaderSourceRewriter shaderSourceRewriter = new(this.semanticModel, this.discoveredTypes, this.staticMethods, this.constantDefinitions);
+ ShaderSourceRewriter shaderSourceRewriter = new(this.semanticModel, this.discoveredTypes, this.staticMethods, this.constantDefinitions, this.context);
MethodDeclarationSyntax
methodNode = (MethodDeclarationSyntax)method.DeclaringSyntaxReferences[0].GetSyntax(),
processedMethod = shaderSourceRewriter.Visit(methodNode)!.NormalizeWhitespace().WithoutTrivia();
@@ -478,7 +575,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
// Track and rewrite the discarded declaration
if (this.semanticModel.GetOperation(node.Expression) is IDiscardOperation operation)
{
- TypeSyntax typeSyntax = operation.Type.TrackType(this.discoveredTypes);
+ TypeSyntax typeSyntax = operation.Type!.TrackType(this.discoveredTypes);
string identifier = $"__implicit{this.implicitVariables.Count}";
// Add the variable to the list of implicit declarations
@@ -508,6 +605,205 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
return updatedNode;
}
+ ///
+ public override SyntaxNode? VisitAwaitExpression(AwaitExpressionSyntax node)
+ {
+ this.context.ReportDiagnostic(DiagnosticDescriptors.AwaitExpression, node);
+
+ return base.VisitAwaitExpression(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitCheckedExpression(CheckedExpressionSyntax node)
+ {
+ this.context.ReportDiagnostic(DiagnosticDescriptors.CheckedExpression, node);
+
+ return base.VisitCheckedExpression(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitCheckedStatement(CheckedStatementSyntax node)
+ {
+ this.context.ReportDiagnostic(DiagnosticDescriptors.CheckedStatement, node);
+
+ return base.VisitCheckedStatement(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitFixedStatement(FixedStatementSyntax node)
+ {
+ this.context.ReportDiagnostic(DiagnosticDescriptors.FixedStatement, node);
+
+ return base.VisitFixedStatement(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitForEachStatement(ForEachStatementSyntax node)
+ {
+ this.context.ReportDiagnostic(DiagnosticDescriptors.ForEachStatement, node);
+
+ return base.VisitForEachStatement(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitForEachVariableStatement(ForEachVariableStatementSyntax node)
+ {
+ this.context.ReportDiagnostic(DiagnosticDescriptors.ForEachStatement, node);
+
+ return base.VisitForEachVariableStatement(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitLockStatement(LockStatementSyntax node)
+ {
+ this.context.ReportDiagnostic(DiagnosticDescriptors.LockStatement, node);
+
+ return base.VisitLockStatement(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitQueryExpression(QueryExpressionSyntax node)
+ {
+ this.context.ReportDiagnostic(DiagnosticDescriptors.QueryExpression, node);
+
+ return base.VisitQueryExpression(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitRangeExpression(RangeExpressionSyntax node)
+ {
+ this.context.ReportDiagnostic(DiagnosticDescriptors.RangeExpression, node);
+
+ return base.VisitRangeExpression(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitRecursivePattern(RecursivePatternSyntax node)
+ {
+ this.context.ReportDiagnostic(DiagnosticDescriptors.RecursivePattern, node);
+
+ return base.VisitRecursivePattern(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitRefType(RefTypeSyntax node)
+ {
+ this.context.ReportDiagnostic(DiagnosticDescriptors.RefType, node);
+
+ return base.VisitRefType(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitRelationalPattern(RelationalPatternSyntax node)
+ {
+ this.context.ReportDiagnostic(DiagnosticDescriptors.RelationalPattern, node);
+
+ return base.VisitRelationalPattern(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitSizeOfExpression(SizeOfExpressionSyntax node)
+ {
+ this.context.ReportDiagnostic(DiagnosticDescriptors.SizeOfExpression, node);
+
+ return base.VisitSizeOfExpression(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitStackAllocArrayCreationExpression(StackAllocArrayCreationExpressionSyntax node)
+ {
+ this.context.ReportDiagnostic(DiagnosticDescriptors.StackAllocArrayCreationExpression, node);
+
+ return base.VisitStackAllocArrayCreationExpression(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitThrowExpression(ThrowExpressionSyntax node)
+ {
+ this.context.ReportDiagnostic(DiagnosticDescriptors.ThrowExpressionOrStatement, node);
+
+ return base.VisitThrowExpression(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitThrowStatement(ThrowStatementSyntax node)
+ {
+ this.context.ReportDiagnostic(DiagnosticDescriptors.ThrowExpressionOrStatement, node);
+
+ return base.VisitThrowStatement(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitTryStatement(TryStatementSyntax node)
+ {
+ this.context.ReportDiagnostic(DiagnosticDescriptors.TryStatement, node);
+
+ return base.VisitTryStatement(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitTupleType(TupleTypeSyntax node)
+ {
+ this.context.ReportDiagnostic(DiagnosticDescriptors.TupleType, node);
+
+ return base.VisitTupleType(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitUsingStatement(UsingStatementSyntax node)
+ {
+ this.context.ReportDiagnostic(DiagnosticDescriptors.UsingStatementOrDeclaration, node);
+
+ return base.VisitUsingStatement(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitVariableDeclarator(VariableDeclaratorSyntax node)
+ {
+ var updatedNode = (VariableDeclaratorSyntax)base.VisitVariableDeclarator(node)!;
+
+ if (node.Initializer is null &&
+ node.Parent is VariableDeclarationSyntax declaration &&
+ this.semanticModel.GetTypeInfo(declaration.Type).Type is ITypeSymbol { IsUnmanagedType: false } type)
+ {
+ this.context.ReportDiagnostic(InvalidObjectDeclaration, node, type);
+ }
+
+ return updatedNode;
+ }
+
+ ///
+ public override SyntaxNode? VisitYieldStatement(YieldStatementSyntax node)
+ {
+ this.context.ReportDiagnostic(DiagnosticDescriptors.YieldStatement, node);
+
+ return base.VisitYieldStatement(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitFunctionPointerType(FunctionPointerTypeSyntax node)
+ {
+ this.context.ReportDiagnostic(DiagnosticDescriptors.FunctionPointer, node);
+
+ return base.VisitFunctionPointerType(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitPointerType(PointerTypeSyntax node)
+ {
+ this.context.ReportDiagnostic(DiagnosticDescriptors.PointerType, node);
+
+ return base.VisitPointerType(node);
+ }
+
+ ///
+ public override SyntaxNode? VisitUnsafeStatement(UnsafeStatementSyntax node)
+ {
+ this.context.ReportDiagnostic(DiagnosticDescriptors.UnsafeStatement, node);
+
+ return base.VisitUnsafeStatement(node);
+ }
+
///
public override SyntaxToken VisitToken(SyntaxToken token)
{
diff --git a/tests/ComputeSharp.Tests.Internals.SourceGenerators/SourceGeneratorTests.cs b/tests/ComputeSharp.Tests.Internals.SourceGenerators/AutoConstructorGeneratorTests.cs
similarity index 96%
rename from tests/ComputeSharp.Tests.Internals.SourceGenerators/SourceGeneratorTests.cs
rename to tests/ComputeSharp.Tests.Internals.SourceGenerators/AutoConstructorGeneratorTests.cs
index 82a2a0a1..487b41c1 100644
--- a/tests/ComputeSharp.Tests.Internals.SourceGenerators/SourceGeneratorTests.cs
+++ b/tests/ComputeSharp.Tests.Internals.SourceGenerators/AutoConstructorGeneratorTests.cs
@@ -10,11 +10,11 @@ using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ComputeSharp.Tests.Internals
{
[TestClass]
- [TestCategory("SourceGenerator")]
- public class SourceGeneratorTests
+ [TestCategory("AutoConstructorGenerator")]
+ public class AutoConstructorGeneratorTests
{
[TestMethod]
- public void SequentialEnum()
+ public void GenerateConstructor()
{
string source = @"
using System.Numerics;
diff --git a/tests/ComputeSharp.Tests.Internals.SourceGenerators/ComputeSharp.Tests.Internals.SourceGenerators.csproj b/tests/ComputeSharp.Tests.Internals.SourceGenerators/ComputeSharp.Tests.Internals.SourceGenerators.csproj
index b0e8280b..a41e2484 100644
--- a/tests/ComputeSharp.Tests.Internals.SourceGenerators/ComputeSharp.Tests.Internals.SourceGenerators.csproj
+++ b/tests/ComputeSharp.Tests.Internals.SourceGenerators/ComputeSharp.Tests.Internals.SourceGenerators.csproj
@@ -1,4 +1,4 @@
-
+
net5.0
diff --git a/tests/ComputeSharp.Tests.Internals.SourceGenerators/DiagnosticsTests.cs b/tests/ComputeSharp.Tests.Internals.SourceGenerators/DiagnosticsTests.cs
new file mode 100644
index 00000000..81336d41
--- /dev/null
+++ b/tests/ComputeSharp.Tests.Internals.SourceGenerators/DiagnosticsTests.cs
@@ -0,0 +1,1131 @@
+using System;
+using System.Collections.Generic;
+using System.Collections.Immutable;
+using System.Linq;
+using ComputeSharp.SourceGenerators;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+
+namespace ComputeSharp.Tests.Internals
+{
+ [TestClass]
+ [TestCategory("Diagnostics")]
+ public class DiagnosticsTests
+ {
+ [TestMethod]
+ public void InvalidShaderField()
+ {
+ string source = @"
+ using ComputeSharp;
+
+ namespace ComputeSharp
+ {
+ public class ReadWriteBuffer { }
+ }
+
+ namespace MyFancyApp.Sample
+ {
+ public struct MyShader : IComputeShader
+ {
+ public ReadWriteBuffer buffer;
+ public string text;
+
+ public void Execute() { }
+ }
+ }";
+
+ VerifyGeneratedDiagnostics(source, "CMPS0001");
+ }
+
+ [TestMethod]
+ public void InvalidGroupSharedFieldType()
+ {
+ string source = @"
+ using ComputeSharp;
+
+ namespace ComputeSharp
+ {
+ public class ReadWriteBuffer { }
+ public class GroupSharedAttribute : Attribute { }
+ }
+
+ namespace MyFancyApp.Sample
+ {
+ public struct MyShader : IComputeShader
+ {
+ public ReadWriteBuffer buffer;
+
+ [GroupShared]
+ public static string text;
+
+ public void Execute() { }
+ }
+ }";
+
+ VerifyGeneratedDiagnostics(source, "CMPS0002");
+ }
+
+ [TestMethod]
+ public void InvalidGroupSharedFieldElementType()
+ {
+ string source = @"
+ using ComputeSharp;
+
+ namespace ComputeSharp
+ {
+ public class ReadWriteBuffer { }
+ public class GroupSharedAttribute : Attribute { }
+ }
+
+ namespace MyFancyApp.Sample
+ {
+ public struct MyShader : IComputeShader
+ {
+ public ReadWriteBuffer buffer;
+
+ [GroupShared]
+ public static string[] text;
+
+ public void Execute() { }
+ }
+ }";
+
+ VerifyGeneratedDiagnostics(source, "CMPS0003");
+ }
+
+ [TestMethod]
+ public void InvalidGroupSharedFieldDeclaration()
+ {
+ string source = @"
+ using ComputeSharp;
+
+ namespace ComputeSharp
+ {
+ public class ReadWriteBuffer { }
+ public class GroupSharedAttribute : Attribute { }
+ }
+
+ namespace MyFancyApp.Sample
+ {
+ public struct MyShader : IComputeShader
+ {
+ [GroupShared]
+ public ReadWriteBuffer buffer;
+
+ public void Execute() { }
+ }
+ }";
+
+ VerifyGeneratedDiagnostics(source, "CMPS0004");
+ }
+
+ [TestMethod]
+ public void MissingShaderResources()
+ {
+ string source = @"
+ using ComputeSharp;
+
+ namespace MyFancyApp.Sample
+ {
+ public struct MyShader : IComputeShader
+ {
+ public void Execute() { }
+ }
+ }";
+
+ VerifyGeneratedDiagnostics(source, "CMPS0005");
+ }
+
+ [TestMethod]
+ [DataRow(nameof(ThreadIds), "CMPS0006")]
+ [DataRow(nameof(GroupIds), "CMPS0007")]
+ [DataRow(nameof(GroupSize), "CMPS0008")]
+ [DataRow(nameof(WarpIds), "CMPS0009")]
+ public void InvalidDispatchInfoUsage_LocalFunction(string typeName, string diagnosticsId)
+ {
+ string source = $@"
+ using ComputeSharp;
+
+ namespace ComputeSharp
+ {{
+ public class ReadWriteBuffer {{ }}
+ public static class {typeName} {{ public static int X => 0; }}
+ }}
+
+ namespace MyFancyApp.Sample
+ {{
+ public struct MyShader : IComputeShader
+ {{
+ public ReadWriteBuffer buffer;
+
+ public void Execute()
+ {{
+ static int Fail() => {typeName}.X;
+
+ Fail();
+ }}
+ }}
+ }}";
+
+ VerifyGeneratedDiagnostics(source, diagnosticsId);
+ }
+
+ [TestMethod]
+ [DataRow(nameof(ThreadIds), "CMPS0006")]
+ [DataRow(nameof(GroupIds), "CMPS0007")]
+ [DataRow(nameof(GroupSize), "CMPS0008")]
+ [DataRow(nameof(WarpIds), "CMPS0009")]
+ public void InvalidDispatchInfoUsage_StaticMethod(string typeName, string diagnosticsId)
+ {
+ string source = $@"
+ using ComputeSharp;
+
+ namespace ComputeSharp
+ {{
+ public class ReadWriteBuffer {{ }}
+ public static class {typeName} {{ public static int X => 0; }}
+ }}
+
+ namespace MyFancyApp.Sample
+ {{
+ public struct MyShader : IComputeShader
+ {{
+ public ReadWriteBuffer buffer;
+
+ public static int Fail() => {typeName}.X;
+
+ public void Execute() => Fail();
+ }}
+ }}";
+
+ VerifyGeneratedDiagnostics(source, diagnosticsId);
+ }
+
+ [TestMethod]
+ public void InvalidObjectCreationExpression_Explicit()
+ {
+ string source = @"
+ using ComputeSharp;
+
+ namespace ComputeSharp
+ {
+ public class ReadWriteBuffer { }
+ }
+
+ namespace MyFancyApp.Sample
+ {
+ public struct MyShader : IComputeShader
+ {
+ public ReadWriteBuffer buffer;
+
+ public void Execute()
+ {
+ object o = new object();
+ }
+ }
+ }";
+
+ VerifyGeneratedDiagnostics(source, "CMPS0010");
+ }
+
+ [TestMethod]
+ public void InvalidObjectCreationExpression_Implicit()
+ {
+ string source = @"
+ using ComputeSharp;
+
+ namespace ComputeSharp
+ {
+ public class ReadWriteBuffer { }
+ }
+
+ namespace MyFancyApp.Sample
+ {
+ public struct MyShader : IComputeShader
+ {
+ public ReadWriteBuffer buffer;
+
+ public void Execute()
+ {
+ object o = new();
+ }
+ }
+ }";
+
+ VerifyGeneratedDiagnostics(source, "CMPS0010");
+ }
+
+ [TestMethod]
+ public void AnonymousObjectCreationExpression()
+ {
+ string source = @"
+ using ComputeSharp;
+
+ namespace ComputeSharp
+ {
+ public class ReadWriteBuffer { }
+ }
+
+ namespace MyFancyApp.Sample
+ {
+ public struct MyShader : IComputeShader
+ {
+ public ReadWriteBuffer buffer;
+
+ public void Execute()
+ {
+ var o = new { Age = 12 };
+ }
+ }
+ }";
+
+ VerifyGeneratedDiagnostics(source, "CMPS0011");
+ }
+
+ [TestMethod]
+ public void AsyncModifierOnMethodOrFunction_LocalFunction()
+ {
+ string source = @"
+ using ComputeSharp;
+
+ namespace ComputeSharp
+ {
+ public class ReadWriteBuffer { }
+ }
+
+ namespace MyFancyApp.Sample
+ {
+ public struct MyShader : IComputeShader
+ {
+ public ReadWriteBuffer buffer;
+
+ public void Execute()
+ {
+ static async void Fail() { }
+
+ Fail();
+ }
+ }
+ }";
+
+ VerifyGeneratedDiagnostics(source, "CMPS0012");
+ }
+
+ [TestMethod]
+ public void AsyncModifierOnMethodOrFunction_StaticMethod()
+ {
+ string source = @"
+ using ComputeSharp;
+
+ namespace ComputeSharp
+ {
+ public class ReadWriteBuffer { }
+ }
+
+ namespace MyFancyApp.Sample
+ {
+ public struct MyShader : IComputeShader
+ {
+ public ReadWriteBuffer buffer;
+
+ public static async void Fail() { }
+
+ public void Execute() => Fail();
+ }
+ }";
+
+ VerifyGeneratedDiagnostics(source, "CMPS0012");
+ }
+
+ [TestMethod]
+ public void AwaitExpression()
+ {
+ string source = @"
+ using ComputeSharp;
+
+ namespace ComputeSharp
+ {
+ public class ReadWriteBuffer { }
+ }
+
+ namespace MyFancyApp.Sample
+ {
+ public struct MyShader : IComputeShader
+ {
+ public ReadWriteBuffer buffer;
+
+ public async void Execute()
+ {
+ await null;
+ }
+ }
+ }";
+
+ VerifyGeneratedDiagnostics(source, "CMPS0012", "CMPS0013");
+ }
+
+ [TestMethod]
+ [DataRow("checked")]
+ [DataRow("unchecked")]
+ public void CheckedExpression(string text)
+ {
+ string source = $@"
+ using ComputeSharp;
+
+ namespace ComputeSharp
+ {{
+ public class ReadWriteBuffer {{ }}
+ }}
+
+ namespace MyFancyApp.Sample
+ {{
+ public struct MyShader : IComputeShader
+ {{
+ public ReadWriteBuffer buffer;
+
+ public void Execute()
+ {{
+ int a = {text}(1 + 1);
+ }}
+ }}
+ }}";
+
+ VerifyGeneratedDiagnostics(source, "CMPS0014");
+ }
+
+ [TestMethod]
+ [DataRow("checked")]
+ [DataRow("unchecked")]
+ public void CheckedStatement(string text)
+ {
+ string source = $@"
+ using ComputeSharp;
+
+ namespace ComputeSharp
+ {{
+ public class ReadWriteBuffer {{ }}
+ }}
+
+ namespace MyFancyApp.Sample
+ {{
+ public struct MyShader : IComputeShader
+ {{
+ public ReadWriteBuffer buffer;
+
+ public void Execute()
+ {{
+ {text}
+ {{
+ int a = 1 + 1;
+ }}
+ }}
+ }}
+ }}";
+
+ VerifyGeneratedDiagnostics(source, "CMPS0015");
+ }
+
+ [TestMethod]
+ public void FixedStatement()
+ {
+ string source = @"
+ using ComputeSharp;
+
+ namespace ComputeSharp
+ {
+ public class ReadWriteBuffer
+ {
+ public int[] Data;
+ }
+ }
+
+ namespace MyFancyApp.Sample
+ {
+ public struct MyShader : IComputeShader
+ {
+ public ReadWriteBuffer buffer;
+
+ public void Execute()
+ {
+ fixed (void* p = buffer.Data)
+ {
+ }
+ }
+ }
+ }";
+
+ VerifyGeneratedDiagnostics(source, "CMPS0016", "CMPS0032");
+ }
+
+ [TestMethod]
+ public void ForEachStatement()
+ {
+ string source = @"
+ using ComputeSharp;
+
+ namespace ComputeSharp
+ {
+ public class ReadWriteBuffer
+ {
+ public int[] Data;
+ }
+ }
+
+ namespace MyFancyApp.Sample
+ {
+ public struct MyShader : IComputeShader
+ {
+ public ReadWriteBuffer buffer;
+
+ public void Execute()
+ {
+ foreach (int i in buffer.Data)
+ {
+ }
+ }
+ }
+ }";
+
+ VerifyGeneratedDiagnostics(source, "CMPS0017");
+ }
+
+ [TestMethod]
+ public void LockStatement()
+ {
+ string source = @"
+ using ComputeSharp;
+
+ namespace ComputeSharp
+ {
+ public class ReadWriteBuffer { }
+ }
+
+ namespace MyFancyApp.Sample
+ {
+ public struct MyShader : IComputeShader
+ {
+ public ReadWriteBuffer buffer;
+
+ public void Execute()
+ {
+ lock (buffer)
+ {
+ }
+ }
+ }
+ }";
+
+ VerifyGeneratedDiagnostics(source, "CMPS0018");
+ }
+
+ [TestMethod]
+ public void QueryExpression()
+ {
+ string source = @"
+ using ComputeSharp;
+
+ namespace ComputeSharp
+ {
+ public class ReadWriteBuffer
+ {
+ public int[] Data;
+ }
+ }
+
+ namespace MyFancyApp.Sample
+ {
+ public struct MyShader : IComputeShader
+ {
+ public ReadWriteBuffer buffer;
+
+ public void Execute()
+ {
+ _ = from x in buffer.Data select x;
+ }
+ }
+ }";
+
+ VerifyGeneratedDiagnostics(source, "CMPS0019");
+ }
+
+ [TestMethod]
+ public void RangeExpression()
+ {
+ string source = @"
+ using ComputeSharp;
+
+ namespace ComputeSharp
+ {
+ public class ReadWriteBuffer
+ {
+ public int[] Data;
+ }
+ }
+
+ namespace MyFancyApp.Sample
+ {
+ public struct MyShader : IComputeShader
+ {
+ public ReadWriteBuffer buffer;
+
+ public void Execute()
+ {
+ _ = buffer.Data[1..];
+ }
+ }
+ }";
+
+ VerifyGeneratedDiagnostics(source, "CMPS0020");
+ }
+
+ [TestMethod]
+ public void RecursivePattern()
+ {
+ string source = @"
+ using ComputeSharp;
+
+ namespace ComputeSharp
+ {
+ public class ReadWriteBuffer
+ {
+ public object Data;
+ }
+ }
+
+ namespace MyFancyApp.Sample
+ {
+ public struct MyShader : IComputeShader
+ {
+ public ReadWriteBuffer buffer;
+
+ public void Execute()
+ {
+ if (buffer.Data is int[] { Length: 50 } foo)
+ {
+ }
+ }
+ }
+ }";
+
+ VerifyGeneratedDiagnostics(source, "CMPS0021");
+ }
+
+ [TestMethod]
+ public void RefType()
+ {
+ string source = @"
+ using ComputeSharp;
+
+ namespace ComputeSharp
+ {
+ public class ReadWriteBuffer
+ {
+ public ref T this[int x] => throw null;
+ }
+ }
+
+ namespace MyFancyApp.Sample
+ {
+ public struct MyShader : IComputeShader
+ {
+ public ReadWriteBuffer buffer;
+
+ public void Execute()
+ {
+ ref float x = ref buffer[0];
+ }
+ }
+ }";
+
+ VerifyGeneratedDiagnostics(source, "CMPS0022");
+ }
+
+ [TestMethod]
+ public void RelationalPattern()
+ {
+ string source = @"
+ using ComputeSharp;
+
+ namespace ComputeSharp
+ {
+ public class ReadWriteBuffer
+ {
+ public int Data;
+ }
+ }
+
+ namespace MyFancyApp.Sample
+ {
+ public struct MyShader : IComputeShader
+ {
+ public ReadWriteBuffer buffer;
+
+ public void Execute()
+ {
+ if (buffer.Data is > 0 and < 10)
+ {
+ }
+ }
+ }
+ }";
+
+ VerifyGeneratedDiagnostics(source, "CMPS0023");
+ }
+
+ [TestMethod]
+ public void SizeOfExpression()
+ {
+ string source = @"
+ using ComputeSharp;
+
+ namespace ComputeSharp
+ {
+ public class ReadWriteBuffer { }
+ }
+
+ namespace MyFancyApp.Sample
+ {
+ public struct MyShader : IComputeShader
+ {
+ public ReadWriteBuffer buffer;
+
+ public void Execute()
+ {
+ _ = sizeof(float);
+ }
+ }
+ }";
+
+ VerifyGeneratedDiagnostics(source, "CMPS0024");
+ }
+
+ [TestMethod]
+ public void StackAllocArrayCreationExpression()
+ {
+ string source = @"
+ using ComputeSharp;
+
+ namespace ComputeSharp
+ {
+ public class ReadWriteBuffer { }
+ }
+
+ namespace MyFancyApp.Sample
+ {
+ public struct MyShader : IComputeShader
+ {
+ public ReadWriteBuffer buffer;
+
+ public void Execute()
+ {
+ int* p = stackalloc int[10];
+ }
+ }
+ }";
+
+ VerifyGeneratedDiagnostics(source, "CMPS0032", "CMPS0025");
+ }
+
+ [TestMethod]
+ public void ThrowExpressionOrStatement()
+ {
+ string source = @"
+ using ComputeSharp;
+
+ namespace ComputeSharp
+ {
+ public class ReadWriteBuffer { }
+ }
+
+ namespace MyFancyApp.Sample
+ {
+ public struct MyShader : IComputeShader
+ {
+ public ReadWriteBuffer buffer;
+
+ public void Execute()
+ {
+ throw null;
+ }
+ }
+ }";
+
+ VerifyGeneratedDiagnostics(source, "CMPS0026");
+ }
+
+ [TestMethod]
+ public void TryStatement()
+ {
+ string source = @"
+ using ComputeSharp;
+
+ namespace ComputeSharp
+ {
+ public class ReadWriteBuffer { }
+ }
+
+ namespace MyFancyApp.Sample
+ {
+ public struct MyShader : IComputeShader
+ {
+ public ReadWriteBuffer buffer;
+
+ public void Execute()
+ {
+ try
+ {
+ }
+ catch
+ {
+ }
+ }
+ }
+ }";
+
+ VerifyGeneratedDiagnostics(source, "CMPS0027");
+ }
+
+ [TestMethod]
+ public void TupleType()
+ {
+ string source = @"
+ using ComputeSharp;
+
+ namespace ComputeSharp
+ {
+ public class ReadWriteBuffer { }
+ }
+
+ namespace MyFancyApp.Sample
+ {
+ public struct MyShader : IComputeShader
+ {
+ public ReadWriteBuffer buffer;
+
+ public void Execute()
+ {
+ (int, float) foo;
+ }
+ }
+ }";
+
+ VerifyGeneratedDiagnostics(source, "CMPS0028");
+ }
+
+ [TestMethod]
+ public void UsingDeclaration()
+ {
+ string source = @"
+ using ComputeSharp;
+
+ namespace ComputeSharp
+ {
+ public class ReadWriteBuffer { }
+ }
+
+ namespace MyFancyApp.Sample
+ {
+ public struct MyShader : IComputeShader
+ {
+ public ReadWriteBuffer buffer;
+
+ public void Execute()
+ {
+ using IDisposable foo = null
+ }
+ }
+ }";
+
+ VerifyGeneratedDiagnostics(source, "CMPS0029");
+ }
+
+ [TestMethod]
+ public void UsingStatement()
+ {
+ string source = @"
+ using ComputeSharp;
+
+ namespace ComputeSharp
+ {
+ public class ReadWriteBuffer { }
+ }
+
+ namespace MyFancyApp.Sample
+ {
+ public struct MyShader : IComputeShader
+ {
+ public ReadWriteBuffer buffer;
+
+ public void Execute()
+ {
+ using (IDisposable foo = null)
+ {
+ }
+ }
+ }
+ }";
+
+ VerifyGeneratedDiagnostics(source, "CMPS0029");
+ }
+
+ [TestMethod]
+ public void YieldStatement()
+ {
+ string source = @"
+ using System.Collections.Generic;
+ using ComputeSharp;
+
+ namespace ComputeSharp
+ {
+ public class ReadWriteBuffer { }
+ }
+
+ namespace MyFancyApp.Sample
+ {
+ public struct MyShader : IComputeShader
+ {
+ public ReadWriteBuffer buffer;
+
+ public static IEnumerable Fail()
+ {
+ yield return 3.14f;
+ }
+
+ public void Execute()
+ {
+ Fail();
+ }
+ }
+ }";
+
+ VerifyGeneratedDiagnostics(source, "CMPS0030");
+ }
+
+ [TestMethod]
+ public void InvalidObjectDeclaration()
+ {
+ string source = @"
+ using ComputeSharp;
+
+ namespace ComputeSharp
+ {
+ public class ReadWriteBuffer { }
+ }
+
+ namespace MyFancyApp.Sample
+ {
+ public struct MyShader : IComputeShader
+ {
+ public ReadWriteBuffer buffer;
+
+ public void Execute()
+ {
+ string bar;
+ }
+ }
+ }";
+
+ VerifyGeneratedDiagnostics(source, "CMPS0031");
+ }
+
+ [TestMethod]
+ public void PointerType()
+ {
+ string source = @"
+ using ComputeSharp;
+
+ namespace ComputeSharp
+ {
+ public class ReadWriteBuffer { }
+ }
+
+ namespace MyFancyApp.Sample
+ {
+ public struct MyShader : IComputeShader
+ {
+ public ReadWriteBuffer buffer;
+
+ public void Execute()
+ {
+ int* p;
+ }
+ }
+ }";
+
+ VerifyGeneratedDiagnostics(source, "CMPS0032");
+ }
+
+ [TestMethod]
+ public void FunctionPointer()
+ {
+ string source = @"
+ using ComputeSharp;
+
+ namespace ComputeSharp
+ {
+ public class ReadWriteBuffer { }
+ }
+
+ namespace MyFancyApp.Sample
+ {
+ public struct MyShader : IComputeShader
+ {
+ public ReadWriteBuffer buffer;
+
+ public void Execute()
+ {
+ delegate* f;
+ }
+ }
+ }";
+
+ VerifyGeneratedDiagnostics(source, "CMPS0033");
+ }
+
+ [TestMethod]
+ public void UnsafeStatement()
+ {
+ string source = @"
+ using ComputeSharp;
+
+ namespace ComputeSharp
+ {
+ public class ReadWriteBuffer { }
+ }
+
+ namespace MyFancyApp.Sample
+ {
+ public struct MyShader : IComputeShader
+ {
+ public ReadWriteBuffer buffer;
+
+ public void Execute()
+ {
+ unsafe
+ {
+ }
+ }
+ }
+ }";
+
+ VerifyGeneratedDiagnostics(source, "CMPS0034");
+ }
+
+ [TestMethod]
+ public void UnsafeModifier_LocalFunction()
+ {
+ string source = @"
+ using ComputeSharp;
+
+ namespace ComputeSharp
+ {
+ public class ReadWriteBuffer { }
+ }
+
+ namespace MyFancyApp.Sample
+ {
+ public struct MyShader : IComputeShader
+ {
+ public ReadWriteBuffer buffer;
+
+ public void Execute()
+ {
+ static unsafe void Fail() { }
+
+ Fail();
+ }
+ }
+ }";
+
+ VerifyGeneratedDiagnostics(source, "CMPS0035");
+ }
+
+ [TestMethod]
+ public void UnsafeModifier_StaticMethod()
+ {
+ string source = @"
+ using ComputeSharp;
+
+ namespace ComputeSharp
+ {
+ public class ReadWriteBuffer { }
+ }
+
+ namespace MyFancyApp.Sample
+ {
+ public struct MyShader : IComputeShader
+ {
+ public static unsafe void Fail() { }
+
+ public ReadWriteBuffer buffer;
+
+ public void Execute()
+ {
+ Fail();
+ }
+ }
+ }";
+
+ VerifyGeneratedDiagnostics(source, "CMPS0035");
+ }
+
+ [TestMethod]
+ public void StringLiteralExpression()
+ {
+ string source = @"
+ using ComputeSharp;
+
+ namespace ComputeSharp
+ {
+ public class ReadWriteBuffer { }
+ }
+
+ namespace MyFancyApp.Sample
+ {
+ public struct MyShader : IComputeShader
+ {
+ public ReadWriteBuffer buffer;
+
+ public void Execute()
+ {
+ _ = ""Hello world"";
+ }
+ }
+ }";
+
+ VerifyGeneratedDiagnostics(source, "CMPS0036");
+ }
+
+ ///
+ /// Verifies the output of a source generator.
+ ///
+ /// The generator type to use.
+ /// The input source to process.
+ /// The target index to check in the resulting output.
+ /// The expected body to compare with the generated code.
+ private void VerifyGeneratedDiagnostics(string source, params string[] diagnosticsIds)
+ where TGenerator : class, ISourceGenerator, new()
+ {
+ SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(source);
+
+ IEnumerable references =
+ from assembly in AppDomain.CurrentDomain.GetAssemblies()
+ where !assembly.IsDynamic
+ let reference = MetadataReference.CreateFromFile(assembly.Location)
+ select reference;
+
+ CSharpCompilation compilation = CSharpCompilation.Create("original", new SyntaxTree[] { syntaxTree }, references, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
+
+ ISourceGenerator generator = new TGenerator();
+
+ CSharpGeneratorDriver driver = CSharpGeneratorDriver.Create(generator);
+
+ driver.RunGeneratorsAndUpdateCompilation(compilation, out Compilation outputCompilation, out ImmutableArray diagnostics);
+
+ HashSet resultingIds = diagnostics.Select(diagnostic => diagnostic.Id).ToHashSet();
+
+ Assert.IsTrue(resultingIds.SetEquals(diagnosticsIds));
+ }
+ }
+}
\ No newline at end of file