From e3627a25f9b6dc1a03b5374dc3e29d3a2d20946f Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 18 Mar 2021 13:15:00 +0100 Subject: [PATCH] Fixed SGs fail with symbols from different syntax trees --- .../Helpers/SemanticModelProvider.cs | 48 +++++++++++++++++++ .../IComputeShaderSourceGenerator.cs | 21 ++++---- .../ShaderMethodSourceGenerator.cs | 13 ++--- .../HlslSourceRewriter.Diagnostics.cs | 2 +- .../SyntaxRewriters/HlslSourceRewriter.cs | 39 +++++++-------- .../SyntaxRewriters/ShaderSourceRewriter.cs | 29 +++++------ .../SyntaxRewriters/StaticFieldRewriter.cs | 9 ++-- .../Misc/ExternalStructType.cs | 25 ++++++++++ .../ComputeSharp.Tests/ShaderCompilerTests.cs | 23 ++++++++- 9 files changed, 154 insertions(+), 55 deletions(-) create mode 100644 src/ComputeSharp.SourceGenerators/Helpers/SemanticModelProvider.cs create mode 100644 tests/ComputeSharp.Tests/Misc/ExternalStructType.cs diff --git a/src/ComputeSharp.SourceGenerators/Helpers/SemanticModelProvider.cs b/src/ComputeSharp.SourceGenerators/Helpers/SemanticModelProvider.cs new file mode 100644 index 00000000..2b6e5529 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Helpers/SemanticModelProvider.cs @@ -0,0 +1,48 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis; + +namespace ComputeSharp.SourceGenerators.Helpers +{ + /// + /// A type providing instances for nodes. + /// + internal sealed class SemanticModelProvider + { + /// + /// The source instance. + /// + private readonly Compilation compilation; + + /// + /// The map of loaded instances. + /// + private readonly Dictionary semanticModelsMap; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The source instance. + public SemanticModelProvider(Compilation compilation) + { + this.compilation = compilation; + this.semanticModelsMap = new Dictionary(); + } + + /// + /// Gets a instance with info on a given . + /// + /// The input to get info for. + /// A instance containing info on . + public SemanticModel For(SyntaxNode syntaxNode) + { + if (!this.semanticModelsMap.TryGetValue(syntaxNode.SyntaxTree, out SemanticModel semanticModel)) + { + semanticModel = this.compilation.GetSemanticModel(syntaxNode.SyntaxTree); + + this.semanticModelsMap.Add(syntaxNode.SyntaxTree, semanticModel); + } + + return semanticModel; + } + } +} diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs index 23177ccc..2a356f48 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs @@ -15,6 +15,7 @@ using Microsoft.CodeAnalysis.Text; using static ComputeSharp.SourceGenerators.Helpers.SyntaxFactoryHelper; using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; +using ComputeSharp.SourceGenerators.Helpers; #pragma warning disable CS0618 @@ -39,8 +40,8 @@ namespace ComputeSharp.SourceGenerators foreach (StructDeclarationSyntax structDeclaration in structDeclarations) { - SemanticModel semanticModel = context.Compilation.GetSemanticModel(structDeclaration.SyntaxTree); - INamedTypeSymbol structDeclarationSymbol = semanticModel.GetDeclaredSymbol(structDeclaration)!; + SemanticModelProvider semanticModel = new(context.Compilation); + INamedTypeSymbol structDeclarationSymbol = semanticModel.For(structDeclaration).GetDeclaredSymbol(structDeclaration)!; try { @@ -58,9 +59,9 @@ namespace ComputeSharp.SourceGenerators /// /// The input instance to use. /// The node to process. - /// The with metadata on the types being processed. + /// The with metadata on the types being processed. /// The for . - private static void OnExecute(GeneratorExecutionContext context, StructDeclarationSyntax structDeclaration, SemanticModel semanticModel, INamedTypeSymbol structDeclarationSymbol) + private static void OnExecute(GeneratorExecutionContext context, StructDeclarationSyntax structDeclaration, SemanticModelProvider semanticModel, INamedTypeSymbol structDeclarationSymbol) { // Only process compute shader types if (!structDeclarationSymbol.Interfaces.Any(static interfaceSymbol => interfaceSymbol.Name == nameof(IComputeShader))) return; @@ -185,7 +186,7 @@ namespace ComputeSharp.SourceGenerators /// Gets a sequence of shader static fields and their mapped names. /// /// The current generator context in use. - /// The instance for the type to process. + /// The instance for the type to process. /// The instance for the current type. /// The type symbol for the shader type. /// The collection of currently discovered types. @@ -194,7 +195,7 @@ namespace ComputeSharp.SourceGenerators [Pure] private static IEnumerable> GetStaticFields( GeneratorExecutionContext context, - SemanticModel semanticModel, + SemanticModelProvider semanticModel, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, ICollection discoveredTypes, @@ -204,7 +205,7 @@ namespace ComputeSharp.SourceGenerators { foreach (var variableDeclarator in fieldDeclaration.Declaration.Variables) { - IFieldSymbol fieldSymbol = (IFieldSymbol)semanticModel.GetDeclaredSymbol(variableDeclarator)!; + IFieldSymbol fieldSymbol = (IFieldSymbol)semanticModel.For(variableDeclarator).GetDeclaredSymbol(variableDeclarator)!; if (!fieldSymbol.IsStatic || fieldSymbol.IsConst) { @@ -298,7 +299,7 @@ namespace ComputeSharp.SourceGenerators /// 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. + /// The instance for the type to process. /// The collection of currently discovered types. /// The set of discovered and processed static methods. /// The collection of discovered constant definitions. @@ -308,7 +309,7 @@ namespace ComputeSharp.SourceGenerators GeneratorExecutionContext context, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, - SemanticModel semanticModel, + SemanticModelProvider semanticModel, ICollection discoveredTypes, IDictionary staticMethods, IDictionary constantDefinitions) @@ -324,7 +325,7 @@ namespace ComputeSharp.SourceGenerators foreach (MethodDeclarationSyntax methodDeclaration in methodDeclarations) { - IMethodSymbol methodDeclarationSymbol = semanticModel.GetDeclaredSymbol(methodDeclaration)!; + IMethodSymbol methodDeclarationSymbol = semanticModel.For(methodDeclaration).GetDeclaredSymbol(methodDeclaration)!; bool isShaderEntryPoint = methodDeclarationSymbol.Name == nameof(IComputeShader.Execute) && methodDeclarationSymbol.ReturnsVoid && diff --git a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs index 6939758f..0cc6a0bc 100644 --- a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs @@ -6,6 +6,7 @@ using System.Text; using ComputeSharp.__Internals; using ComputeSharp.SourceGenerators.Diagnostics; using ComputeSharp.SourceGenerators.Extensions; +using ComputeSharp.SourceGenerators.Helpers; using ComputeSharp.SourceGenerators.SyntaxRewriters; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; @@ -41,8 +42,8 @@ namespace ComputeSharp.SourceGenerators foreach (MethodDeclarationSyntax methodDeclaration in methods) { - SemanticModel semanticModel = context.Compilation.GetSemanticModel(methodDeclaration.SyntaxTree); - IMethodSymbol methodDeclarationSymbol = semanticModel.GetDeclaredSymbol(methodDeclaration)!; + SemanticModelProvider semanticModel = new(context.Compilation); + IMethodSymbol methodDeclarationSymbol = semanticModel.For(methodDeclaration).GetDeclaredSymbol(methodDeclaration)!; try { @@ -60,9 +61,9 @@ namespace ComputeSharp.SourceGenerators /// /// The input instance to use. /// The node to process. - /// The with metadata on the types being processed. + /// The with metadata on the types being processed. /// The for . - private static void OnExecute(GeneratorExecutionContext context, MethodDeclarationSyntax methodDeclaration, SemanticModel semanticModel, IMethodSymbol methodDeclarationSymbol) + private static void OnExecute(GeneratorExecutionContext context, MethodDeclarationSyntax methodDeclaration, SemanticModelProvider semanticModel, IMethodSymbol methodDeclarationSymbol) { // We need to sets to track all discovered custom types and static methods HashSet discoveredTypes = new(SymbolEqualityComparer.Default); @@ -98,7 +99,7 @@ namespace ComputeSharp.SourceGenerators /// /// The current generator context in use. /// The instance for the current method. - /// The instance for the method to process. + /// The instance for the method to process. /// The collection of currently discovered types. /// The set of discovered and processed static methods. /// The collection of discovered constant definitions. @@ -107,7 +108,7 @@ namespace ComputeSharp.SourceGenerators private static (string InvokeMethod, IEnumerable Methods) GetProcessedMethods( GeneratorExecutionContext context, MethodDeclarationSyntax methodDeclaration, - SemanticModel semanticModel, + SemanticModelProvider semanticModel, ICollection discoveredTypes, IDictionary staticMethods, IDictionary constantDefinitions) diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Diagnostics.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Diagnostics.cs index 3f34c34b..38a70d07 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Diagnostics.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Diagnostics.cs @@ -178,7 +178,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters if (node.Initializer is null && node.Parent is VariableDeclarationSyntax declaration && - SemanticModel.GetTypeInfo(declaration.Type).Type is ITypeSymbol { IsUnmanagedType: false } type) + SemanticModel.For(node).GetTypeInfo(declaration.Type).Type is ITypeSymbol { IsUnmanagedType: false } type) { Context.ReportDiagnostic(InvalidObjectDeclaration, node, type); } diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs index c49b8506..2156d71c 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs @@ -4,6 +4,7 @@ using System.Globalization; using System.Linq; using ComputeSharp.SourceGenerators.Diagnostics; using ComputeSharp.SourceGenerators.Extensions; +using ComputeSharp.SourceGenerators.Helpers; using ComputeSharp.SourceGenerators.Mappings; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; @@ -28,7 +29,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters /// The collection of discovered constant definitions. /// The current generator context in use. protected HlslSourceRewriter( - SemanticModel semanticModel, + SemanticModelProvider semanticModel, ICollection discoveredTypes, IDictionary constantDefinitions, GeneratorExecutionContext context) @@ -40,9 +41,9 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters } /// - /// The instance with semantic info on the target syntax tree. + /// The instance with semantic info on the target syntax tree. /// - protected readonly SemanticModel SemanticModel; + protected readonly SemanticModelProvider SemanticModel; /// /// The collection of discovered custom types. @@ -64,7 +65,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters { var updatedNode = (CastExpressionSyntax)base.VisitCastExpression(node)!; - return updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel, DiscoveredTypes); + return updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel.For(node), DiscoveredTypes); } /// @@ -72,12 +73,12 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters { var updatedNode = (ObjectCreationExpressionSyntax)base.VisitObjectCreationExpression(node)!; - if (SemanticModel.GetTypeInfo(node).Type is ITypeSymbol { IsUnmanagedType: false } type) + if (SemanticModel.For(node).GetTypeInfo(node).Type is ITypeSymbol { IsUnmanagedType: false } type) { Context.ReportDiagnostic(InvalidObjectCreationExpression, node, type); } - updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node, SemanticModel, DiscoveredTypes); + updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node, SemanticModel.For(node), DiscoveredTypes); // New objects use the default HLSL cast syntax, eg. (float4)0 if (updatedNode.ArgumentList!.Arguments.Count == 0) @@ -86,12 +87,12 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters } // Add explicit casts for matrix constructors to help the overload resolution - if (SemanticModel.GetTypeInfo(node).Type is ITypeSymbol matrixType && + if (SemanticModel.For(node).GetTypeInfo(node).Type is ITypeSymbol matrixType && HlslKnownTypes.IsMatrixType(matrixType.GetFullMetadataName())) { for (int i = 0; i < node.ArgumentList!.Arguments.Count; i++) { - IArgumentOperation argumentOperation = (IArgumentOperation)SemanticModel.GetOperation(node.ArgumentList.Arguments[i])!; + IArgumentOperation argumentOperation = (IArgumentOperation)SemanticModel.For(node).GetOperation(node.ArgumentList.Arguments[i])!; INamedTypeSymbol elementType = (INamedTypeSymbol)argumentOperation.Parameter!.Type; updatedNode = updatedNode.ReplaceNode( @@ -108,12 +109,12 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters { var updatedNode = (ImplicitObjectCreationExpressionSyntax)base.VisitImplicitObjectCreationExpression(node)!; - if (SemanticModel.GetTypeInfo(node).Type is ITypeSymbol { IsUnmanagedType: false } type) + if (SemanticModel.For(node).GetTypeInfo(node).Type is ITypeSymbol { IsUnmanagedType: false } type) { Context.ReportDiagnostic(InvalidObjectCreationExpression, node, type); } - TypeSyntax explicitType = IdentifierName("").ReplaceAndTrackType(node, SemanticModel, DiscoveredTypes); + TypeSyntax explicitType = IdentifierName("").ReplaceAndTrackType(node, SemanticModel.For(node), DiscoveredTypes); // Mutate the syntax like with explicit object creation expressions if (updatedNode.ArgumentList!.Arguments.Count == 0) @@ -122,12 +123,12 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters } // Add explicit casts like with the explicit object creation expressions above - if (SemanticModel.GetTypeInfo(node).Type is ITypeSymbol matrixType && + if (SemanticModel.For(node).GetTypeInfo(node).Type is ITypeSymbol matrixType && HlslKnownTypes.IsMatrixType(matrixType.GetFullMetadataName())) { for (int i = 0; i < node.ArgumentList.Arguments.Count; i++) { - IArgumentOperation argumentOperation = (IArgumentOperation)SemanticModel.GetOperation(node.ArgumentList.Arguments[i])!; + IArgumentOperation argumentOperation = (IArgumentOperation)SemanticModel.For(node).GetOperation(node.ArgumentList.Arguments[i])!; INamedTypeSymbol elementType = (INamedTypeSymbol)argumentOperation.Parameter!.Type; updatedNode = updatedNode.ReplaceNode( @@ -144,7 +145,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters { var updatedNode = (DefaultExpressionSyntax)base.VisitDefaultExpression(node)!; - updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel, DiscoveredTypes); + updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel.For(node), DiscoveredTypes); // A default expression becomes (T)0 in HLSL return CastExpression(updatedNode.Type, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0))); @@ -157,13 +158,13 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters if (updatedNode.IsKind(SyntaxKind.DefaultLiteralExpression)) { - TypeSyntax type = node.TrackType(SemanticModel, DiscoveredTypes); + TypeSyntax type = node.TrackType(SemanticModel.For(node), DiscoveredTypes); // Same HLSL-style expression in the form (T)0 return CastExpression(type, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0))); } else if (updatedNode.IsKind(SyntaxKind.NumericLiteralExpression) && - SemanticModel.GetOperation(node) is ILiteralOperation operation && + SemanticModel.For(node).GetOperation(node) is ILiteralOperation operation && operation.Type is INamedTypeSymbol type) { // If the expression is a literal floating point value, we need to ensure the proper suffixes are @@ -196,7 +197,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters { var updatedNode = (ElementAccessExpressionSyntax)base.VisitElementAccessExpression(node)!; - if (SemanticModel.GetOperation(node) is IPropertyReferenceOperation operation) + if (SemanticModel.For(node).GetOperation(node) is IPropertyReferenceOperation operation) { string propertyName = operation.Property.GetFullMetadataName(); @@ -218,7 +219,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters // Validate the arguments foreach (ArgumentSyntax argument in node.ArgumentList.Arguments) { - if (SemanticModel.GetOperation(argument.Expression) is not IFieldReferenceOperation fieldReference || + if (SemanticModel.For(node).GetOperation(argument.Expression) is not IFieldReferenceOperation fieldReference || !HlslKnownMembers.IsKnownMatrixIndex(fieldReference.Field.GetFullMetadataName())) { Context.ReportDiagnostic(NonConstantMatrixSwizzledIndex, argument); @@ -232,7 +233,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters // Rewrite the indexer as a property access string hlslPropertyName = string.Join("", from argument in node.ArgumentList.Arguments - let fieldReference = (IFieldReferenceOperation)SemanticModel.GetOperation(argument.Expression)! + let fieldReference = (IFieldReferenceOperation)SemanticModel.For(node).GetOperation(argument.Expression)! let fieldName = fieldReference.Field.Name let row = (char)(fieldName[1] - 1) let column = (char)(fieldName[2] - 1) @@ -254,7 +255,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters { var updatedNode = (IdentifierNameSyntax)base.VisitIdentifierName(node)!; - if (SemanticModel.GetOperation(node) is IFieldReferenceOperation operation && + if (SemanticModel.For(node).GetOperation(node) is IFieldReferenceOperation operation && operation.Field.IsConst && operation.Type!.TypeKind != TypeKind.Enum) { diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs index 04f4b894..43fe3386 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs @@ -4,6 +4,7 @@ using System.Globalization; using System.Linq; using ComputeSharp.SourceGenerators.Diagnostics; using ComputeSharp.SourceGenerators.Extensions; +using ComputeSharp.SourceGenerators.Helpers; using ComputeSharp.SourceGenerators.Mappings; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; @@ -58,7 +59,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters /// Creates a new instance with the specified parameters. /// /// The type symbol for the shader type. - /// The instance for the target syntax tree. + /// The instance for the target syntax tree. /// The set of discovered custom types. /// The set of discovered and processed static methods. /// The collection of discovered constant definitions. @@ -66,7 +67,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters /// Whether or not the current instance is processing a shader entry point. public ShaderSourceRewriter( INamedTypeSymbol shaderType, - SemanticModel semanticModel, + SemanticModelProvider semanticModel, ICollection discoveredTypes, IDictionary staticMethods, IDictionary constantDefinitions, @@ -84,13 +85,13 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters /// /// Creates a new instance with the specified parameters. /// - /// The instance for the target syntax tree. + /// The instance for the target syntax tree. /// 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, + SemanticModelProvider semanticModel, ICollection discoveredTypes, IDictionary staticMethods, IDictionary constantDefinitions, @@ -129,7 +130,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters var updatedNode = (MethodDeclarationSyntax?)base.Visit(node)!; - updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.ReturnType, node!.ReturnType, SemanticModel, DiscoveredTypes); + updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.ReturnType, node!.ReturnType, SemanticModel.For(node), DiscoveredTypes); if (node!.Modifiers.Any(m => m.IsKind(SyntaxKind.AsyncKeyword))) { @@ -171,7 +172,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters return updatedNode .WithAttributeLists(default) - .ReplaceAndTrackType(updatedNode.Type!, node.Type!, SemanticModel, DiscoveredTypes) + .ReplaceAndTrackType(updatedNode.Type!, node.Type!, SemanticModel.For(node), DiscoveredTypes) .WithModifiers(TokenList(modifier)); } @@ -180,12 +181,12 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters { var updatedNode = ((LocalDeclarationStatementSyntax)base.VisitLocalDeclarationStatement(node)!); - if (SemanticModel.GetOperation(node) is IOperation { Kind: OperationKind.UsingDeclaration }) + if (SemanticModel.For(node).GetOperation(node) is IOperation { Kind: OperationKind.UsingDeclaration }) { Context.ReportDiagnostic(UsingStatementOrDeclaration, node); } - return updatedNode.ReplaceAndTrackType(updatedNode.Declaration.Type, node.Declaration.Type, SemanticModel, DiscoveredTypes); + return updatedNode.ReplaceAndTrackType(updatedNode.Declaration.Type, node.Declaration.Type, SemanticModel.For(node), DiscoveredTypes); } /// @@ -193,7 +194,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters { var updatedNode = (DeclarationExpressionSyntax)base.VisitDeclarationExpression(node)!; - updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel, DiscoveredTypes); + updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel.For(node), DiscoveredTypes); // Add the variable to the list of implicit declarations this.implicitVariables.Add(VariableDeclaration(updatedNode.Type).AddVariables(VariableDeclarator(updatedNode.Designation.ToString()))); @@ -222,7 +223,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters .WithAttributeLists(List()) .WithIdentifier(Identifier($"__{this.currentMethod!.Identifier.Text}__{node.Identifier.Text}")); - updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.ReturnType, node!.ReturnType, SemanticModel, DiscoveredTypes); + updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.ReturnType, node!.ReturnType, SemanticModel.For(node), DiscoveredTypes); if (node.Modifiers.Any(m => m.IsKind(SyntaxKind.AsyncKeyword))) { @@ -251,7 +252,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters var updatedNode = (MemberAccessExpressionSyntax)base.VisitMemberAccessExpression(node)!; if (node.IsKind(SyntaxKind.SimpleMemberAccessExpression) && - SemanticModel.GetOperation(node) is IMemberReferenceOperation operation) + SemanticModel.For(node).GetOperation(node) is IMemberReferenceOperation operation) { // If the member access is a constant, track it and replace the tree with the processed constant name if (operation is IFieldReferenceOperation fieldOperation && @@ -323,7 +324,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters if (!this.staticMethods.TryGetValue(key, out MethodDeclarationSyntax? methodSyntax)) { - INamedTypeSymbol resourceType = (INamedTypeSymbol)SemanticModel.GetTypeInfo(node.Expression).Type!; + INamedTypeSymbol resourceType = (INamedTypeSymbol)SemanticModel.For(node).GetTypeInfo(node.Expression).Type!; string resourceName = HlslKnownTypes.GetMappedName(resourceType); // Create a static method to get a specified dimension for a target resource type. @@ -371,7 +372,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters { var updatedNode = (InvocationExpressionSyntax)base.VisitInvocationExpression(node)!; - if (SemanticModel.GetOperation(node) is IInvocationOperation operation && + if (SemanticModel.For(node).GetOperation(node) is IInvocationOperation operation && operation.TargetMethod is IMethodSymbol method && method.IsStatic) { @@ -426,7 +427,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters updatedNode = updatedNode.WithRefKindKeyword(Token(SyntaxKind.None)); // Track and rewrite the discarded declaration - if (SemanticModel.GetOperation(node.Expression) is IDiscardOperation operation) + if (SemanticModel.For(node).GetOperation(node.Expression) is IDiscardOperation operation) { TypeSyntax typeSyntax = operation.Type!.TrackType(DiscoveredTypes); string identifier = $"__implicit{this.implicitVariables.Count}"; diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/StaticFieldRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/StaticFieldRewriter.cs index 6915f53a..c98451b9 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/StaticFieldRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/StaticFieldRewriter.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Globalization; using ComputeSharp.SourceGenerators.Diagnostics; using ComputeSharp.SourceGenerators.Extensions; +using ComputeSharp.SourceGenerators.Helpers; using ComputeSharp.SourceGenerators.Mappings; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; @@ -21,12 +22,12 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters /// /// Creates a new instance with the specified parameters. /// - /// The instance for the target syntax tree. + /// The instance for the target syntax tree. /// The set of discovered custom types. /// The collection of discovered constant definitions. /// The current generator context in use. public StaticFieldRewriter( - SemanticModel semanticModel, + SemanticModelProvider semanticModel, ICollection discoveredTypes, IDictionary constantDefinitions, GeneratorExecutionContext context) @@ -51,7 +52,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters var updatedNode = (MemberAccessExpressionSyntax)base.VisitMemberAccessExpression(node)!; if (node.IsKind(SyntaxKind.SimpleMemberAccessExpression) && - SemanticModel.GetOperation(node) is IMemberReferenceOperation operation) + SemanticModel.For(node).GetOperation(node) is IMemberReferenceOperation operation) { // Track and replace constants if (operation is IFieldReferenceOperation fieldOperation && @@ -106,7 +107,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters { var updatedNode = (InvocationExpressionSyntax)base.VisitInvocationExpression(node)!; - if (SemanticModel.GetOperation(node) is IInvocationOperation operation && + if (SemanticModel.For(node).GetOperation(node) is IInvocationOperation operation && operation.TargetMethod is IMethodSymbol method && method.IsStatic) { diff --git a/tests/ComputeSharp.Tests/Misc/ExternalStructType.cs b/tests/ComputeSharp.Tests/Misc/ExternalStructType.cs new file mode 100644 index 00000000..960d6475 --- /dev/null +++ b/tests/ComputeSharp.Tests/Misc/ExternalStructType.cs @@ -0,0 +1,25 @@ +namespace ComputeSharp.Tests.Misc +{ + /// + /// An internal custom struct used to test semantic model information coming from different files (different syntax trees). + /// + internal struct ExternalStructType + { + public int A; + public float B; + + public static ExternalStructType New(int a, float b) + { + ExternalStructType value; + value.A = a; + value.B = b; + + return value; + } + + public static float Sum(ExternalStructType value) + { + return value.A + value.B; + } + } +} diff --git a/tests/ComputeSharp.Tests/ShaderCompilerTests.cs b/tests/ComputeSharp.Tests/ShaderCompilerTests.cs index a856dfb6..a51ce292 100644 --- a/tests/ComputeSharp.Tests/ShaderCompilerTests.cs +++ b/tests/ComputeSharp.Tests/ShaderCompilerTests.cs @@ -1,5 +1,5 @@ -using System.Threading; using ComputeSharp.Interop; +using ComputeSharp.Tests.Misc; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace ComputeSharp.Tests @@ -99,5 +99,26 @@ namespace ComputeSharp.Tests buffer[ThreadIds.X] *= foo.a.X + foo.b; } } + + [TestMethod] + public void ExternalStructType_Ok() + { + ReflectionServices.GetShaderInfo(out var info); + } + + [AutoConstructor] + public readonly partial struct ExternalStructTypeShader : IComputeShader + { + public readonly ReadWriteBuffer buffer; + + /// + public void Execute() + { + float value = buffer[ThreadIds.X]; + ExternalStructType type = ExternalStructType.New((int)value, Hlsl.Abs(value)); + + buffer[ThreadIds.X] = ExternalStructType.Sum(type); + } + } } }