mirror of
https://github.com/LadybirdBrowser/ladybird.git
synced 2025-04-21 20:15:17 +00:00
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:
parent
a96bf2c22e
commit
b6307beb6e
Notes:
sideshowbarker
2024-07-19 08:50:44 +09:00
Author: https://github.com/0xtechnobabble Commit: https://github.com/SerenityOS/serenity/commit/b6307beb6ef Pull-request: https://github.com/SerenityOS/serenity/pull/1380
2 changed files with 47 additions and 0 deletions
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -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,
|
||||
|
|
Loading…
Add table
Reference in a new issue