Skip to content

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 5 commits into from
May 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions Files.sln
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Files.App", "src\Files.App\
EndProject
Project("{C7167F0D-BC9F-4E6E-AFE1-012C56B48DB5}") = "Files.Package", "src\Files.App (Package)\Files.Package.wapproj", "{8F60FD8E-1921-47D6-97B0-D26D7B3A4999}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Files.SourceGenerator", "src\Files.SourceGenerator\Files.SourceGenerator.csproj", "{6FA07816-DE0A-4D49-84E8-38E953A33C87}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|arm64 = Debug|arm64
Expand Down Expand Up @@ -372,6 +374,36 @@ Global
{8F60FD8E-1921-47D6-97B0-D26D7B3A4999}.Store|x86.ActiveCfg = Store|x86
{8F60FD8E-1921-47D6-97B0-D26D7B3A4999}.Store|x86.Build.0 = Store|x86
{8F60FD8E-1921-47D6-97B0-D26D7B3A4999}.Store|x86.Deploy.0 = Store|x86
{6FA07816-DE0A-4D49-84E8-38E953A33C87}.Debug|arm64.ActiveCfg = Debug|Any CPU
{6FA07816-DE0A-4D49-84E8-38E953A33C87}.Debug|arm64.Build.0 = Debug|Any CPU
{6FA07816-DE0A-4D49-84E8-38E953A33C87}.Debug|x64.ActiveCfg = Debug|Any CPU
{6FA07816-DE0A-4D49-84E8-38E953A33C87}.Debug|x64.Build.0 = Debug|Any CPU
{6FA07816-DE0A-4D49-84E8-38E953A33C87}.Debug|x86.ActiveCfg = Debug|Any CPU
{6FA07816-DE0A-4D49-84E8-38E953A33C87}.Debug|x86.Build.0 = Debug|Any CPU
{6FA07816-DE0A-4D49-84E8-38E953A33C87}.Preview|arm64.ActiveCfg = Debug|Any CPU
{6FA07816-DE0A-4D49-84E8-38E953A33C87}.Preview|arm64.Build.0 = Debug|Any CPU
{6FA07816-DE0A-4D49-84E8-38E953A33C87}.Preview|x64.ActiveCfg = Debug|Any CPU
{6FA07816-DE0A-4D49-84E8-38E953A33C87}.Preview|x64.Build.0 = Debug|Any CPU
{6FA07816-DE0A-4D49-84E8-38E953A33C87}.Preview|x86.ActiveCfg = Debug|Any CPU
{6FA07816-DE0A-4D49-84E8-38E953A33C87}.Preview|x86.Build.0 = Debug|Any CPU
{6FA07816-DE0A-4D49-84E8-38E953A33C87}.Release|arm64.ActiveCfg = Release|Any CPU
{6FA07816-DE0A-4D49-84E8-38E953A33C87}.Release|arm64.Build.0 = Release|Any CPU
{6FA07816-DE0A-4D49-84E8-38E953A33C87}.Release|x64.ActiveCfg = Release|Any CPU
{6FA07816-DE0A-4D49-84E8-38E953A33C87}.Release|x64.Build.0 = Release|Any CPU
{6FA07816-DE0A-4D49-84E8-38E953A33C87}.Release|x86.ActiveCfg = Release|Any CPU
{6FA07816-DE0A-4D49-84E8-38E953A33C87}.Release|x86.Build.0 = Release|Any CPU
{6FA07816-DE0A-4D49-84E8-38E953A33C87}.Stable|arm64.ActiveCfg = Debug|Any CPU
{6FA07816-DE0A-4D49-84E8-38E953A33C87}.Stable|arm64.Build.0 = Debug|Any CPU
{6FA07816-DE0A-4D49-84E8-38E953A33C87}.Stable|x64.ActiveCfg = Debug|Any CPU
{6FA07816-DE0A-4D49-84E8-38E953A33C87}.Stable|x64.Build.0 = Debug|Any CPU
{6FA07816-DE0A-4D49-84E8-38E953A33C87}.Stable|x86.ActiveCfg = Debug|Any CPU
{6FA07816-DE0A-4D49-84E8-38E953A33C87}.Stable|x86.Build.0 = Debug|Any CPU
{6FA07816-DE0A-4D49-84E8-38E953A33C87}.Store|arm64.ActiveCfg = Debug|Any CPU
{6FA07816-DE0A-4D49-84E8-38E953A33C87}.Store|arm64.Build.0 = Debug|Any CPU
{6FA07816-DE0A-4D49-84E8-38E953A33C87}.Store|x64.ActiveCfg = Debug|Any CPU
{6FA07816-DE0A-4D49-84E8-38E953A33C87}.Store|x64.Build.0 = Debug|Any CPU
{6FA07816-DE0A-4D49-84E8-38E953A33C87}.Store|x86.ActiveCfg = Debug|Any CPU
{6FA07816-DE0A-4D49-84E8-38E953A33C87}.Store|x86.Build.0 = Debug|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand All @@ -390,6 +422,7 @@ Global
{25FD5045-6D4C-4DD0-B3AC-613AB59CBB07} = {0175B70C-1E29-4A3F-AA4F-C2017B040EF0}
{6F431D82-A5FF-4833-B5E4-702E1E523126} = {A188C26B-E731-4E0B-9D17-D21CEBD9B43F}
{8F60FD8E-1921-47D6-97B0-D26D7B3A4999} = {A74DCE98-A744-4D71-A2B1-7EE4FED0936B}
{6FA07816-DE0A-4D49-84E8-38E953A33C87} = {A74DCE98-A744-4D71-A2B1-7EE4FED0936B}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {0E62043C-A7A1-4982-9EC9-4CDB2939B776}
Expand Down
54 changes: 54 additions & 0 deletions src/Files.App/Attributes/DependencyPropertyAttribute.cs
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";
}
}
1 change: 1 addition & 0 deletions src/Files.App/Files.App.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@
<ProjectReference Include="..\Files.Backend\Files.Backend.csproj" />
<ProjectReference Include="..\Files.Sdk.Storage\Files.Sdk.Storage.csproj" />
<ProjectReference Include="..\Files.Shared\Files.Shared.csproj" />
<ProjectReference Include="..\Files.SourceGenerator\Files.SourceGenerator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
</ItemGroup>
<ItemGroup>
<TrimmerRootAssembly Include="BackgroundTasks" />
Expand Down
13 changes: 2 additions & 11 deletions src/Files.App/UserControls/PathBreadcrumb.xaml.cs
Original file line number Diff line number Diff line change
@@ -1,27 +1,18 @@
// Copyright (c) 2023 Files Community
// Licensed under the MIT License. See the LICENSE.

