Skip to content

Commit

Permalink
Support else if / else in if blocks
Browse files Browse the repository at this point in the history
  • Loading branch information
ethanmoffat committed Feb 5, 2022
1 parent aec22de commit 14cf50d
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
10 changes: 10 additions & 0 deletions EOBot/Interpreter/States/BlockEvaluator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,16 @@ protected async Task<(EvalResult, string, BotToken)> EvaluateBlockAsync(ProgramS

protected void SkipBlock(ProgramState input)
{
// ensure that for 'else if' the if condition is skipped as well
var current = input.Current();
if (current.TokenType == BotTokenType.Keyword && current.TokenValue == "if")
{
input.Expect(BotTokenType.Keyword);
input.Expect(BotTokenType.LParen);
while (!input.Expect(BotTokenType.RParen))
input.SkipToken();
}

// potential newline character - skip so we can advance execution beyond the block
input.Expect(BotTokenType.NewLine);

Expand Down
29 changes: 29 additions & 0 deletions EOBot/Interpreter/States/IfEvaluator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,38 @@ public override async Task<(EvalResult, string, BotToken)> EvaluateAsync(Program
return await EvaluateBlockAsync(input);

SkipBlock(input);

if (IsElse(input))
{
input.Expect(BotTokenType.Keyword);

var elseIfRes = await Evaluator<IfEvaluator>().EvaluateAsync(input);
if (elseIfRes.Result == EvalResult.Failed)
return elseIfRes;
else if (elseIfRes.Result == EvalResult.Ok)
{
// skip the rest of the following blocks if evaluated
while (IsElse(input))
{
input.Expect(BotTokenType.Keyword);
SkipBlock(input);
}

return elseIfRes;
}

// if not a match for else if, it is an else block
return await EvaluateBlockAsync(input);
}
}

return (result, reason, token);
}

private bool IsElse(ProgramState input)
{
var current = input.Current();
return current.TokenType == BotTokenType.Keyword && current.TokenValue == "else";
}
}
}

0 comments on commit 14cf50d

Please sign in to comment.