LibJS: Implement if statements

If statements execute a certain action or an alternative one depending
on whether the tested condition is true or false, this commit helps
establish basic control flow capabilities in the AST.
This commit is contained in:
0xtechnobabble 2020-03-08 07:58:58 +02:00 committed by Andreas Kling
parent a96bf2c22e
commit b6307beb6e
Notes: sideshowbarker 2024-07-19 08:50:44 +09:00
2 changed files with 47 additions and 0 deletions

View file

@ -61,6 +61,16 @@ Value ReturnStatement::execute(Interpreter& interpreter) const
return value;
}
Value IfStatement::execute(Interpreter& interpreter) const
{
auto predicate_result = m_predicate->execute(interpreter);
if (predicate_result.as_bool())
return interpreter.run(*m_consequent);
else
return interpreter.run(*m_alternate);
}
Value add(Value lhs, Value rhs)
{
ASSERT(lhs.is_number());
@ -236,4 +246,17 @@ void ReturnStatement::dump(int indent) const
argument().dump(indent + 1);
}
void IfStatement::dump(int indent) const
{
ASTNode::dump(indent);
print_indent(indent);
printf("If\n");
predicate().dump(indent + 1);
consequent().dump(indent + 1);
print_indent(indent);
printf("Else\n");
alternate().dump(indent + 1);
}
}

View file

@ -127,6 +127,30 @@ private:
NonnullOwnPtr<Expression> m_argument;
};
class IfStatement : public ASTNode {
public:
explicit IfStatement(NonnullOwnPtr<Expression> predicate, NonnullOwnPtr<ScopeNode> consequent, NonnullOwnPtr<ScopeNode> alternate)
: m_predicate(move(predicate))
, m_consequent(move(consequent))
, m_alternate(move(alternate))
{
}
const Expression& predicate() const { return *m_predicate; }
const ScopeNode& consequent() const { return *m_consequent; }
const ScopeNode& alternate() const { return *m_alternate; }
virtual Value execute(Interpreter&) const override;
virtual void dump(int indent) const override;
private:
virtual const char* class_name() const override { return "IfStatement"; }
NonnullOwnPtr<Expression> m_predicate;
NonnullOwnPtr<ScopeNode> m_consequent;
NonnullOwnPtr<ScopeNode> m_alternate;
};
enum class BinaryOp {
Plus,
Minus,