enums
This commit is contained in:
@@ -78,9 +78,10 @@ public sealed class Parser
|
||||
{
|
||||
Symbol.Func => ParseFunc(startIndex, exported, null),
|
||||
Symbol.Struct => ParseStruct(startIndex, exported),
|
||||
Symbol.Enum => ParseEnum(startIndex, exported),
|
||||
_ => throw new ParseException(Diagnostic
|
||||
.Error($"Expected 'func', 'struct', 'import' or 'module' but found '{keyword.Symbol}'")
|
||||
.WithHelp("Valid top level statements are 'func', 'struct', 'import' and 'module'")
|
||||
.Error($"Expected 'func', 'struct', 'enum', 'import' or 'module' but found '{keyword.Symbol}'")
|
||||
.WithHelp("Valid top level statements are 'func', 'struct', 'enum', 'import' and 'module'")
|
||||
.At(keyword)
|
||||
.Build())
|
||||
};
|
||||
@@ -176,6 +177,54 @@ public sealed class Parser
|
||||
return new StructSyntax(GetTokens(startIndex), name.Value, exported, fields);
|
||||
}
|
||||
|
||||
private EnumSyntax ParseEnum(int startIndex, bool exported)
|
||||
{
|
||||
var name = ExpectIdentifier();
|
||||
|
||||
TypeSyntax? type = null;
|
||||
|
||||
if (TryExpectSymbol(Symbol.Colon))
|
||||
{
|
||||
type = ParseType();
|
||||
}
|
||||
|
||||
List<EnumFieldSyntax> fields = [];
|
||||
|
||||
ExpectSymbol(Symbol.OpenBrace);
|
||||
|
||||
long value = -1;
|
||||
|
||||
while (!TryExpectSymbol(Symbol.CloseBrace))
|
||||
{
|
||||
var memberStartIndex = _tokenIndex;
|
||||
var fieldName = ExpectIdentifier().Value;
|
||||
long fieldValue;
|
||||
|
||||
if (TryExpectSymbol(Symbol.Assign))
|
||||
{
|
||||
if (!TryExpectIntLiteral(out var intLiteralToken))
|
||||
{
|
||||
throw new ParseException(Diagnostic
|
||||
.Error("Value of enum field must be an integer literal")
|
||||
.At(CurrentToken)
|
||||
.Build());
|
||||
}
|
||||
|
||||
fieldValue = Convert.ToInt64(intLiteralToken.Value, intLiteralToken.Base);
|
||||
value = fieldValue;
|
||||
}
|
||||
else
|
||||
{
|
||||
fieldValue = value + 1;
|
||||
value = fieldValue;
|
||||
}
|
||||
|
||||
fields.Add(new EnumFieldSyntax(GetTokens(memberStartIndex), fieldName, fieldValue));
|
||||
}
|
||||
|
||||
return new EnumSyntax(GetTokens(startIndex), name.Value, exported, type, fields);
|
||||
}
|
||||
|
||||
private StatementSyntax ParseStatement()
|
||||
{
|
||||
var startIndex = _tokenIndex;
|
||||
|
||||
Reference in New Issue
Block a user