srctree

Robin Linden parent e193b0ef f1f6e33e
js: Create more specific Literal types

inlinesplit
js/ast.h added: 22, removed: 11, total 11
@@ -62,13 +62,24 @@ private:
std::string name_;
};
 
class Literal : public Expression {
class Literal : public Expression {};
 
class NumericLiteral : public Literal {
public:
explicit Literal(Value value) : value_{std::move(value)} {}
Value execute(Context &) const override { return value_; }
explicit NumericLiteral(double value) : value_{value} {}
Value execute(Context &) const override { return Value{value_}; }
 
private:
Value value_;
double value_{};
};
 
class StringLiteral : public Literal {
public:
explicit StringLiteral(std::string value) : value_{std::move(value)} {}
Value execute(Context &) const override { return Value{value_}; }
 
private:
std::string value_{};
};
 
// TODO(robinlinden): Support more operators.
 
js/ast_test.cpp added: 22, removed: 11, total 11
@@ -15,13 +15,13 @@ using etest::expect_eq;
int main() {
etest::test("literals", [] {
js::ast::Context ctx;
expect_eq(Literal{Value{5.}}.execute(ctx), Value{5.});
expect_eq(Literal{Value{"hello"s}}.execute(ctx), Value{"hello"s});
expect_eq(NumericLiteral{5.}.execute(ctx), Value{5.});
expect_eq(StringLiteral{"hello"s}.execute(ctx), Value{"hello"s});
});
 
etest::test("variable declaration", [] {
// AST for `var a = 1`
auto init = std::make_unique<Literal>(Value{1.});
auto init = std::make_unique<NumericLiteral>(1.);
auto id = std::make_unique<Identifier>("a");
auto declarator = VariableDeclarator{};
declarator.id = std::move(id);
@@ -40,12 +40,12 @@ int main() {
 
etest::test("binary expression", [] {
auto plus_expr = BinaryExpression{
BinaryOperator::Plus, std::make_unique<Literal>(Value{11.}), std::make_unique<Literal>(Value{31.})};
BinaryOperator::Plus, std::make_unique<NumericLiteral>(11.), std::make_unique<NumericLiteral>(31.)};
Context ctx;
expect_eq(plus_expr.execute(ctx), Value{42.});
 
auto minus_expr = BinaryExpression{
BinaryOperator::Minus, std::make_unique<Literal>(Value{11.}), std::make_unique<Literal>(Value{31.})};
BinaryOperator::Minus, std::make_unique<NumericLiteral>(11.), std::make_unique<NumericLiteral>(31.)};
expect_eq(minus_expr.execute(ctx), Value{-20.});
});