Added 'else if' support.

This commit is contained in:
yhirose 2015-05-28 21:35:58 -04:00
parent 0ed897dd01
commit a7c2de1c32
2 changed files with 13 additions and 6 deletions

View File

@ -56,12 +56,19 @@ private:
}
static Value eval_if(const Ast& ast, Env& env) {
auto cond = eval(*ast.nodes[0], env);
if (cond.to_bool()) {
return eval(*ast.nodes[1], env);
} else if (ast.nodes.size() > 2) {
return eval(*ast.nodes[2], env);
const auto& nodes = ast.nodes;
for (auto i = 0u; i < nodes.size(); i += 2) {
if (i + 1 == nodes.size()) {
return eval(*nodes[i], env);
} else {
auto cond = eval(*nodes[i], env);
if (cond.to_bool()) {
return eval(*nodes[i + 1], env);
}
}
}
return Value();
}

View File

@ -11,7 +11,7 @@ static auto g_grammar = R"(
EXPRESSION <- ASSIGNMENT / PRIMARY
ASSIGNMENT <- IDENTIFIER '=' _ EXPRESSION
WHILE <- 'while' _ EXPRESSION BLOCK
IF <- 'if' _ EXPRESSION BLOCK ('else' _ BLOCK)?
IF <- 'if' _ EXPRESSION BLOCK ('else' _ 'if' _ EXPRESSION BLOCK)* ('else' _ BLOCK)?
FUNCTION <- 'fn' _ PARAMETERS BLOCK
PARAMETERS <- '(' _ IDENTIFIER* ')' _
FUNCTION_CALL <- IDENTIFIER ARGUMENTS