using Files.App.ViewModels;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Input;
using Files.App.Attributes;

// The User Control item template is documented at https://go.microsoft.com/fwlink/?LinkId=234236

namespace Files.App.UserControls
{
[DependencyProperty<ToolbarViewModel>("ViewModel")]
public sealed partial class PathBreadcrumb : UserControl
{
public ToolbarViewModel ViewModel
{
get => (ToolbarViewModel)GetValue(ViewModelProperty);
set => SetValue(ViewModelProperty, value);
}

// Using a DependencyProperty as the backing store for ViewModel. This enables animation, styling, binding, etc...
public static readonly DependencyProperty ViewModelProperty =
DependencyProperty.Register(nameof(ViewModel), typeof(ToolbarViewModel), typeof(PathBreadcrumb), new PropertyMetadata(null));

public PathBreadcrumb()
{
InitializeComponent();
Expand Down
80 changes: 80 additions & 0 deletions src/Files.SourceGenerator/DependencyPropertyGenerator.cs
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;
}
}
}
21 changes: 21 additions & 0 deletions src/Files.SourceGenerator/Files.SourceGenerator.csproj
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>
45 changes: 45 additions & 0 deletions src/Files.SourceGenerator/TypeWithAttributeGenerator.cs
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);
});
}
}
}
Loading