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) { static Value eval_if(const Ast& ast, Env& env) {
auto cond = eval(*ast.nodes[0], env); const auto& nodes = ast.nodes;
if (cond.to_bool()) {
return eval(*ast.nodes[1], env); for (auto i = 0u; i < nodes.size(); i += 2) {
} else if (ast.nodes.size() > 2) { if (i + 1 == nodes.size()) {
return eval(*ast.nodes[2], env); return eval(*nodes[i], env);
} else {
auto cond = eval(*nodes[i], env);
if (cond.to_bool()) {
return eval(*nodes[i + 1], env);
}
}
} }
return Value(); return Value();
} }

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

Loading…
Cancel
Save