Skip to content

Commit 7b6855b

Browse files
committed
For loops now can use existing variables
1 parent 7956c01 commit 7b6855b

File tree

1 file changed

+26
-6
lines changed

1 file changed

+26
-6
lines changed

Library/src/Compilers/TombLangCompiler.cs

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1184,10 +1184,22 @@ private StatementBlock ParseCommandBlock(Scope scope, MethodDeclaration method)
11841184

11851185
ExpectToken("(");
11861186

1187-
ExpectToken("local");
1187+
bool mustExist;
1188+
1189+
var next = FetchToken();
1190+
if (next.value == "local")
1191+
{
1192+
mustExist = false;
1193+
}
1194+
else
1195+
{
1196+
mustExist = true;
1197+
Rewind();
1198+
}
11881199

11891200
AssignStatement initCmd;
1190-
forCommand.loopVar = ParseVariableDeclaration(scope, out initCmd);
1201+
forCommand.loopVar = ParseVariableDeclaration(scope, out initCmd, mustExist);
1202+
11911203
if (initCmd == null)
11921204
{
11931205
throw new CompilerException("variable missing initialization statement in for loop");
@@ -1212,7 +1224,7 @@ private StatementBlock ParseCommandBlock(Scope scope, MethodDeclaration method)
12121224
throw new CompilerException($"expected variable {varName} (temporary compiler limitation, no complex for statements supported!)");
12131225
}
12141226

1215-
var next = FetchToken();
1227+
next = FetchToken();
12161228

12171229
if (next.kind == TokenKind.Postfix)
12181230
{
@@ -1457,7 +1469,7 @@ private StatementBlock ParseCommandBlock(Scope scope, MethodDeclaration method)
14571469
}
14581470
}
14591471

1460-
private VarDeclaration ParseVariableDeclaration(Scope scope, out AssignStatement assignment)
1472+
private VarDeclaration ParseVariableDeclaration(Scope scope, out AssignStatement assignment, bool mustExist = false)
14611473
{
14621474
var varName = ExpectIdentifier();
14631475

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

14761488
Expression initExpr = ParseVariableInitialization(scope, ref type);
14771489

1478-
var varDecl = new VarDeclaration(scope, varName, type, VarStorage.Local);
1490+
VarDeclaration varDecl;
14791491

1480-
scope.AddVariable(varDecl);
1492+
if (mustExist)
1493+
{
1494+
varDecl = scope.FindVariable(varName);
1495+
}
1496+
else
1497+
{
1498+
varDecl = new VarDeclaration(scope, varName, type, VarStorage.Local);
1499+
scope.AddVariable(varDecl);
1500+
}
14811501

14821502
if (initExpr != null)
14831503
{

0 commit comments

Comments
 (0)