This commit is contained in:
nub31
2025-05-28 14:15:16 +02:00
parent 3fe47a0ed0
commit bba7906221
7 changed files with 93 additions and 53 deletions

View File

@@ -15,7 +15,7 @@ public class Lexer
["break"] = Symbol.Break,
["continue"] = Symbol.Continue,
["return"] = Symbol.Return,
["new"] = Symbol.New,
["alloc"] = Symbol.Alloc,
["struct"] = Symbol.Struct,
["let"] = Symbol.Let,
};

View File

@@ -38,11 +38,11 @@ public enum Symbol
Minus,
Star,
ForwardSlash,
New,
Struct,
Caret,
Ampersand,
DoubleColon,
Namespace,
Let
Let,
Alloc
}

View File

@@ -507,43 +507,6 @@ public class Parser
expr = new CastNode(GetTokensForNode(startIndex), type, expressionToCast);
break;
}
case Symbol.New:
{
var next = Peek();
if (next.Value is SymbolToken { Symbol: Symbol.OpenBracket })
{
Next();
var size = ParseExpression();
ExpectSymbol(Symbol.CloseBracket);
var type = ParseType();
expr = new ArrayInitializerNode(GetTokensForNode(startIndex), size, type);
}
else
{
var type = ParseType();
Dictionary<string, ExpressionNode> initializers = [];
ExpectSymbol(Symbol.OpenBrace);
while (!TryExpectSymbol(Symbol.CloseBrace))
{
var name = ExpectIdentifier().Value;
ExpectSymbol(Symbol.Assign);
var value = ParseExpression();
initializers.Add(name, value);
}
if (type is not NubStructType structType)
{
throw new ParseException(Diagnostic
.Error($"Cannot use new keyword on type {type}")
.At(symbolToken)
.Build());
}
expr = new StructInitializerNode(GetTokensForNode(startIndex), structType, initializers);
}
break;
}
case Symbol.Ampersand:
{
var expression = ParsePrimaryExpression();
@@ -562,6 +525,38 @@ public class Parser
expr = new UnaryExpressionNode(GetTokensForNode(startIndex), UnaryExpressionOperator.Invert, expression);
break;
}
case Symbol.OpenBracket:
{
var size = ParseExpression();
ExpectSymbol(Symbol.CloseBracket);
var type = ParseType();
expr = new ArrayInitializerNode(GetTokensForNode(startIndex), size, type);
break;
}
case Symbol.Alloc:
{
var type = ParseType();
Dictionary<string, ExpressionNode> initializers = [];
ExpectSymbol(Symbol.OpenBrace);
while (!TryExpectSymbol(Symbol.CloseBrace))
{
var name = ExpectIdentifier().Value;
ExpectSymbol(Symbol.Assign);
var value = ParseExpression();
initializers.Add(name, value);
}
if (type is not NubStructType structType)
{
throw new ParseException(Diagnostic
.Error($"Cannot use new keyword on type {type}")
.At(symbolToken)
.Build());
}
expr = new StructInitializerNode(GetTokensForNode(startIndex), structType, initializers);
break;
}
default:
{
throw new ParseException(Diagnostic