From 4e62dcd6e695740ff0e1e09b69d09713b473e9a7 Mon Sep 17 00:00:00 2001 From: 0xtechnobabble <0xtechnobabble@protonmail.com> Date: Sun, 8 Mar 2020 07:53:02 +0200 Subject: [PATCH] LibJS: Add typed comparison operator The `===` operator allows us to compare two values while taking their type into consideration. --- Libraries/LibJS/AST.cpp | 42 +++++++++++++++++++++++++++++++++++++++++ Libraries/LibJS/AST.h | 1 + 2 files changed, 43 insertions(+) diff --git a/Libraries/LibJS/AST.cpp b/Libraries/LibJS/AST.cpp index 7005343bb7..1b8a666d31 100644 --- a/Libraries/LibJS/AST.cpp +++ b/Libraries/LibJS/AST.cpp @@ -75,6 +75,29 @@ Value sub(Value lhs, Value rhs) return Value(lhs.as_double() - rhs.as_double()); } +const Value typed_eq(const Value lhs, const Value rhs) +{ + if (rhs.type() != lhs.type()) + return Value(false); + + switch (lhs.type()) { + case Value::Type::Undefined: + return Value(true); + case Value::Type::Null: + return Value(true); + case Value::Type::Number: + return Value(lhs.as_double() == rhs.as_double()); + case Value::Type::String: + return Value(lhs.as_string() == rhs.as_string()); + case Value::Type::Boolean: + return Value(lhs.as_bool() == rhs.as_bool()); + case Value::Type::Object: + return Value(lhs.as_object() == rhs.as_object()); + } + + ASSERT_NOT_REACHED(); +} + Value BinaryExpression::execute(Interpreter& interpreter) const { auto lhs_result = m_lhs->execute(interpreter); @@ -85,6 +108,12 @@ Value BinaryExpression::execute(Interpreter& interpreter) const return add(lhs_result, rhs_result); case BinaryOp::Minus: return sub(lhs_result, rhs_result); + case BinaryOp::TypedEquals: + return typed_eq(lhs_result, rhs_result); + } + + ASSERT_NOT_REACHED(); +} } ASSERT_NOT_REACHED(); @@ -119,6 +148,19 @@ void BinaryExpression::dump(int indent) const case BinaryOp::Minus: op_string = "-"; break; + case BinaryOp::TypedEquals: + op_string = "==="; + break; + } + + print_indent(indent); + printf("%s\n", class_name()); + m_lhs->dump(indent + 1); + print_indent(indent + 1); + printf("%s\n", op_string); + m_rhs->dump(indent + 1); +} + } print_indent(indent); diff --git a/Libraries/LibJS/AST.h b/Libraries/LibJS/AST.h index 7c1ca77866..6d8fbd66c8 100644 --- a/Libraries/LibJS/AST.h +++ b/Libraries/LibJS/AST.h @@ -129,6 +129,7 @@ private: enum class BinaryOp { Plus, Minus, + TypedEquals, }; class BinaryExpression : public Expression {