Skip to content
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

style: format code with dotnet-format #17

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
24 changes: 12 additions & 12 deletions src/CompileTimeComputation/Tests/Constants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,18 @@ public static class Constants
public const string Source = """
namespace Foo;

public partial class Bar
{
public static readonly MD5 MD5 = global::System.Security.Cryptography.MD5.Create();
public const string UriString = "https://dgmjr.io/codegeneration/compiletimecomputation/samples";
[method: CompileTimeComputation("GuidString")]
public static string MakeGuidString() => MD5.ComputeHash(UriString.ToUTF8Bytes()).ToHexString();
}
public partial class Bar
{
public static readonly MD5 MD5 = global::System.Security.Cryptography.MD5.Create();

public const string UriString = "https://dgmjr.io/codegeneration/compiletimecomputation/samples";

[method: CompileTimeComputation("GuidString")]
public static string MakeGuidString() => MD5.ComputeHash(UriString.ToUTF8Bytes()).ToHexString();
}
""";

public const string Bar = nameof(Bar);
public const string Foo = nameof(Foo);
public const string GuidString = nameof(GuidString);
public const string Bar = nameof(Bar);
public const string Foo = nameof(Foo);
public const string GuidString = nameof(GuidString);
}
74 changes: 37 additions & 37 deletions src/CompileTimeComputation/Tests/Tests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,41 +6,41 @@ namespace Dgmjr.CodeGeneration.CompileTimeComputation.Tests;
public class Tests(ITestOutputHelper output) : BaseTest<CompileTimeComputationGenerator>(output)
{
public override CompileTimeComputationGenerator UnitUnderTest { get; } =
new CompileTimeComputationGenerator();
[Fact]
public void Can_Produce_Compile_Time_Computation()
{
Logger.LogSourceToBeCompiled(Constants.Source);
var (inputCompilation, outputCompilation, _) = UnitUnderTest.RunGenerators(
Constants.Source
);
var inputErrors = inputCompilation.GetDiagnostics().Errors();
var outputErrors = outputCompilation.GetDiagnostics().Errors();
// errors.Any().Should().BeFalse("there were errors during compilation");
Logger.LogInformation("Input Errors:");
if (inputErrors.Any())
{
foreach (var error in inputErrors)
{
Logger.LogDiagnosticError(error.Location, error.Id, error.Descriptor);
}
}
Logger.LogInformation("Output Errors:");
if (outputErrors.Any())
{
foreach (var error in outputErrors)
{
Logger.LogDiagnosticError(error);
}
}
var compiledType = outputCompilation.GetTypeByMetadataName(
$"{Constants.Foo}.{Constants.Bar}"
);
compiledType.Should().NotBeNull();
var guidStringField =
compiledType.GetMembers(Constants.GuidString).FirstOrDefault() as IFieldSymbol;
guidStringField.Should().NotBeNull();
Logger.LogInformation($"guidStringField.ConstantValue: {guidStringField.ConstantValue}");
}
new CompileTimeComputationGenerator();

[Fact]
public void Can_Produce_Compile_Time_Computation()
{
Logger.LogSourceToBeCompiled(Constants.Source);
var (inputCompilation, outputCompilation, _) = UnitUnderTest.RunGenerators(
Constants.Source
);
var inputErrors = inputCompilation.GetDiagnostics().Errors();
var outputErrors = outputCompilation.GetDiagnostics().Errors();
// errors.Any().Should().BeFalse("there were errors during compilation");
Logger.LogInformation("Input Errors:");
if (inputErrors.Any())
{
foreach (var error in inputErrors)
{
Logger.LogDiagnosticError(error.Location, error.Id, error.Descriptor);
}
}
Logger.LogInformation("Output Errors:");
if (outputErrors.Any())
{
foreach (var error in outputErrors)
{
Logger.LogDiagnosticError(error);
}
}
var compiledType = outputCompilation.GetTypeByMetadataName(
$"{Constants.Foo}.{Constants.Bar}"
);
compiledType.Should().NotBeNull();
var guidStringField =
compiledType.GetMembers(Constants.GuidString).FirstOrDefault() as IFieldSymbol;
guidStringField.Should().NotBeNull();
Logger.LogInformation($"guidStringField.ConstantValue: {guidStringField.ConstantValue}");
}
}
68 changes: 39 additions & 29 deletions src/CompileTimeComputation/src/CompileTimeComputationGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@ public void Initialize(IncrementalGeneratorInitializationContext context)

private static Action<
Action<IncrementalGeneratorPostInitializationContext>
> RegisterPostInitializationOutput { get; set; }
> RegisterPostInitializationOutput
{ get; set; }

private static bool Select(SyntaxNode node, CancellationToken cancellationToken) => true; /*node is PropertyDeclarationSyntax pds ? pds.DescendantNodesAndTokensAndSelf(node => node.IsKind(SyntaxKind.PublicKeyword)).Any() && pds.DescendantNodesAndTokensAndSelf(node => node.IsKind(SyntaxKind.StaticKeyword)).Any() : node is MethodDeclarationSyntax mds && mds.DescendantNodesAndTokensAndSelf(node => node.IsKind(SyntaxKind.PublicKeyword)).Any() && mds.DescendantNodesAndTokensAndSelf(node => node.IsKind(SyntaxKind.StaticKeyword)).Any();*/

