Added 'else if' support.

pull/3/head
yhirose 9 years ago
parent 0ed897dd01
commit a7c2de1c32
  1. 17
      language/interpreter.cc
  2. 2
      language/parser.cc

@ -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();
}

@ -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

Loading…
Cancel
Save