Skip to content

Commit

Permalink
improved formatting of generated code (#10)
Browse files Browse the repository at this point in the history
saw this style [https://github.com/maryamariyan/runtime/blob/2814f8912c05019c1d1b161e0201eda3f7fc8e69/src/libraries/Microsoft.Extensions.Logging.Abstractions/gen/LoggerMessageGenerator.Emitter.cs](here) & thought it was good

makes things nicer with more line breaks & uses `Append` instead of `AppendLine`, which has better performance
  • Loading branch information
IGood authored Jul 3, 2021
1 parent 149c952 commit 4d77ebf
Show file tree
Hide file tree
Showing 4 changed files with 57 additions and 36 deletions.
3 changes: 3 additions & 0 deletions Bpz.Test/Widget.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ public partial class Widget : DependencyObject
public static readonly DependencyProperty MyBool1Property = Gen.MyBool1<bool>();
public static readonly DependencyProperty MyBool2Property = Gen.MyBool2((bool?)false);

/// <summary>
/// Test dox! Gets or sets a string value or something.
/// </summary>
public static readonly DependencyProperty MyString0Property = Gen.MyString0("asdf");
public static readonly DependencyProperty MyString1Property = Gen.MyString1<string?>();
public static readonly DependencyProperty MyString2Property = Gen.MyString2(default(string?));
Expand Down
8 changes: 8 additions & 0 deletions boilerplatezero/GlobalSuppressions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// This file is used by Code Analysis to maintain SuppressMessage
// attributes that are applied to this project.
// Project-level suppressions either have no target or are given
// a specific target and scoped to a namespace, type, member, etc.

using System.Diagnostics.CodeAnalysis;

[assembly: SuppressMessage("Style", "IDE0057:Use range operator", Justification = "not supported in .net standard 2.0")]
80 changes: 45 additions & 35 deletions boilerplatezero/Wpf/DependencyPropertyGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,13 +68,17 @@ public void Execute(GeneratorExecutionContext context)
this.flagsTypeSymbol ??= context.Compilation.GetTypeByMetadataName("System.Windows.FrameworkPropertyMetadataOptions")!;

string namespaceName = namespaceGroup.Key.ToString();
sourceBuilder.AppendLine($"namespace {namespaceName} {{");
sourceBuilder.Append($@"
namespace {namespaceName}
{{");

foreach (var classGroup in namespaceGroup)
{
string? maybeStatic = classGroup.Key.IsStatic ? "static" : null;
string? maybeStatic = classGroup.Key.IsStatic ? "static " : null;
string className = GetTypeName((INamedTypeSymbol)classGroup.Key);
sourceBuilder.AppendLine($"\t{maybeStatic} partial class {className} {{");
sourceBuilder.Append($@"
{maybeStatic}partial class {className}
{{");

foreach (var generateThis in classGroup)
{
Expand All @@ -83,10 +87,14 @@ public void Execute(GeneratorExecutionContext context)
this.ApppendSource(context, sourceBuilder, generateThis);
}

sourceBuilder.AppendLine("\t}");
sourceBuilder.Append(@"
}
");
}

sourceBuilder.AppendLine("}");
sourceBuilder.Append(@"
}
");
}

if (sourceBuilder.Length != 0)
Expand All @@ -103,7 +111,6 @@ public void Execute(GeneratorExecutionContext context)
//------------------------------------------------------------------------------
{maybeNullableContext}
using System.Windows;
");

context.AddSource($"bpz.DependencyProperties.g.cs", sourceBuilder.ToString());
Expand Down Expand Up @@ -135,7 +142,8 @@ private void ApppendSource(GeneratorExecutionContext context, StringBuilder sour

// Something like...
// public static readonly DependencyProperty FooProperty = FooPropertyKey.DependencyProperty;
sourceBuilder.AppendLine($"\t\tpublic static readonly DependencyProperty {dpMemberName} = {dpkMemberName}.DependencyProperty;");
sourceBuilder.Append($@"
public static readonly DependencyProperty {dpMemberName} = {dpkMemberName}.DependencyProperty;");
}
}

Expand Down Expand Up @@ -240,8 +248,8 @@ private void ApppendSource(GeneratorExecutionContext context, StringBuilder sour
// Something like...
// public static int GetFoo(DependencyObject d) => (int)d.GetValue(FooProperty);
// private static void SetFoo(DependencyObject d, int value) => d.SetValue(FooPropertyKey);
sourceBuilder.AppendLine(
$@" {getterAccess} static {generateThis.PropertyTypeName} Get{propertyName}({targetTypeName} d) => ({generateThis.PropertyTypeName})d.GetValue({dpMemberName});
sourceBuilder.Append($@"
{getterAccess} static {generateThis.PropertyTypeName} Get{propertyName}({targetTypeName} d) => ({generateThis.PropertyTypeName})d.GetValue({dpMemberName});
{setterAccess} static void Set{propertyName}({targetTypeName} d, {generateThis.PropertyTypeName} value) => d.SetValue({setterArg0}, value);");
}
else
Expand All @@ -264,18 +272,20 @@ private void ApppendSource(GeneratorExecutionContext context, StringBuilder sour

// Write the instance property source code.
string propertyAccess = dpAccess.ToString().ToLower();
string setterAccess = generateThis.IsDpk ? dpkAccess.ToString().ToLower() : "";
string setterAccess = generateThis.IsDpk ? (dpkAccess.ToString().ToLower() + " ") : "";
string setterArg0 = generateThis.IsDpk ? dpkMemberName : dpMemberName;

// Something like...
// public int Foo {
// public int Foo
// {
// get => (int)this.GetValue(FooProperty);
// set => this.SetValue(FooPropertyKey, value);
// private set => this.SetValue(FooPropertyKey, value);
// }
sourceBuilder.AppendLine(
$@" {maybeDox}{propertyAccess} {generateThis.PropertyTypeName} {propertyName} {{
sourceBuilder.Append($@"
{maybeDox}{propertyAccess} {generateThis.PropertyTypeName} {propertyName}
{{
get => ({generateThis.PropertyTypeName})this.GetValue({dpMemberName});
{setterAccess} set => this.SetValue({setterArg0}, value);
{setterAccess}set => this.SetValue({setterArg0}, value);
}}");
}

Expand Down Expand Up @@ -304,32 +314,32 @@ private void ApppendSource(GeneratorExecutionContext context, StringBuilder sour
parameters = string.Join(", ", @params, 0, numParams);
}

sourceBuilder.AppendLine(
$@" private static partial class {genClassDecl} {{
/// <summary>
/// Registers {what} named ""{propertyName}"" whose type is <see cref=""{ReplaceBrackets(generateThis.PropertyTypeName)}""/>.{moreDox}
/// </summary>
public static {returnType} {propertyName}<__T>({parameters}) {{");

sourceBuilder.Append("\t\t\t\t");
sourceBuilder.AppendLine(this.GetPropertyMetadataDeclaration(generateThis, hasDefaultValue, hasFlags));

string a = generateThis.IsAttached ? "Attached" : "";
string ro = generateThis.IsDpk ? "ReadOnly" : "";
string ownerTypeName = GetTypeName(generateThis.FieldSymbol.ContainingType);
sourceBuilder.AppendLine(
$@" return DependencyProperty.Register{a}{ro}(""{propertyName}"", typeof(__T), typeof({ownerTypeName}), metadata);

sourceBuilder.Append($@"
private static partial class {genClassDecl}
{{
/// <summary>
/// Registers {what} named ""{propertyName}"" whose type is <see cref=""{ReplaceBrackets(generateThis.PropertyTypeName)}""/>.{moreDox}
/// </summary>
public static {returnType} {propertyName}<__T>({parameters})
{{
var metadata = {this.GetPropertyMetadataInstance(generateThis, hasDefaultValue, hasFlags)};
return DependencyProperty.Register{a}{ro}(""{propertyName}"", typeof(__T), typeof({ownerTypeName}), metadata);
}}
}}");
}}
");
}

/// <summary>
/// Gets source text that declares the property metadata variable named "metadata".
/// Gets source text that creates the property metadata object.
/// Accounts for whether a default value exists.
/// Accounts for whether a compatible property-changed handler exists.
/// Accounts for whether a compatible coercion handler exists.
/// </summary>
private string GetPropertyMetadataDeclaration(GenerationDetails generateThis, bool hasDefaultValue, bool hasFlags)
private string GetPropertyMetadataInstance(GenerationDetails generateThis, bool hasDefaultValue, bool hasFlags)
{
INamedTypeSymbol ownerType = generateThis.FieldSymbol.ContainingType;
string propertyName = generateThis.MethodNameNode.Identifier.ValueText;
Expand Down Expand Up @@ -557,26 +567,26 @@ bool _TryGetCoercionHandler(IMethodSymbol methodSymbol, out string coercionHandl
if (hasFlags)
{
string defaultValue = hasDefaultValue ? "defaultValue" : "default(__T)";
return $"FrameworkPropertyMetadata metadata = new FrameworkPropertyMetadata({defaultValue}, flags, {changeHandler}, {coercionHandler});";
return $"new FrameworkPropertyMetadata({defaultValue}, flags, {changeHandler}, {coercionHandler})";
}

if (hasDefaultValue)
{
return $"PropertyMetadata metadata = new PropertyMetadata(defaultValue, {changeHandler}, {coercionHandler});";
return $"new PropertyMetadata(defaultValue, {changeHandler}, {coercionHandler})";
}

if (changeHandler != "null")
{
return $"PropertyMetadata metadata = new PropertyMetadata({changeHandler}) {{ CoerceValueCallback = {coercionHandler} }};";
return $"new PropertyMetadata({changeHandler}) {{ CoerceValueCallback = {coercionHandler} }}";
}

if (coercionHandler != "null")
{
return $"PropertyMetadata metadata = new PropertyMetadata() {{ CoerceValueCallback = {coercionHandler} }};";
return $"new PropertyMetadata() {{ CoerceValueCallback = {coercionHandler} }}";
}

string nullLiteral = this.useNullableContext ? "null!" : "null";
return $"PropertyMetadata metadata = {nullLiteral};";
return $"(PropertyMetadata){nullLiteral}";
}

/// <summary>
Expand Down
2 changes: 1 addition & 1 deletion boilerplatezero/boilerplatezero.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
<DevelopmentDependency>true</DevelopmentDependency>
<IncludeBuildOutput>false</IncludeBuildOutput>
<PackageId>boilerplatezero</PackageId>
<Version>1.5.1</Version>
<Version>1.5.2</Version>
<Authors>IGood</Authors>
<Company />
<Copyright>Copyright (c) Ian Good</Copyright>
Expand Down

0 comments on commit 4d77ebf

Please sign in to comment.