Expand Down Expand Up @@ -149,38 +150,47 @@ public static void Execute(
var constDeclaration =
HeaderTemplate.Render(new { Filename = filename })
+ $$$"""
namespace {{{fieldSymbol.ContainingType.ContainingNamespace.ToDisplayString()}}};

{{{fieldSymbol.ContainingType.DeclaredAccessibility.ToString().ToLower().Replace("or", " ").Replace("and", " ")}}} {{{(fieldSymbol.ContainingType.IsStatic ? "static" : "")}}} partial {{{(fieldSymbol.ContainingType.IsRecord ? "record" : "")}}} {{{(fieldSymbol.ContainingType.TypeKind == TypeKind.Class ? "class" : fieldSymbol.ContainingType.TypeKind == TypeKind.Struct ? "struct" : $"#error Wrong data structure type: {fieldSymbol.ContainingType.TypeKind}")}}} {{{fieldSymbol.ContainingType.Name}}}
{
public const {{{fieldSymbol.ToDisplayString()}}} {{{name}}} = {{{(fieldType.Name.Equals(nameof(String), InvariantCultureIgnoreCase) ? "\"" : "")}}}{{{funcResult}}}{{{(fieldSymbol.Name.Equals(nameof(String), InvariantCultureIgnoreCase) ? "\"" : "")}}};
namespace {{{fieldSymbol.ContainingType.ContainingNamespace.ToDisplayString() }
}};

{ { { fieldSymbol.ContainingType.DeclaredAccessibility.ToString().ToLower().Replace("or", " ").Replace("and", " ")} } }
{ { { (fieldSymbol.ContainingType.IsStatic ? "static" : "")} } }
partial
{ { { (fieldSymbol.ContainingType.IsRecord ? "record" : "")} } }
{ { { (fieldSymbol.ContainingType.TypeKind == TypeKind.Class ? "class" : fieldSymbol.ContainingType.TypeKind == TypeKind.Struct ? "struct" : $"#error Wrong data structure type: {fieldSymbol.ContainingType.TypeKind}")} } }
{ { { fieldSymbol.ContainingType.Name} } }
{
public const { { { fieldSymbol.ToDisplayString()} } }
{ { { name} } } = { { { (fieldType.Name.Equals(nameof(String), InvariantCultureIgnoreCase) ? "\"" : "")} } }
{ { { funcResult} } }
{ { { (fieldSymbol.Name.Equals(nameof(String), InvariantCultureIgnoreCase) ? "\"" : "")} } };
}
""";

// Add the class and const variable declarations to the compilation
context.AddSource(filename, constDeclaration);
}
catch (TargetInvocationException tiex)
{
throw tiex.InnerException ?? tiex;

// Add the class and const variable declarations to the compilation
context.AddSource(filename, constDeclaration);
}
catch (TargetInvocationException tiex)
{
throw tiex.InnerException ?? tiex;
}
}
else
{
context.ReportDiagnostic(
Diagnostic.Create(
new DiagnosticDescriptor(
"CTCG002",
"Error generatimg compile-time computed constant: must be const-able",
Format(CTCG002ErrorMessage, fieldSymbolDisplay),
"CTCG002: Field must be const-able",
DiagnosticSeverity.Error,
true
),
fieldSymbol.Locations.FirstOrDefault()
)
);
}
else
{
context.ReportDiagnostic(
Diagnostic.Create(
new DiagnosticDescriptor(
"CTCG002",
"Error generatimg compile-time computed constant: must be const-able",
Format(CTCG002ErrorMessage, fieldSymbolDisplay),
"CTCG002: Field must be const-able",
DiagnosticSeverity.Error,
true
),
fieldSymbol.Locations.FirstOrDefault()
)
);
}
}
}
}
23 changes: 13 additions & 10 deletions src/CompileTimeComputation/src/Constants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -84,16 +84,19 @@ public static class Constants
);

