Skip to content

Commit

Permalink
feat: Add automatic enum member initialization
Browse files Browse the repository at this point in the history
  • Loading branch information
furesoft committed Feb 6, 2025
1 parent e4fe33a commit b54e5d2
Showing 1 changed file with 42 additions and 1 deletion.
43 changes: 42 additions & 1 deletion NewSource/SocordiaC/Compilation/Listeners/CollectEnumListener.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using MrKWatkins.Ast.Listening;
using Socordia.CodeAnalysis.AST;
using Socordia.CodeAnalysis.AST.Declarations;
using Socordia.CodeAnalysis.AST.Literals;

namespace SocordiaC.Compilation.Listeners;

Expand All @@ -17,11 +18,21 @@ protected override void ListenToNode(Driver context, EnumDeclaration node)
type.CreateField("value__", new TypeSig(Utils.GetTypeFromNode(node.BaseType, type)),
FieldAttributes.Public | FieldAttributes.SpecialName | FieldAttributes.RTSpecialName);

if (!ValidateEnumMembers(node))
{
return;
}

// .field public static literal valuetype Color R = int32(0)
foreach (var astNode in node.Children)
for (int memberIndex = 0; memberIndex < node.Children.Count; memberIndex++)
{
var member = (EnumMemberDeclaration)astNode;

if (memberIndex.Value is EmptyNode)
{
member.Value.Replace(new LiteralNode(memberIndex));
}

type.CreateField(member.Name.Name, new TypeSig(type),
FieldAttributes.Public | FieldAttributes.Literal | FieldAttributes.Static | FieldAttributes.HasDefault,
Utils.GetLiteralValue(member.Value));
Expand All @@ -30,6 +41,36 @@ protected override void ListenToNode(Driver context, EnumDeclaration node)
Utils.EmitAnnotations(node, type);
}

private bool ValidateEnumMembers(EnumDeclaration node)
{
bool hasSpecifiedValues = false;
bool hasUnspecifiedValues = false;

foreach (var child in node.Children)
{
if (child is EnumMemberDeclaration member)
{
if (member.Value is EmptyNode)
{
hasUnspecifiedValues = true;
}
else
{
hasSpecifiedValues = true;
}
}

if (hasSpecifiedValues && hasUnspecifiedValues)
{
node.AddError("Cannot mix specified and unspecified enum values");
return false;
}
}

return true;
}


private TypeAttributes GetModifiers(Declaration node)
{
var attrs = TypeAttributes.Public;
Expand Down

0 comments on commit b54e5d2

Please sign in to comment.