-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Code Quality: Use SourceGenerator to simplify DependencyProperty
#11587
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
using Microsoft.UI.Xaml; | ||
|
||
namespace Files.App.Attributes | ||
{ | ||
/// <summary> | ||
/// Generate: | ||
/// <code> | ||
/// <see langword="public static readonly"/> <see cref="DependencyProperty"/> Property = <see cref="DependencyProperty"/>.Register(<see langword="nameof"/>(Field), <see langword="typeof"/>(<typeparamref name="T"/>), <see langword="typeof"/>(TClass), <see langword="new"/> <see cref="PropertyMetadata"/>(DefaultValue, OnPropertyChanged)); | ||
/// <br/> | ||
/// <see langword="public"/> <typeparamref name="T"/> Field { <see langword="get"/> => (<typeparamref name="T"/>)GetValue(Property); <see langword="set"/> => SetValue(Property, <see langword="value"/>); } | ||
/// </code> | ||
/// </summary> | ||
/// <typeparam name="T">property type (nullable value type are not allowed)</typeparam> | ||
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)] | ||
public sealed class DependencyPropertyAttribute<T> : Attribute where T : notnull | ||
{ | ||
/// <inheritdoc cref="DependencyPropertyAttribute{T}"/> | ||
/// <param name="name">Property name</param> | ||
/// <param name="propertyChanged">The name of the method, which called when property changed</param> | ||
public DependencyPropertyAttribute(string name, string propertyChanged = "") | ||
{ | ||
Name = name; | ||
PropertyChanged = propertyChanged; | ||
} | ||
|
||
/// <summary> | ||
/// Property name | ||
/// </summary> | ||
public string Name { get; } | ||
|
||
/// <summary> | ||
/// The name of the method, which called when property changed | ||
/// </summary> | ||
public string PropertyChanged { get; } | ||
|
||
/// <summary> | ||
/// Whether property setter is private | ||
/// </summary> | ||
/// <remarks>default: <see langword="false"/></remarks> | ||
public bool IsSetterPrivate { get; init; } = false; | ||
|
||
/// <summary> | ||
/// Whether property type is nullable (nullable value type are not allowed) | ||
/// </summary> | ||
/// <remarks>default: <see langword="false"/></remarks> | ||
public bool IsNullable { get; init; } | ||
|
||
/// <summary> | ||
/// Default value of property | ||
/// </summary> | ||
/// <remarks>default: <see cref="DependencyProperty.UnsetValue"/></remarks> | ||
public string DefaultValue { get; init; } = "DependencyProperty.UnsetValue"; | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,80 @@ | ||
// Copyright (c) 2023 Files Community | ||
// Licensed under the MIT License. See the LICENSE. | ||
|
||
using System.Collections.Generic; | ||
using System.Collections.Immutable; | ||
using System.Text; | ||
using Microsoft.CodeAnalysis; | ||
using Microsoft.CodeAnalysis.CSharp.Syntax; | ||
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; | ||
using static Files.SourceGenerator.Utilities.SourceGeneratorHelper; | ||
|
||
namespace Files.SourceGenerator | ||
{ | ||
[Generator] | ||
public class DependencyPropertyGenerator : TypeWithAttributeGenerator | ||
{ | ||
internal override string AttributeName => "DependencyPropertyAttribute`1"; | ||
|
||
internal override string? TypeWithAttribute(INamedTypeSymbol typeSymbol, ImmutableArray<AttributeData> attributeList) | ||
{ | ||
var members = new List<MemberDeclarationSyntax>(); | ||
|
||
foreach (var attribute in attributeList) | ||
{ | ||
if (attribute.AttributeClass is not { TypeArguments: [var type, ..] }) | ||
return null; | ||
|
||
if (attribute.ConstructorArguments is not [{ Value: string propertyName }, { Value: string propertyChanged }, ..]) | ||
continue; | ||
|
||
var isSetterPrivate = false; | ||
var defaultValue = "global::Microsoft.UI.Xaml.DependencyProperty.UnsetValue"; | ||
var isNullable = false; | ||
|
||
foreach (var namedArgument in attribute.NamedArguments) | ||
if (namedArgument.Value.Value is { } value) | ||
switch (namedArgument.Key) | ||
{ | ||
case "IsSetterPrivate": | ||
isSetterPrivate = (bool)value; | ||
break; | ||
case "DefaultValue": | ||
defaultValue = (string)value; | ||
break; | ||
case "IsNullable": | ||
isNullable = (bool)value; | ||
break; | ||
} | ||
|
||
var fieldName = propertyName + "Property"; | ||
|
||
var defaultValueExpression = ParseExpression(defaultValue); | ||
var metadataCreation = GetObjectCreationExpression(defaultValueExpression); | ||
if (propertyChanged is not "") | ||
metadataCreation = GetMetadataCreation(metadataCreation, propertyChanged); | ||
|
||
var registration = GetRegistration(propertyName, type, typeSymbol, metadataCreation); | ||
var staticFieldDeclaration = GetStaticFieldDeclaration(fieldName, registration) | ||
.AddAttributeLists(GetAttributeForField(nameof(DependencyPropertyGenerator))); | ||
var getter = GetGetter(fieldName, isNullable, type); | ||
var setter = GetSetter(fieldName, isSetterPrivate); | ||
var propertyDeclaration = GetPropertyDeclaration(propertyName, isNullable, type, getter, setter) | ||
.AddAttributeLists(GetAttributeForMethod(nameof(DependencyPropertyGenerator))); | ||
|
||
members.Add(staticFieldDeclaration); | ||
members.Add(propertyDeclaration); | ||
} | ||
|
||
if (members.Count > 0) | ||
{ | ||
var generatedClass = GetClassDeclaration(typeSymbol, members); | ||
var generatedNamespace = GetFileScopedNamespaceDeclaration(typeSymbol, generatedClass); | ||
var compilationUnit = GetCompilationUnit(generatedNamespace); | ||
return SyntaxTree(compilationUnit, encoding: Encoding.UTF8).GetText().ToString(); | ||
} | ||
|
||
return null; | ||
} | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
<Project Sdk="Microsoft.NET.Sdk"> | ||
|
||
<PropertyGroup> | ||
<TargetFramework>netstandard2.0</TargetFramework> | ||
<LangVersion>preview</LangVersion> | ||
<Nullable>enable</Nullable> | ||
<IncludeBuildOutput>false</IncludeBuildOutput> | ||
<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules> | ||
</PropertyGroup> | ||
|
||
<ItemGroup> | ||
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.5.0" PrivateAssets="all" /> | ||
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.4" PrivateAssets="all" /> | ||
<PackageReference Include="PolySharp" Version="1.13.1"> | ||
<PrivateAssets>all</PrivateAssets> | ||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> | ||
</PackageReference> | ||
</ItemGroup> | ||
|
||
|
||
</Project> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
// Copyright (c) 2023 Files Community | ||
// Licensed under the MIT License. See the LICENSE. | ||
|
||
using System.Collections.Immutable; | ||
using System.Linq; | ||
using Microsoft.CodeAnalysis; | ||
using static Files.SourceGenerator.Utilities.SourceGeneratorHelper; | ||
|
||
namespace Files.SourceGenerator | ||
{ | ||
public abstract class TypeWithAttributeGenerator : IIncrementalGenerator | ||
{ | ||
internal abstract string AttributeName { get; } | ||
|
||
private string AttributeFullName => AttributeNamespace + AttributeName; | ||
|
||
internal abstract string? TypeWithAttribute(INamedTypeSymbol typeSymbol, ImmutableArray<AttributeData> attributeList); | ||
|
||
public void Initialize(IncrementalGeneratorInitializationContext context) | ||
{ | ||
var generatorAttributes = context.SyntaxProvider.ForAttributeWithMetadataName( | ||
AttributeFullName, | ||
(_, _) => true, | ||
(syntaxContext, _) => syntaxContext | ||
).Combine(context.CompilationProvider); | ||
|
||
context.RegisterSourceOutput(generatorAttributes, (spc, tuple) => | ||
{ | ||
var (ga, compilation) = tuple; | ||
|
||
if (compilation.Assembly.GetAttributes().Any(attrData => attrData.AttributeClass?.ToDisplayString() == DisableSourceGeneratorAttribute)) | ||
return; | ||
|
||
if (ga.TargetSymbol is not INamedTypeSymbol symbol) | ||
return; | ||
|
||
if (TypeWithAttribute(symbol, ga.Attributes) is { } source) | ||
spc.AddSource( | ||
// Avoid duplicate names | ||
$"{symbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat.WithGlobalNamespaceStyle(SymbolDisplayGlobalNamespaceStyle.Omitted))}_{AttributeFullName}.g.cs", | ||
source); | ||
}); | ||
} | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.