Skip to content

Commit

Permalink
For loops now can use existing variables
Browse files Browse the repository at this point in the history
  • Loading branch information
Relfos committed Sep 21, 2023
1 parent 7956c01 commit 7b6855b
Showing 1 changed file with 26 additions and 6 deletions.
32 changes: 26 additions & 6 deletions Library/src/Compilers/TombLangCompiler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1184,10 +1184,22 @@ private StatementBlock ParseCommandBlock(Scope scope, MethodDeclaration method)

ExpectToken("(");

ExpectToken("local");
bool mustExist;

var next = FetchToken();
if (next.value == "local")
{
mustExist = false;
}
else
{
mustExist = true;
Rewind();
}

AssignStatement initCmd;
forCommand.loopVar = ParseVariableDeclaration(scope, out initCmd);
forCommand.loopVar = ParseVariableDeclaration(scope, out initCmd, mustExist);

if (initCmd == null)
{
throw new CompilerException("variable missing initialization statement in for loop");
Expand All @@ -1212,7 +1224,7 @@ private StatementBlock ParseCommandBlock(Scope scope, MethodDeclaration method)
throw new CompilerException($"expected variable {varName} (temporary compiler limitation, no complex for statements supported!)");
}

var next = FetchToken();
next = FetchToken();

if (next.kind == TokenKind.Postfix)
{
Expand Down Expand Up @@ -1457,7 +1469,7 @@ private StatementBlock ParseCommandBlock(Scope scope, MethodDeclaration method)
}
}

private VarDeclaration ParseVariableDeclaration(Scope scope, out AssignStatement assignment)
private VarDeclaration ParseVariableDeclaration(Scope scope, out AssignStatement assignment, bool mustExist = false)
{
var varName = ExpectIdentifier();

Expand All @@ -1475,9 +1487,17 @@ private VarDeclaration ParseVariableDeclaration(Scope scope, out AssignStatement

Expression initExpr = ParseVariableInitialization(scope, ref type);

var varDecl = new VarDeclaration(scope, varName, type, VarStorage.Local);
VarDeclaration varDecl;

scope.AddVariable(varDecl);
if (mustExist)
{
varDecl = scope.FindVariable(varName);
}
else
{
varDecl = new VarDeclaration(scope, varName, type, VarStorage.Local);
scope.AddVariable(varDecl);
}

if (initExpr != null)
{
Expand Down

0 comments on commit 7b6855b

Please sign in to comment.