From c908cc57e57262f6a90e2bb5145b093d3a2d9bdb Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 24 Sep 2022 15:25:15 +0200 Subject: [PATCH] Add InvalidComputeContextCopyAnalyzer --- .../AnalyzerReleases.Shipped.md | 1 + .../InvalidComputeContextCopyAnalyzer.cs | 361 ++++++++++++++++++ .../Diagnostics/DiagnosticDescriptors.cs | 16 + 3 files changed, 378 insertions(+) create mode 100644 src/ComputeSharp.SourceGenerators/Diagnostics/Analyzers/InvalidComputeContextCopyAnalyzer.cs diff --git a/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md index 254bf2b1..03539010 100644 --- a/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md +++ b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md @@ -57,3 +57,4 @@ CMPS0047 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Ser CMPS0048 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPS0049 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPS0050 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0051 | ComputeSharp | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) diff --git a/src/ComputeSharp.SourceGenerators/Diagnostics/Analyzers/InvalidComputeContextCopyAnalyzer.cs b/src/ComputeSharp.SourceGenerators/Diagnostics/Analyzers/InvalidComputeContextCopyAnalyzer.cs new file mode 100644 index 00000000..354d5a3e --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Diagnostics/Analyzers/InvalidComputeContextCopyAnalyzer.cs @@ -0,0 +1,361 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Operations; +using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; + +namespace ComputeSharp.SourceGenerators; + +/// +/// A diagnostic analyzer that generates an error whenever a ComputeContext value is copied. +/// +[DiagnosticAnalyzer(LanguageNames.CSharp)] +public sealed class InvalidComputeContextCopyAnalyzer : DiagnosticAnalyzer +{ + /// + public override ImmutableArray SupportedDiagnostics { get; } = ImmutableArray.Create(InvalidComputeContextCopy); + + /// + public override void Initialize(AnalysisContext context) + { + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); + context.EnableConcurrentExecution(); + + context.RegisterCompilationStartAction(csc => + { + // Initializations + csc.RegisterOperationAction(static context => + { + if (context.Operation is ISymbolInitializerOperation operation) + { + CheckCopyability(context, operation.Value); + } + }, + OperationKind.FieldInitializer, + OperationKind.ParameterInitializer, + OperationKind.PropertyInitializer, + OperationKind.VariableInitializer); + + // Assignments + csc.RegisterOperationAction(static context => + { + if (context.Operation is ISimpleAssignmentOperation { IsRef: false } operation) + { + CheckCopyability(context, operation.Value); + } + }, OperationKind.SimpleAssignment); + + // Arguments + csc.RegisterOperationAction(static context => + { + if (context.Operation is IArgumentOperation { Parameter.RefKind: RefKind.None } operation) + { + CheckCopyability(context, operation.Value); + } + }, OperationKind.Argument); + + // Returns + csc.RegisterOperationAction(static context => + { + if (context.Operation is IReturnOperation { ReturnedValue: not null } operation) + { + // In the absence of data flow analysis we can treat + // return of a local variable or a parameter as a "move" + if (operation.ReturnedValue.Kind is (OperationKind.LocalReference or OperationKind.ParameterReference) && + operation.Kind == OperationKind.Return) + { + ISymbol? varScope = operation.ReturnedValue.Kind switch + { + OperationKind.LocalReference => ((ILocalReferenceOperation)operation.ReturnedValue).Local, + OperationKind.ParameterReference => ((IParameterReferenceOperation)operation.ReturnedValue).Parameter, + _ => null + }; + + if (varScope is null) + { + return; + } + + ISymbol? opScope = operation.SemanticModel?.GetEnclosingSymbol(operation.Syntax.SpanStart); + + if (SymbolEqualityComparer.Default.Equals(varScope, opScope)) + { + return; + } + } + + CheckCopyability(context, operation.ReturnedValue); + } + }, + OperationKind.Return, + OperationKind.YieldReturn); + + // Conversions + csc.RegisterOperationAction(static context => + { + if (context.Operation is IConversionOperation operation) + { + if (operation.Operand.Kind == OperationKind.DefaultValue) + { + return; + } + + if (operation.Operand.Type is not ITypeSymbol typeSymbol) + { + return; + } + + if (!IsComputeContextType(typeSymbol)) + { + return; + } + + if (operation.OperatorMethod is { Parameters.Length: 1 }) + { + if (operation.OperatorMethod.Parameters[0].RefKind != RefKind.None) + { + return; + } + } + + if (operation.Parent is IForEachLoopOperation { Collection: IOperation collectionOperation } && + operation == collectionOperation && + operation.Conversion.IsIdentity) + { + return; + } + + context.ReportDiagnostic(Diagnostic.Create(InvalidComputeContextCopy, operation.Operand.Syntax.GetLocation())); + } + }, OperationKind.Conversion); + + // Array initialization + csc.RegisterOperationAction(static context => + { + if (context.Operation is IArrayInitializerOperation { Parent.Type: IArrayTypeSymbol arrayTypeSymbol } operation) + { + if (!IsComputeContextType(arrayTypeSymbol.ElementType)) + { + return; + } + + foreach (IOperation v in operation.ElementValues) + { + CheckCopyability(context, v); + } + } + }, OperationKind.ArrayInitializer); + + // Declaration pattern + csc.RegisterOperationAction(static context => + { + if (context.Operation is IDeclarationPatternOperation { DeclaredSymbol: ILocalSymbol { Type: ITypeSymbol typeSymbol } } operation) + { + if (!IsComputeContextType(typeSymbol)) + { + return; + } + + context.ReportDiagnostic(Diagnostic.Create(InvalidComputeContextCopy, operation.Syntax.GetLocation())); + } + }, OperationKind.DeclarationPattern); + + // Tuple + csc.RegisterOperationAction(static context => + { + if (context.Operation is ITupleOperation operation) + { + // Exclude ParenthesizedVariableDesignationSyntax + if (!operation.Syntax.IsKind(SyntaxKind.TupleExpression)) + { + return; + } + + foreach (IOperation v in operation.Elements) + { + CheckCopyability(context, v); + } + } + }, OperationKind.Tuple); + + // Member references + csc.RegisterOperationAction(static context => + { + if (context.Operation is IMemberReferenceOperation { Instance: not null } operation) + { + CheckInstanceReadonly(context, operation.Instance); + } + }, + OperationKind.PropertyReference, + OperationKind.EventReference); + + // Invocations + csc.RegisterOperationAction(static context => + { + if (context.Operation is IInvocationOperation operation) + { + CheckGenericConstraints(context, operation); + + if (operation.Instance is not null) + { + CheckInstanceReadonly(context, operation.Instance); + } + } + }, OperationKind.Invocation); + + // Method reference + csc.RegisterOperationAction(static context => + { + if (context.Operation is IMemberReferenceOperation { Instance.Type: not null } operation) + { + if (!IsComputeContextType(operation.Instance.Type)) + { + return; + } + + context.ReportDiagnostic(Diagnostic.Create(InvalidComputeContextCopy, operation.Syntax.GetLocation())); + } + }, OperationKind.MethodReference); + + // Field use + csc.RegisterSymbolAction(static context => + { + if (context.Symbol is IFieldSymbol { IsStatic: false } symbol) + { + if (!IsComputeContextType(symbol.Type)) + { + return; + } + + if (symbol.ContainingType.IsReferenceType) + { + return; + } + + if (IsComputeContextType(symbol.ContainingType)) + { + return; + } + + context.ReportDiagnostic(Diagnostic.Create(InvalidComputeContextCopy, symbol.DeclaringSyntaxReferences[0].GetSyntax().GetLocation())); + } + }, SymbolKind.Field); + }); + } + + /// + /// Checks the generic constraints of an operation. + /// + /// The input instance to use. + /// The instance to check. + private static void CheckGenericConstraints(in OperationAnalysisContext context, IInvocationOperation operation) + { + IMethodSymbol methodSymbol = operation.TargetMethod; + + if (methodSymbol.IsGenericMethod) + { + foreach (ITypeSymbol argumentSymbol in methodSymbol.TypeArguments) + { + if (IsComputeContextType(argumentSymbol)) + { + context.ReportDiagnostic(Diagnostic.Create(InvalidComputeContextCopy, operation.Syntax.GetLocation())); + } + } + } + } + + /// + /// Checks that an instance is not readonly. + /// + /// The input instance to use. + /// The instance to check. + private static void CheckInstanceReadonly(in OperationAnalysisContext context, IOperation operation) + { + if (operation.Type is not ITypeSymbol typeSymbol) + { + return; + } + + if (!IsComputeContextType(typeSymbol)) + { + return; + } + + if (operation is + IFieldReferenceOperation { Field.IsReadOnly: true } or + ILocalReferenceOperation { Local.RefKind: RefKind.In } or + IParameterReferenceOperation { Parameter.RefKind: RefKind.In }) + { + context.ReportDiagnostic(Diagnostic.Create(InvalidComputeContextCopy, operation.Syntax.GetLocation())); + } + } + + /// + /// Checks that an operation supports copying. + /// + /// The input instance to use. + /// The instance to check. + private static void CheckCopyability(in OperationAnalysisContext context, IOperation operation) + { + if (operation.Type is not ITypeSymbol typeSymbol) + { + return; + } + + if (!IsComputeContextType(typeSymbol)) + { + return; + } + + if (CanCopy(operation)) + { + return; + } + + context.ReportDiagnostic(Diagnostic.Create(InvalidComputeContextCopy, operation.Syntax.GetLocation())); + } + + /// + /// Checks that a given type symbol is ComputeContext. + /// + /// The input instance to check. + /// Whether is ComputeContext. + private static bool IsComputeContextType(ITypeSymbol typeSymbol) + { + return typeSymbol is { TypeKind: TypeKind.Struct, Name: "ComputeContext", ContainingNamespace.Name: "ComputeSharp" }; + } + + /// + /// Checks whether an operation is copyable or not even when it is a non-copyable instance. + /// + /// The instance to check. + /// Whether the operation suppots copying. + private static bool CanCopy(IOperation operation) + { + OperationKind kind = operation.Kind; + + if (kind == OperationKind.Conversion) + { + return operation is IConversionOperation { Operand.Kind: OperationKind.DefaultValue or OperationKind.Invalid }; + } + + if (kind is OperationKind.LocalReference or OperationKind.FieldReference or OperationKind.PropertyReference or OperationKind.ArrayElementReference) + { + return operation.Syntax.Parent?.IsKind(SyntaxKind.RefExpression) == true; + } + + if (kind == OperationKind.Conditional) + { + return + operation is IConditionalOperation { WhenFalse: IOperation whenFalse, WhenTrue: IOperation whenTrue } && + CanCopy(whenFalse) && + CanCopy(whenTrue); + } + + return + kind is (OperationKind.ObjectCreation or OperationKind.DefaultValue or OperationKind.Literal or OperationKind.Invocation) || + (kind is (OperationKind.None or OperationKind.Invalid) && operation.Syntax is InvocationExpressionSyntax); // Workaround for https://github.com/dotnet/roslyn/issues/49751 + } +} diff --git a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs index 5e95f4e8..3486414b 100644 --- a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -713,4 +713,20 @@ partial class DiagnosticDescriptors isEnabledByDefault: true, description: "Shaders and shader methods can only use supported types (some .NET primitives and vector types, HLSL primitive, vector and matrix types, and custom types containing these types can be used, and bool fields in custom struct types have to be replaced with the ComputeSharp.Bool type for alignment reasons).", helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a an invalid copy operation for ComputeContext. + /// + /// Format: "The compute shader or method {0} uses the invalid type {1}". + /// + /// + public static readonly DiagnosticDescriptor InvalidComputeContextCopy = new DiagnosticDescriptor( + id: "CMPS0051", + title: "Invalid ComputeContext copy operation", + messageFormat: "The ComputeContext type cannot be copied (consider passing it via ref readonly or in instead) and cannot be used as a field of value types (as it could be indirectly copied)", + category: "ComputeSharp", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "The ComputeContext type cannot be copied (and values should rather be passed via ref readonly or in instead) and cannot be used as a field of value types (as it could be indirectly copied).", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); }