Skip to content

Commit

Permalink
Merge branch 'master' into enum-missing-values
Browse files Browse the repository at this point in the history
  • Loading branch information
Rodrigo Cesar committed May 28, 2024
2 parents 96f4f91 + b9468d9 commit 1095cb7
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 1 deletion.
4 changes: 3 additions & 1 deletion lib/csharp-models-to-json/EnumCollector.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,11 @@ public override void VisitEnumDeclaration(EnumDeclarationSyntax node)
var values = new Dictionary<string, object>();

foreach (var member in node.Members) {
values[member.Identifier.ToString()] = member.EqualsValue != null
var value = member.EqualsValue != null
? member.EqualsValue.Value.ToString()
: null;

values[member.Identifier.ToString()] = value?.Replace("_", "");
}

this.Enums.Add(new Enum() {
Expand Down
33 changes: 33 additions & 0 deletions lib/csharp-models-to-json_test/ModelCollector_test.cs
Original file line number Diff line number Diff line change
Expand Up @@ -172,5 +172,38 @@ public void DictionaryInheritance_ReturnsIndexAccessor()
Assert.That(modelCollector.Models.First().BaseClasses, Is.Not.Null);
Assert.That(modelCollector.Models.First().BaseClasses, Is.EqualTo(new[] { "Dictionary<string, string>" }));
}

[Test]
public void EnumBinaryValue()
{
var tree = CSharpSyntaxTree.ParseText(@"
public enum A {
A = 1, // decimal: 1
B = 1_002, // decimal: 1002
C = 0b011, // binary: 3 in decimal
D = 0b_0000_0100, // binary: 4 in decimal
E = 0x005, // hexadecimal: 5 in decimal
F = 0x000_01a, // hexadecimal: 26 in decimal
}"
);

var root = (CompilationUnitSyntax)tree.GetRoot();

var enumCollector = new EnumCollector();
enumCollector.VisitEnumDeclaration(root.DescendantNodes().OfType<EnumDeclarationSyntax>().First());

var model = enumCollector.Enums.First();

Assert.That(model, Is.Not.Null);
Assert.That(model.Values, Is.Not.Null);

Assert.That(model.Values["A"], Is.EqualTo("1"));
Assert.That(model.Values["B"], Is.EqualTo("1002"));
Assert.That(model.Values["C"], Is.EqualTo("0b011"));
Assert.That(model.Values["D"], Is.EqualTo("0b00000100"));
Assert.That(model.Values["E"], Is.EqualTo("0x005"));
Assert.That(model.Values["F"], Is.EqualTo("0x00001a"));
}

}
}
9 changes: 9 additions & 0 deletions test-files/TestClass.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,13 @@ public class TestClass

public bool BooleanProperty { get; set; }
}

public enum TestEnum {
A = 1, // decimal: 1
B = 1_002, // decimal: 1002
C = 0b011, // binary: 3 in decimal
D = 0b_0000_0100, // binary: 4 in decimal
E = 0x005, // hexadecimal: 5 in decimal
F = 0x000_01a, // hexadecimal: 26 in decimal
}
}

0 comments on commit 1095cb7

Please sign in to comment.