public const string CompileTimeComputationClassDeclaration = $$$"""
{{{GeneratedCodeAttributes}}}
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property)]
internal sealed class {{{CompileTimeComputation}}} : Attribute
{
public {{{CompileTimeComputation}}}(string name)
{
Name = name;
}

public string Name { get; }
{{{GeneratedCodeAttributes
}
}}
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property)]
internal sealed class {{ { CompileTimeComputation} }} : Attribute
{
public
{ { { CompileTimeComputation} } } (string name)
{
Name = name;
}

public string Name { get; }
}
""";
}
144 changes: 72 additions & 72 deletions src/Constants/Constants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ public static partial class Constants
);
public const string AttributeDeclarationTemplateString = """"
#nullable enable

[AttributeUsage({{ regex.replace(regex.replace attribute_targets "(?:(?:^)|(?: ))" "System.AttributeTargets.") "," " | " }
}, AllowMultiple = false)]
internal class {{ attribute_class_name }} : { { attribute_base_type.full_name } }
Expand All @@ -106,17 +106,17 @@ internal class {{ attribute_class_name }} : { { attribute_base_type.full_name }
{ get; set; }
{ { ~end ~} }
}
"""";
public static readonly Scriban.Template AttributeDeclarationTemplate = Scriban.Template.Parse(
AttributeDeclarationTemplateString
);
public static readonly string ToolName = typeof(Constants).Assembly.GetName().Name;
public static readonly string ToolVersion = typeof(Constants).Assembly
.GetName()
.GetName()
.Version.ToString();
public static readonly string MinimalCodeHeaderTemplateString = $$$""""
"""";
public static readonly Scriban.Template AttributeDeclarationTemplate = Scriban.Template.Parse(
AttributeDeclarationTemplateString
);

public static readonly string ToolName = typeof(Constants).Assembly.GetName().Name;
public static readonly string ToolVersion = typeof(Constants).Assembly
.GetName()
.GetName()
.Version.ToString();
public static readonly string MinimalCodeHeaderTemplateString = $$$""""
/*
* <auto-generated>
* This code was generated by the{{{ToolName}}}, version {{{ToolVersion}}}
Expand All @@ -128,64 +128,64 @@ internal class {{ attribute_class_name }} : { { attribute_base_type.full_name }
* Generated: {{ timestamp }}
* Generated by: {{{System.Environment.UserName}}}
*/
"""";
public static readonly Scriban.Template MinimalCodeHeaderTemplate = Scriban.Template.Parse(
MinimalCodeHeaderTemplateString
);
public static string GenerateMininmalCodeHeader(string filename, string timestamp)
{
return MinimalCodeHeaderTemplate.Render(new { filename, timestamp });
}
public static string GenerateAttributeDeclaration(
string attributeName,
AttributeTargets attributeTargets = AttributeTargets.All,
Type baseType = default,
params AttributeProperty[] properties
)
{
baseType ??= typeof(Attribute);
var result =
MinimalCodeHeaderTemplate.Render(
new
{
filename = $"{attributeName}.cs",
timestamp = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm")
}
)
+ Environment.NewLine
+ AttributeDeclarationTemplate.Render(
new AttributeInfo(attributeName, baseType, attributeTargets.ToString(), properties)
);
return result;
}
public static string GenerateAttributeDeclaration(AttributeInfo attributeInfo)
{
return MinimalCodeHeaderTemplate.Render(attributeInfo);
}
public static string TrimToSentinel(this string codeHeader)
{
var sentinelIndex = codeHeader.IndexOf(BeginCodeHeaderSentinel);
if (sentinelIndex == -1)
{
return codeHeader;
}
return codeHeader.Substring(sentinelIndex + BeginCodeHeaderSentinel.Length).Trim();
}
public static IEnumerable<(string Name, string? Email)> ParseAuthors(string authors)
{
var authorsList = authors.Split(';');
foreach (var author in authorsList)
{
var authorParts = author.Split('<');
var authorName = authorParts.First().Trim();
var authorEmail = authorParts.Skip(1).FirstOrDefault()?.Trim().TrimEnd('>');
yield return (authorName, authorEmail);
}
}
"""";
public static readonly Scriban.Template MinimalCodeHeaderTemplate = Scriban.Template.Parse(
MinimalCodeHeaderTemplateString
);

public static string GenerateMininmalCodeHeader(string filename, string timestamp)
{
return MinimalCodeHeaderTemplate.Render(new { filename, timestamp });
}

public static string GenerateAttributeDeclaration(
string attributeName,
AttributeTargets attributeTargets = AttributeTargets.All,
Type baseType = default,
params AttributeProperty[] properties
)
{
baseType ??= typeof(Attribute);
var result =
MinimalCodeHeaderTemplate.Render(
new
{
filename = $"{attributeName}.cs",
timestamp = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm")
}
)
+ Environment.NewLine
+ AttributeDeclarationTemplate.Render(
new AttributeInfo(attributeName, baseType, attributeTargets.ToString(), properties)
);

return result;
}

public static string GenerateAttributeDeclaration(AttributeInfo attributeInfo)
{
return MinimalCodeHeaderTemplate.Render(attributeInfo);
}

public static string TrimToSentinel(this string codeHeader)
{
var sentinelIndex = codeHeader.IndexOf(BeginCodeHeaderSentinel);
if (sentinelIndex == -1)
{
return codeHeader;
}
return codeHeader.Substring(sentinelIndex + BeginCodeHeaderSentinel.Length).Trim();
}

public static IEnumerable<(string Name, string? Email)> ParseAuthors(string authors)
{
var authorsList = authors.Split(';');
foreach (var author in authorsList)
{
var authorParts = author.Split('<');
var authorName = authorParts.First().Trim();
var authorEmail = authorParts.Skip(1).FirstOrDefault()?.Trim().TrimEnd('>');
yield return (authorName, authorEmail);
}
}
}
Loading