Skip to content

Commit

Permalink
Imported some recent changes to CodeFormatter from bug fixes to Jaspe…
Browse files Browse the repository at this point in the history
…rFx.CodeGeneration
  • Loading branch information
jeremydmiller committed Dec 27, 2024
1 parent 60196ea commit c865110
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 1 deletion.
23 changes: 23 additions & 0 deletions src/CodegenTests/Codegen/CodeFormatterTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,29 @@ public void write_string()
.ShouldBe("\"Hello!\"");
}

[Fact]
public void write_string_array()
{
CodeFormatter.Write(new string[]{"Hello!", "Bad", "Good"})
.ShouldBe("new string[]{\"Hello!\", \"Bad\", \"Good\"}");
}

[Fact]
public void write_int_array()
{
CodeFormatter.Write(new int[]{1, 2, 4})
.ShouldBe("new int[]{1, 2, 4}");

CodeFormatter.Write(new int[]{1, 2})
.ShouldBe("new int[]{1, 2}");

CodeFormatter.Write(new int[]{1})
.ShouldBe("new int[]{1}");

CodeFormatter.Write(new int[]{})
.ShouldBe("new int[]{}");
}

[Fact]
public void write_enum()
{
Expand Down
39 changes: 38 additions & 1 deletion src/JasperFx/CodeGeneration/CodeFormatter.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using JasperFx.CodeGeneration.Model;
using JasperFx.Core;
using JasperFx.Core.Reflection;

namespace JasperFx.CodeGeneration;
Expand All @@ -8,7 +9,7 @@ public static class CodeFormatter
public static string Write(object? value)
{
// TODO -- add Guid, int, double, long, bool

if (value == null)
{
return "null";
Expand All @@ -29,6 +30,42 @@ public static string Write(object? value)
return value.GetType().FullNameInCode() + "." + value;
}

if (value.GetType() == typeof(string[]))
{
var array = (string[])value;
return $"new string[]{{{array.Select(Write).Join(", ")}}}";
}

if (value.GetType().IsArray)
{
var code = $"new {value.GetType().GetElementType().FullNameInCode()}[]{{";

var enumerable = (Array)value;
switch (enumerable.Length)
{
case 0:

break;
case 1:
code += Write(enumerable.GetValue(0));
break;

default:
for (int i = 0; i < enumerable.Length - 1; i++)
{
code += Write(enumerable.GetValue(i));
code += ", ";
}

code += Write(enumerable.GetValue(enumerable.Length - 1));
break;
}

code += "}";

return code;
}

if (value is Type t)
{
return $"typeof({t.FullNameInCode()})";
Expand Down

0 comments on commit c865110

Please sign in to comment.