Move files to shared project
このコミットが含まれているのは:
1 親
d4ed2099a3
コミット
7f704fa326
9ファイル変更
+10
-1
検索条件に一致するファイルはありません
@@ -0,0 +1,233 @@
|
||||
using System.Threading;
|
||||
using ComputeSharp.D2D1.WinUI.SourceGenerators.Models;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
|
||||
namespace ComputeSharp.D2D1.WinUI.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
partial class CanvasEffectPropertyGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// A container for all the logic for <see cref="CanvasEffectPropertyGenerator"/>.
|
||||
/// </summary>
|
||||
private static partial class Execute
|
||||
{
|
||||
/// <summary>
|
||||
/// Checks whether an input syntax node is a candidate property declaration for the generator.
|
||||
/// </summary>
|
||||
/// <param name="node">The input syntax node to check.</param>
|
||||
/// <param name="token">The <see cref="CancellationToken"/> used to cancel the operation, if needed.</param>
|
||||
/// <returns>Whether <paramref name="node"/> is a candidate property declaration.</returns>
|
||||
public static bool IsCandidatePropertyDeclaration(SyntaxNode node, CancellationToken token)
|
||||
{
|
||||
// The node must be a property declaration with two accessors
|
||||
if (node is not PropertyDeclarationSyntax { AccessorList.Accessors: { Count: 2 } accessors } property)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// The property must be partial (we'll check that it's a declaration from its symbol)
|
||||
if (!property.Modifiers.Any(SyntaxKind.PartialKeyword))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// The accessors must be a get and a set (with any accessibility)
|
||||
if (accessors[0].Kind() is not (SyntaxKind.GetAccessorDeclaration or SyntaxKind.SetAccessorDeclaration) ||
|
||||
accessors[1].Kind() is not (SyntaxKind.GetAccessorDeclaration or SyntaxKind.SetAccessorDeclaration))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// The property must be in a type with a base type (as it must derive from CanvasEffect)
|
||||
return node.Parent?.IsTypeDeclarationWithOrPotentiallyWithBaseTypes<ClassDeclarationSyntax>() == true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tries to get the accessibility of the property and accessors, if possible.
|
||||
/// </summary>
|
||||
/// <param name="node">The input <see cref="PropertyDeclarationSyntax"/> node.</param>
|
||||
/// <param name="symbol">The input <see cref="IPropertySymbol"/> instance.</param>
|
||||
/// <param name="declaredAccessibility">The accessibility of the property, if available.</param>
|
||||
/// <param name="getterAccessibility">The accessibility of the <see langword="get"/> accessor, if available.</param>
|
||||
/// <param name="setterAccessibility">The accessibility of the <see langword="set"/> accessor, if available.</param>
|
||||
/// <returns>Whether the property was valid and the accessibilities could be retrieved.</returns>
|
||||
public static bool TryGetAccessibilityModifiers(
|
||||
PropertyDeclarationSyntax node,
|
||||
IPropertySymbol symbol,
|
||||
out Accessibility declaredAccessibility,
|
||||
out Accessibility getterAccessibility,
|
||||
out Accessibility setterAccessibility)
|
||||
{
|
||||
declaredAccessibility = Accessibility.NotApplicable;
|
||||
getterAccessibility = Accessibility.NotApplicable;
|
||||
setterAccessibility = Accessibility.NotApplicable;
|
||||
|
||||
// Ensure that we have a getter and a setter, and that the setter is not init-only
|
||||
if (symbol is not { GetMethod: { } getMethod, SetMethod: { IsInitOnly: false } setMethod })
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// Track the property accessibility if explicitly set
|
||||
if (node.Modifiers.Count > 0)
|
||||
{
|
||||
declaredAccessibility = symbol.DeclaredAccessibility;
|
||||
}
|
||||
|
||||
// Track the accessors accessibility, if explicitly set
|
||||
foreach (AccessorDeclarationSyntax accessor in node.AccessorList?.Accessors ?? [])
|
||||
{
|
||||
if (accessor.Modifiers.Count == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
switch (accessor.Kind())
|
||||
{
|
||||
case SyntaxKind.GetAccessorDeclaration:
|
||||
getterAccessibility = getMethod.DeclaredAccessibility;
|
||||
break;
|
||||
case SyntaxKind.SetAccessorDeclaration:
|
||||
setterAccessibility = setMethod.DeclaredAccessibility;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the invalidation type to use for the generated effect property.
|
||||
/// </summary>
|
||||
/// <param name="attributeData">The <see cref="AttributeData"/> instance for the processed attribute.</param>
|
||||
/// <returns>The resulting <see cref="CanvasEffectInvalidationType"/> to use for the generated property.</returns>
|
||||
public static CanvasEffectInvalidationType GetCanvasEffectInvalidationType(AttributeData attributeData)
|
||||
{
|
||||
if (attributeData.ConstructorArguments is [{ Kind: TypedConstantKind.Enum, Value: byte enumValue }])
|
||||
{
|
||||
return (CanvasEffectInvalidationType)enumValue;
|
||||
}
|
||||
|
||||
// No constructor parameter, or an invalid one. In this case we either just use the default
|
||||
// invalidation mode, or let the analyzer emit a diagnostic to let the user know.
|
||||
return CanvasEffectInvalidationType.Update;
|
||||
}
|
||||
|
||||
public static void WritePropertyDeclarations(EquatableArray<CanvasEffectPropertyInfo> properties, IndentedTextWriter writer)
|
||||
{
|
||||
// Helper to get the nullable type name for the initial property value
|
||||
static string GetOldValueTypeNameAsNullable(CanvasEffectPropertyInfo propertyInfo)
|
||||
{
|
||||
// Prepare the nullable type for the previous property value. This is needed because if the type is a reference
|
||||
// type, the previous value might be null even if the property type is not nullable, as the first invocation would
|
||||
// happen when the property is first set to some value that is not null (but the backing field would still be so).
|
||||
// As a cheap way to check whether we need to add nullable, we can simply check whether the type name with nullability
|
||||
// annotations ends with a '?'. If it doesn't and the type is a reference type, we add it. Otherwise, we keep it.
|
||||
return propertyInfo.IsReferenceTypeOrUnconstraindTypeParameter switch
|
||||
{
|
||||
true when !propertyInfo.TypeNameWithNullabilityAnnotations.EndsWith("?")
|
||||
=> $"{propertyInfo.TypeNameWithNullabilityAnnotations}?",
|
||||
_ => propertyInfo.TypeNameWithNullabilityAnnotations
|
||||
};
|
||||
}
|
||||
|
||||
// Helper to get the accessibility with a trailing space
|
||||
static string GetExpressionWithTrailingSpace(Accessibility accessibility)
|
||||
{
|
||||
return accessibility.GetExpression() switch
|
||||
{
|
||||
{ Length: > 0 } expression => expression + " ",
|
||||
_ => ""
|
||||
};
|
||||
}
|
||||
|
||||
// First, generate all partial property implementations at the top of the partial type declaration
|
||||
foreach (CanvasEffectPropertyInfo propertyInfo in properties)
|
||||
{
|
||||
string oldValueTypeNameAsNullable = GetOldValueTypeNameAsNullable(propertyInfo);
|
||||
|
||||
writer.WriteLine("/// <inheritdoc/>");
|
||||
writer.WriteGeneratedAttributes(GeneratorName);
|
||||
writer.WriteLine($$"""
|
||||
{{GetExpressionWithTrailingSpace(propertyInfo.DeclaredAccessibility)}}partial {{propertyInfo.TypeNameWithNullabilityAnnotations}} {{propertyInfo.PropertyName}}
|
||||
{
|
||||
{{GetExpressionWithTrailingSpace(propertyInfo.GetterAccessibility)}}get => field;
|
||||
{{GetExpressionWithTrailingSpace(propertyInfo.SetterAccessibility)}}set
|
||||
{
|
||||
if (global::System.Collections.Generic.EqualityComparer<{{oldValueTypeNameAsNullable}}>.Default.Equals(field, value))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
{{oldValueTypeNameAsNullable}} oldValue = field;
|
||||
|
||||
On{{propertyInfo.PropertyName}}Changing(value);
|
||||
On{{propertyInfo.PropertyName}}Changing(oldValue, value);
|
||||
|
||||
field = value;
|
||||
|
||||
On{{propertyInfo.PropertyName}}Changed(value);
|
||||
On{{propertyInfo.PropertyName}}Changed(oldValue, value);
|
||||
|
||||
InvalidateEffectGraph(global::ComputeSharp.D2D1.WinUI.CanvasEffectInvalidationType.{{propertyInfo.InvalidationType}});
|
||||
}
|
||||
}
|
||||
""", isMultiline: true);
|
||||
writer.WriteLine();
|
||||
}
|
||||
|
||||
// Next, emit all partial method declarations at the bottom of the file
|
||||
foreach (CanvasEffectPropertyInfo propertyInfo in properties)
|
||||
{
|
||||
// On<PROPERTY_NAME>Changing, only with new value
|
||||
writer.WriteLine(skipIfPresent: true);
|
||||
writer.WriteLine($"""
|
||||
/// <summary>Executes the logic for when <see cref="{propertyInfo.PropertyName}"/> is changing.</summary>
|
||||
/// <param name="value">The new property value being set.</param>
|
||||
/// <remarks>This method is invoked right before the value of <see cref="{propertyInfo.PropertyName}"/> is changed.</remarks>
|
||||
""", isMultiline: true);
|
||||
writer.WriteGeneratedAttributes(GeneratorName, includeNonUserCodeAttributes: false);
|
||||
writer.WriteLine($"partial void On{propertyInfo.PropertyName}Changing({propertyInfo.TypeNameWithNullabilityAnnotations} newValue);");
|
||||
|
||||
string oldValueTypeNameAsNullable = GetOldValueTypeNameAsNullable(propertyInfo);
|
||||
|
||||
// On<PROPERTY_NAME>Changing, with both values
|
||||
writer.WriteLine();
|
||||
writer.WriteLine($"""
|
||||
/// <summary>Executes the logic for when <see cref="{propertyInfo.PropertyName}"/> is changing.</summary>
|
||||
/// <param name="oldValue">The previous property value that is being replaced.</param>
|
||||
/// <param name="newValue">The new property value being set.</param>
|
||||
/// <remarks>This method is invoked right before the value of <see cref="{propertyInfo.PropertyName}"/> is changed.</remarks>
|
||||
""", isMultiline: true);
|
||||
writer.WriteGeneratedAttributes(GeneratorName, includeNonUserCodeAttributes: false);
|
||||
writer.WriteLine($"partial void On{propertyInfo.PropertyName}Changing({oldValueTypeNameAsNullable} oldValue, {propertyInfo.TypeNameWithNullabilityAnnotations} newValue);");
|
||||
|
||||
// On<PROPERTY_NAME>Changed, only with new value
|
||||
writer.WriteLine();
|
||||
writer.WriteLine($"""
|
||||
/// <summary>Executes the logic for when <see cref="{propertyInfo.PropertyName}"/> has just changed.</summary>
|
||||
/// <param name="value">The new property value that has been set.</param>
|
||||
/// <remarks>This method is invoked right after the value of <see cref="{propertyInfo.PropertyName}"/> is changed.</remarks>
|
||||
""", isMultiline: true);
|
||||
writer.WriteGeneratedAttributes(GeneratorName, includeNonUserCodeAttributes: false);
|
||||
writer.WriteLine($"partial void On{propertyInfo.PropertyName}Changed({propertyInfo.TypeNameWithNullabilityAnnotations} newValue);");
|
||||
|
||||
// On<PROPERTY_NAME>Changed, with both values
|
||||
writer.WriteLine();
|
||||
writer.WriteLine($"""
|
||||
/// <summary>Executes the logic for when <see cref="{propertyInfo.PropertyName}"/> has just changed.</summary>
|
||||
/// <param name="oldValue">The previous property value that has been replaced.</param>
|
||||
/// <param name="newValue">The new property value that has been set.</param>
|
||||
/// <remarks>This method is invoked right after the value of <see cref="{propertyInfo.PropertyName}"/> is changed.</remarks>
|
||||
""", isMultiline: true);
|
||||
writer.WriteGeneratedAttributes(GeneratorName, includeNonUserCodeAttributes: false);
|
||||
writer.WriteLine($"partial void On{propertyInfo.PropertyName}Changed({oldValueTypeNameAsNullable} oldValue, {propertyInfo.TypeNameWithNullabilityAnnotations} newValue);");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
using ComputeSharp.D2D1.WinUI.SourceGenerators.Models;
|
||||
using ComputeSharp.SourceGeneration.Constants;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
using ComputeSharp.SourceGeneration.Models;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
|
||||
namespace ComputeSharp.D2D1.WinUI.SourceGenerators;
|
||||
|
||||
/// <summary>
|
||||
/// A source generator creating implementations of effect properties.
|
||||
/// </summary>
|
||||
[Generator(LanguageNames.CSharp)]
|
||||
public sealed partial class CanvasEffectPropertyGenerator : IIncrementalGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// The name of generator to include in the generated code.
|
||||
/// </summary>
|
||||
private const string GeneratorName = "ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator";
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void Initialize(IncrementalGeneratorInitializationContext context)
|
||||
{
|
||||
IncrementalValuesProvider<CanvasEffectPropertyInfo> propertyInfo =
|
||||
context.SyntaxProvider
|
||||
.ForAttributeWithMetadataName(
|
||||
"ComputeSharp.D2D1.WinUI.GeneratedCanvasEffectPropertyAttribute",
|
||||
Execute.IsCandidatePropertyDeclaration,
|
||||
static (context, token) =>
|
||||
{
|
||||
// This generator requires C# preview to be used (due to the use of the 'field' keyword)
|
||||
if (!context.SemanticModel.Compilation.IsLanguageVersionPreview())
|
||||
{
|
||||
return default;
|
||||
}
|
||||
|
||||
// Ensure we do have a property with a valid containing type
|
||||
if (context.TargetSymbol is not IPropertySymbol { ContainingType: INamedTypeSymbol typeSymbol } propertySymbol)
|
||||
{
|
||||
return default;
|
||||
}
|
||||
|
||||
// Ensure that the property declaration is a partial definition with no implementation
|
||||
if (propertySymbol is not { IsPartialDefinition: true, PartialImplementationPart: null })
|
||||
{
|
||||
return default;
|
||||
}
|
||||
|
||||
// Also ignore all properties that have an invalid declaration
|
||||
if (propertySymbol.IsStatic || propertySymbol.ReturnsByRef || propertySymbol.ReturnsByRefReadonly || propertySymbol.Type.IsRefLikeType)
|
||||
{
|
||||
return default;
|
||||
}
|
||||
|
||||
// Ensure that the containing type derives from CanvasEffect
|
||||
if (!typeSymbol.InheritsFromFullyQualifiedMetadataName("ComputeSharp.D2D1.WinUI.CanvasEffect"))
|
||||
{
|
||||
return default;
|
||||
}
|
||||
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
// Get the accessibility values, if the property is valid
|
||||
if (!Execute.TryGetAccessibilityModifiers(
|
||||
node: (PropertyDeclarationSyntax)context.TargetNode,
|
||||
symbol: propertySymbol,
|
||||
out Accessibility declaredAccessibility,
|
||||
out Accessibility getterAccessibility,
|
||||
out Accessibility setterAccessibility))
|
||||
{
|
||||
return default;
|
||||
}
|
||||
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
string typeNameWithNullabilityAnnotations = propertySymbol.Type.GetFullyQualifiedNameWithNullabilityAnnotations();
|
||||
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
CanvasEffectInvalidationType invalidationType = Execute.GetCanvasEffectInvalidationType(context.Attributes[0]);
|
||||
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
// We're using IsValueType here and not IsReferenceType to also cover unconstrained type parameter cases.
|
||||
// This will cover both reference types as well T when the constraints are not struct or unmanaged.
|
||||
// If this is true, it means the field storage can potentially be in a null state (even if not annotated).
|
||||
bool isReferenceTypeOrUnconstraindTypeParameter = !propertySymbol.Type.IsValueType;
|
||||
|
||||
// Finally, get the hierarchy too
|
||||
HierarchyInfo hierarchyInfo = HierarchyInfo.From(typeSymbol);
|
||||
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
return new CanvasEffectPropertyInfo(
|
||||
Hierarchy: hierarchyInfo,
|
||||
PropertyName: propertySymbol.Name,
|
||||
DeclaredAccessibility: declaredAccessibility,
|
||||
GetterAccessibility: getterAccessibility,
|
||||
SetterAccessibility: setterAccessibility,
|
||||
TypeNameWithNullabilityAnnotations: typeNameWithNullabilityAnnotations,
|
||||
IsReferenceTypeOrUnconstraindTypeParameter: isReferenceTypeOrUnconstraindTypeParameter,
|
||||
InvalidationType: invalidationType);
|
||||
})
|
||||
.WithTrackingName(WellKnownTrackingNames.Execute)
|
||||
.Where(static item => item is not null)!;
|
||||
|
||||
// Split and group by containing type
|
||||
IncrementalValuesProvider<(HierarchyInfo Hierarchy, EquatableArray<CanvasEffectPropertyInfo> Properties)> groupedPropertyInfo =
|
||||
propertyInfo
|
||||
.GroupBy(keySelector: static item => item.Hierarchy, elementSelector: static item => item)
|
||||
.WithTrackingName(WellKnownTrackingNames.Output);
|
||||
|
||||
// Generate the source files, if any
|
||||
context.RegisterSourceOutput(groupedPropertyInfo, static (context, item) =>
|
||||
{
|
||||
using IndentedTextWriter writer = new();
|
||||
|
||||
item.Hierarchy.WriteSyntax(
|
||||
state: item.Properties,
|
||||
writer: writer,
|
||||
baseTypes: [],
|
||||
memberCallbacks: [Execute.WritePropertyDeclarations]);
|
||||
|
||||
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.g.cs", writer.ToString());
|
||||
});
|
||||
}
|
||||
}
|
||||
+10
-1
@@ -9,5 +9,14 @@
|
||||
<Import_RootNamespace>ComputeSharp.D2D1.UI.SourceGenerators</Import_RootNamespace>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="$(MSBuildThisFileDirectory)CanvasEffectPropertyGenerator.cs" />
|
||||
<Compile Include="$(MSBuildThisFileDirectory)CanvasEffectPropertyGenerator.Execute.cs" />
|
||||
<Compile Include="$(MSBuildThisFileDirectory)Diagnostics\Analyzers\InvalidGeneratedCanvasEffectPropertyAccessorsAnalyzer.cs" />
|
||||
<Compile Include="$(MSBuildThisFileDirectory)Diagnostics\Analyzers\InvalidGeneratedCanvasEffectPropertyContainingTypeAnalyzer.cs" />
|
||||
<Compile Include="$(MSBuildThisFileDirectory)Diagnostics\Analyzers\InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer.cs" />
|
||||
<Compile Include="$(MSBuildThisFileDirectory)Diagnostics\Analyzers\RequireCSharpLanguageVersionPreviewAnalyzer.cs" />
|
||||
<Compile Include="$(MSBuildThisFileDirectory)Diagnostics\DiagnosticDescriptors.cs" />
|
||||
<Compile Include="$(MSBuildThisFileDirectory)Models\CanvasEffectPropertyInfo.cs" />
|
||||
<Compile Include="$(MSBuildThisFileDirectory)..\ComputeSharp.D2D1.UI\CanvasEffectInvalidationType.cs" Link="ComputeSharp.D2D1.UI\CanvasEffectInvalidationType.cs" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
</Project>
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
using System.Collections.Immutable;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.Diagnostics;
|
||||
using static ComputeSharp.D2D1.WinUI.SourceGenerators.DiagnosticDescriptors;
|
||||
|
||||
namespace ComputeSharp.D2D1.WinUI.SourceGenerators;
|
||||
|
||||
/// <summary>
|
||||
/// A diagnostic analyzer that generates errors when a property using [GeneratedCanvasEffectProperty] has invalid accessors.
|
||||
/// </summary>
|
||||
[DiagnosticAnalyzer(LanguageNames.CSharp)]
|
||||
public sealed class InvalidGeneratedCanvasEffectPropertyAccessorsAnalyzer : DiagnosticAnalyzer
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = [InvalidGeneratedCanvasEffectPropertyAccessors];
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void Initialize(AnalysisContext context)
|
||||
{
|
||||
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
|
||||
context.EnableConcurrentExecution();
|
||||
|
||||
context.RegisterCompilationStartAction(static context =>
|
||||
{
|
||||
// Get the [GeneratedCanvasEffectProperty] symbols
|
||||
if (context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.WinUI.GeneratedCanvasEffectPropertyAttribute") is not { } generatedCanvasEffectPropertyAttributeSymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
context.RegisterSymbolAction(context =>
|
||||
{
|
||||
// Check that the property doesn't have 'get' and 'set' accessors
|
||||
if (context.Symbol is IPropertySymbol { GetMethod: { }, SetMethod.IsInitOnly: false })
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Skip implementation parts to avoid duplicate errors
|
||||
if (context.Symbol is IPropertySymbol { PartialDefinitionPart: not null })
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// If the property is using [GeneratedCanvasEffectProperty], emit the diagnostic
|
||||
if (context.Symbol.TryGetAttributeWithType(generatedCanvasEffectPropertyAttributeSymbol, out AttributeData? generatedCanvasEffectPropertyAttribute))
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
InvalidGeneratedCanvasEffectPropertyAccessors,
|
||||
generatedCanvasEffectPropertyAttribute.GetLocation(),
|
||||
context.Symbol));
|
||||
}
|
||||
}, SymbolKind.Property);
|
||||
});
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
using System.Collections.Immutable;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.Diagnostics;
|
||||
using static ComputeSharp.D2D1.WinUI.SourceGenerators.DiagnosticDescriptors;
|
||||
|
||||
namespace ComputeSharp.D2D1.WinUI.SourceGenerators;
|
||||
|
||||
/// <summary>
|
||||
/// A diagnostic analyzer that generates errors when a property using [GeneratedCanvasEffectProperty] is in an invalid type.
|
||||
/// </summary>
|
||||
[DiagnosticAnalyzer(LanguageNames.CSharp)]
|
||||
public sealed class InvalidGeneratedCanvasEffectPropertyContainingTypeAnalyzer : DiagnosticAnalyzer
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = [InvalidGeneratedCanvasEffectPropertyContainingType];
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void Initialize(AnalysisContext context)
|
||||
{
|
||||
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
|
||||
context.EnableConcurrentExecution();
|
||||
|
||||
context.RegisterCompilationStartAction(static context =>
|
||||
{
|
||||
// Get the [GeneratedCanvasEffectProperty] and CanvasEffect symbols
|
||||
if (context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.WinUI.GeneratedCanvasEffectPropertyAttribute") is not { } generatedCanvasEffectPropertyAttributeSymbol ||
|
||||
context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.WinUI.CanvasEffect") is not { } canvasEffectSymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
context.RegisterSymbolAction(context =>
|
||||
{
|
||||
// Validate that we have a valid containing type (also skip implementation parts)
|
||||
if (context.Symbol is not IPropertySymbol { ContainingType: { } containingTypeSymbol, PartialDefinitionPart: null })
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// If the property is not using [GeneratedCanvasEffectProperty], there's nothing to do
|
||||
if (!context.Symbol.TryGetAttributeWithType(generatedCanvasEffectPropertyAttributeSymbol, out AttributeData? generatedCanvasEffectPropertyAttribute))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Issue a diagnostic if the type doesn't derive from CanvasEffect
|
||||
if (!containingTypeSymbol.InheritsFromType(canvasEffectSymbol))
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
InvalidGeneratedCanvasEffectPropertyContainingType,
|
||||
generatedCanvasEffectPropertyAttribute.GetLocation(),
|
||||
context.Symbol));
|
||||
}
|
||||
}, SymbolKind.Property);
|
||||
});
|
||||
}
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
using System.Collections.Immutable;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.Diagnostics;
|
||||
using static ComputeSharp.D2D1.WinUI.SourceGenerators.DiagnosticDescriptors;
|
||||
|
||||
namespace ComputeSharp.D2D1.WinUI.SourceGenerators;
|
||||
|
||||
/// <summary>
|
||||
/// A diagnostic analyzer that generates errors when a property using [GeneratedCanvasEffectProperty] has invalid accessors.
|
||||
/// </summary>
|
||||
[DiagnosticAnalyzer(LanguageNames.CSharp)]
|
||||
public sealed class InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer : DiagnosticAnalyzer
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } =
|
||||
[
|
||||
InvalidGeneratedCanvasEffectPropertyDeclarationIsStatic,
|
||||
InvalidGeneratedCanvasEffectPropertyDeclarationIsNotIncompletePartialDefinition,
|
||||
InvalidGeneratedCanvasEffectPropertyDeclarationReturnsByRef,
|
||||
InvalidGeneratedCanvasEffectPropertyDeclarationReturnsRefLikeType
|
||||
];
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void Initialize(AnalysisContext context)
|
||||
{
|
||||
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
|
||||
context.EnableConcurrentExecution();
|
||||
|
||||
context.RegisterCompilationStartAction(static context =>
|
||||
{
|
||||
// Get the [GeneratedCanvasEffectProperty] symbols
|
||||
if (context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.WinUI.GeneratedCanvasEffectPropertyAttribute") is not { } generatedCanvasEffectPropertyAttributeSymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
context.RegisterSymbolAction(context =>
|
||||
{
|
||||
// Ensure that we have some target property to analyze (also skip implementation parts)
|
||||
if (context.Symbol is not IPropertySymbol { PartialDefinitionPart: null } propertySymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// If the property is not using [GeneratedCanvasEffectProperty], there's nothing to do
|
||||
if (!context.Symbol.TryGetAttributeWithType(generatedCanvasEffectPropertyAttributeSymbol, out AttributeData? generatedCanvasEffectPropertyAttribute))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Emit an error if the property is static
|
||||
if (propertySymbol.IsStatic)
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
InvalidGeneratedCanvasEffectPropertyDeclarationIsStatic,
|
||||
generatedCanvasEffectPropertyAttribute.GetLocation(),
|
||||
context.Symbol));
|
||||
}
|
||||
|
||||
// Emit an error if the property is not a partial definition with no implementation
|
||||
if (propertySymbol is not { IsPartialDefinition: true, PartialImplementationPart: null })
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
InvalidGeneratedCanvasEffectPropertyDeclarationIsNotIncompletePartialDefinition,
|
||||
generatedCanvasEffectPropertyAttribute.GetLocation(),
|
||||
context.Symbol));
|
||||
}
|
||||
|
||||
// Emit an error if the property returns a value by ref
|
||||
if (propertySymbol.ReturnsByRef || propertySymbol.ReturnsByRefReadonly)
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
InvalidGeneratedCanvasEffectPropertyDeclarationReturnsByRef,
|
||||
generatedCanvasEffectPropertyAttribute.GetLocation(),
|
||||
context.Symbol));
|
||||
}
|
||||
|
||||
// Emit an error if the property type is a ref struct
|
||||
if (propertySymbol.Type.IsRefLikeType)
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
InvalidGeneratedCanvasEffectPropertyDeclarationReturnsRefLikeType,
|
||||
generatedCanvasEffectPropertyAttribute.GetLocation(),
|
||||
context.Symbol));
|
||||
}
|
||||
}, SymbolKind.Property);
|
||||
});
|
||||
}
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
using System.Collections.Immutable;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.Diagnostics;
|
||||
using static ComputeSharp.D2D1.WinUI.SourceGenerators.DiagnosticDescriptors;
|
||||
|
||||
namespace ComputeSharp.D2D1.WinUI.SourceGenerators;
|
||||
|
||||
/// <summary>
|
||||
/// A diagnostic analyzer that generates errors when a property using [GeneratedCanvasEffectProperty] is in a project with the C# language version not set to preview.
|
||||
/// </summary>
|
||||
[DiagnosticAnalyzer(LanguageNames.CSharp)]
|
||||
public sealed class RequireCSharpLanguageVersionPreviewAnalyzer : DiagnosticAnalyzer
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = [CSharpLanguageVersionIsNotPreview];
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void Initialize(AnalysisContext context)
|
||||
{
|
||||
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
|
||||
context.EnableConcurrentExecution();
|
||||
|
||||
context.RegisterCompilationStartAction(static context =>
|
||||
{
|
||||
// If the language version is set to preview, we'll never emit diagnostics
|
||||
if (context.Compilation.IsLanguageVersionPreview())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Get the [GeneratedCanvasEffectProperty] symbols
|
||||
if (context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.WinUI.GeneratedCanvasEffectPropertyAttribute") is not { } generatedCanvasEffectPropertyAttributeSymbol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
context.RegisterSymbolAction(context =>
|
||||
{
|
||||
// We only want to target partial property definitions (also include non-partial ones for diagnostics)
|
||||
if (context.Symbol is not IPropertySymbol { PartialDefinitionPart: null })
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// If the property is using [GeneratedCanvasEffectProperty], emit the diagnostic
|
||||
if (context.Symbol.TryGetAttributeWithType(generatedCanvasEffectPropertyAttributeSymbol, out AttributeData? generatedCanvasEffectPropertyAttribute))
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
CSharpLanguageVersionIsNotPreview,
|
||||
generatedCanvasEffectPropertyAttribute.GetLocation(),
|
||||
context.Symbol));
|
||||
}
|
||||
}, SymbolKind.Property);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
using Microsoft.CodeAnalysis;
|
||||
|
||||
namespace ComputeSharp.D2D1.WinUI.SourceGenerators;
|
||||
|
||||
/// <summary>
|
||||
/// A container for all <see cref="DiagnosticDescriptor"/> instances for errors reported by analyzers in this project.
|
||||
/// </summary>
|
||||
internal static class DiagnosticDescriptors
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets a <see cref="DiagnosticDescriptor"/> for an invalid CanvasEffect property.
|
||||
/// <para>
|
||||
/// Format: <c>"The property "{0}" is not in a type that derives from CanvasEffect ([GeneratedCanvasEffectProperty] must be used in effect types that extend CanvasEffect)"</c>.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public static readonly DiagnosticDescriptor InvalidGeneratedCanvasEffectPropertyContainingType = new(
|
||||
id: "CMPSD2DWINUI0001",
|
||||
title: "Invalid generated CanvasEffect property containing type",
|
||||
messageFormat: """The property "{0}" is not in a type that derives from CanvasEffect ([GeneratedCanvasEffectProperty] must be used in effect types that extend CanvasEffect)""",
|
||||
category: "ComputeSharp.D2D1.WinUI.Effects",
|
||||
defaultSeverity: DiagnosticSeverity.Error,
|
||||
isEnabledByDefault: true,
|
||||
description: "A property using [GeneratedCanvasEffectProperty] is in a type that does not derive from CanvasEffect ([GeneratedCanvasEffectProperty] must be used in effect types that extend CanvasEffect).",
|
||||
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
|
||||
|
||||
/// <summary>
|
||||
/// Gets a <see cref="DiagnosticDescriptor"/> for a CanvasEffect property with invalid accessors.
|
||||
/// <para>
|
||||
/// Format: <c>"The property "{0}" does not have a getter and a setter ([GeneratedCanvasEffectProperty] must be used on properties with get and set accessors)"</c>.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public static readonly DiagnosticDescriptor InvalidGeneratedCanvasEffectPropertyAccessors = new(
|
||||
id: "CMPSD2DWINUI0002",
|
||||
title: "Invalid generated CanvasEffect property accessors",
|
||||
messageFormat: """The property "{0}" does not have a getter and a setter ([GeneratedCanvasEffectProperty] must be used on properties with get and set accessors)""",
|
||||
category: "ComputeSharp.D2D1.WinUI.Effects",
|
||||
defaultSeverity: DiagnosticSeverity.Error,
|
||||
isEnabledByDefault: true,
|
||||
description: "A property using [GeneratedCanvasEffectProperty] does not have a getter and a setter ([GeneratedCanvasEffectProperty] must be used on properties with get and set accessors).",
|
||||
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
|
||||
|
||||
/// <summary>
|
||||
/// Gets a <see cref="DiagnosticDescriptor"/> for a static CanvasEffect property.
|
||||
/// <para>
|
||||
/// Format: <c>"The property "{0}" is static ([GeneratedCanvasEffectProperty] must be used on instance properties)"</c>.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public static readonly DiagnosticDescriptor InvalidGeneratedCanvasEffectPropertyDeclarationIsStatic = new(
|
||||
id: "CMPSD2DWINUI0003",
|
||||
title: "Invalid generated CanvasEffect property declaration (static member)",
|
||||
messageFormat: """The property "{0}" is static ([GeneratedCanvasEffectProperty] must be used on instance properties)""",
|
||||
category: "ComputeSharp.D2D1.WinUI.Effects",
|
||||
defaultSeverity: DiagnosticSeverity.Error,
|
||||
isEnabledByDefault: true,
|
||||
description: "A property using [GeneratedCanvasEffectProperty] cannot be static ([GeneratedCanvasEffectProperty] must be used on instance properties).",
|
||||
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
|
||||
|
||||
/// <summary>
|
||||
/// Gets a <see cref="DiagnosticDescriptor"/> for a CanvasEffect property with invalid accessors.
|
||||
/// <para>
|
||||
/// Format: <c>"The property "{0}" is not an incomplete partial definition ([GeneratedCanvasEffectProperty] must be used on partial property definitions with no implementation part)"</c>.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public static readonly DiagnosticDescriptor InvalidGeneratedCanvasEffectPropertyDeclarationIsNotIncompletePartialDefinition = new(
|
||||
id: "CMPSD2DWINUI0004",
|
||||
title: "Invalid generated CanvasEffect property declaration (not incomplete partial definition)",
|
||||
messageFormat: """The property "{0}" is not an incomplete partial definition ([GeneratedCanvasEffectProperty] must be used on partial property definitions with no implementation part)""",
|
||||
category: "ComputeSharp.D2D1.WinUI.Effects",
|
||||
defaultSeverity: DiagnosticSeverity.Error,
|
||||
isEnabledByDefault: true,
|
||||
description: "A property using [GeneratedCanvasEffectProperty] is either not partial, or a partial implementation part ([GeneratedCanvasEffectProperty] must be used on partial property definitions with no implementation par).",
|
||||
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
|
||||
|
||||
/// <summary>
|
||||
/// Gets a <see cref="DiagnosticDescriptor"/> for a CanvasEffect property with invalid accessors.
|
||||
/// <para>
|
||||
/// Format: <c>"The property "{0}" returns a value by reference ([GeneratedCanvasEffectProperty] must be used on properties returning a type by value)"</c>.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public static readonly DiagnosticDescriptor InvalidGeneratedCanvasEffectPropertyDeclarationReturnsByRef = new(
|
||||
id: "CMPSD2DWINUI0005",
|
||||
title: "Invalid generated CanvasEffect property declaration (returns byref)",
|
||||
messageFormat: """The property "{0}" returns a value by reference ([GeneratedCanvasEffectProperty] must be used on properties returning a type by value)""",
|
||||
category: "ComputeSharp.D2D1.WinUI.Effects",
|
||||
defaultSeverity: DiagnosticSeverity.Error,
|
||||
isEnabledByDefault: true,
|
||||
description: "A property using [GeneratedCanvasEffectProperty] returns a value by reference ([GeneratedCanvasEffectProperty] must be used on properties returning a type by value).",
|
||||
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
|
||||
|
||||
/// <summary>
|
||||
/// Gets a <see cref="DiagnosticDescriptor"/> for a CanvasEffect property with invalid accessors.
|
||||
/// <para>
|
||||
/// Format: <c>"The property "{0}" returns a ref struct value ([GeneratedCanvasEffectProperty] must be used on properties with a type that is not a ref struct)"</c>.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public static readonly DiagnosticDescriptor InvalidGeneratedCanvasEffectPropertyDeclarationReturnsRefLikeType = new(
|
||||
id: "CMPSD2DWINUI0006",
|
||||
title: "Invalid generated CanvasEffect property declaration (returns ref struct type)",
|
||||
messageFormat: """The property "{0}" returns a ref struct value ([GeneratedCanvasEffectProperty] must be used on properties with a type that is not a ref struct)""",
|
||||
category: "ComputeSharp.D2D1.WinUI.Effects",
|
||||
defaultSeverity: DiagnosticSeverity.Error,
|
||||
isEnabledByDefault: true,
|
||||
description: "A property using [GeneratedCanvasEffectProperty] has a ref struct type ([GeneratedCanvasEffectProperty] must be used on properties with a type that is not a ref struct).",
|
||||
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
|
||||
|
||||
/// <summary>
|
||||
/// Gets a <see cref="DiagnosticDescriptor"/> for a CanvasEffect property with invalid accessors.
|
||||
/// <para>
|
||||
/// Format: <c>"Using [GeneratedCanvasEffectProperty] requires the C# language version to be set to 'preview', as support for the 'field' keyword is needed by the source generators to emit valid code (add <LangVersion>preview</LangVersion> to your .csproj/.props file)"</c>.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public static readonly DiagnosticDescriptor CSharpLanguageVersionIsNotPreview = new(
|
||||
id: "CMPSD2DWINUI0007",
|
||||
title: "C# language version is not 'preview'",
|
||||
messageFormat: """Using [GeneratedCanvasEffectProperty] requires the C# language version to be set to 'preview', as support for the 'field' keyword is needed by the source generators to emit valid code (add <LangVersion>preview</LangVersion> to your .csproj/.props file)""",
|
||||
category: "ComputeSharp.D2D1.WinUI.Effects",
|
||||
defaultSeverity: DiagnosticSeverity.Error,
|
||||
isEnabledByDefault: true,
|
||||
description: "The C# language version must be set to 'preview' when using [GeneratedComputeShaderDescriptor] for the source generators to emit valid code (the <LangVersion>preview</LangVersion> option must be set in the .csproj/.props file).",
|
||||
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
using ComputeSharp.SourceGeneration.Models;
|
||||
using Microsoft.CodeAnalysis;
|
||||
|
||||
namespace ComputeSharp.D2D1.WinUI.SourceGenerators.Models;
|
||||
|
||||
/// <summary>
|
||||
/// A model representing a generated canvas effect property.
|
||||
/// </summary>
|
||||
/// <param name="Hierarchy">The hierarchy info for the shader type.</param>
|
||||
/// <param name="PropertyName">The generated property name.</param>
|
||||
/// <param name="DeclaredAccessibility">The accessibility of the property, if available.</param>
|
||||
/// <param name="GetterAccessibility">The accessibility of the <see langword="get"/> accessor, if available.</param>
|
||||
/// <param name="SetterAccessibility">The accessibility of the <see langword="set"/> accessor, if available.</param>
|
||||
/// <param name="TypeNameWithNullabilityAnnotations">The type name for the generated property, including nullability annotations.</param>
|
||||
/// <param name="IsReferenceTypeOrUnconstraindTypeParameter">Indicates whether the property is of a reference type or an unconstrained type parameter.</param>
|
||||
/// <param name="InvalidationType">The invalidation type to request.</param>
|
||||
internal sealed record CanvasEffectPropertyInfo(
|
||||
HierarchyInfo Hierarchy,
|
||||
string PropertyName,
|
||||
Accessibility DeclaredAccessibility,
|
||||
Accessibility GetterAccessibility,
|
||||
Accessibility SetterAccessibility,
|
||||
string TypeNameWithNullabilityAnnotations,
|
||||
bool IsReferenceTypeOrUnconstraindTypeParameter,
|
||||
CanvasEffectInvalidationType InvalidationType);
|
||||
新しいイシューから参照
ユーザーをブロックする