1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-25 04:07:44 +00:00

LibJS: Add basic support for (scoped) variables

It's now possible to assign expressions to variables. The variables are
put into the current scope of the interpreter.

Variable lookup follows the scope chain, ending in the global object.
This commit is contained in:
Andreas Kling 2020-03-09 21:13:55 +01:00
parent ac3c19b91c
commit 1382dbc5e1
5 changed files with 224 additions and 19 deletions

View file

@ -31,24 +31,13 @@
#include <LibJS/Value.h>
#include <stdio.h>
//static void build_program_1(JS::Program&);
static void build_program_2(JS::Program&);
int main()
{
// function foo() { return (1 + 2) + 3; }
// foo();
auto program = make<JS::Program>();
auto block = make<JS::BlockStatement>();
block->append<JS::ReturnStatement>(
make<JS::BinaryExpression>(
JS::BinaryOp::Plus,
make<JS::BinaryExpression>(
JS::BinaryOp::Plus,
make<JS::Literal>(JS::Value(1)),
make<JS::Literal>(JS::Value(2))),
make<JS::Literal>(JS::Value(3))));
program->append<JS::FunctionDeclaration>("foo", move(block));
program->append<JS::CallExpression>("foo");
build_program_2(*program);
program->dump(0);
@ -68,3 +57,59 @@ int main()
interpreter.heap().collect_garbage();
return 0;
}
#if 0
void build_program_1(JS::Program& program)
{
// function foo() { return (1 + 2) + 3; }
// foo();
auto block = make<JS::BlockStatement>();
block->append<JS::ReturnStatement>(
make<JS::BinaryExpression>(
JS::BinaryOp::Plus,
make<JS::BinaryExpression>(
JS::BinaryOp::Plus,
make<JS::Literal>(JS::Value(1)),
make<JS::Literal>(JS::Value(2))),
make<JS::Literal>(JS::Value(3))));
program.append<JS::FunctionDeclaration>("foo", move(block));
program.append<JS::CallExpression>("foo");
}
#endif
void build_program_2(JS::Program& program)
{
// c = 1;
// function foo() {
// var a = 5;
// var b = 7;
// return a + b + c;
// }
// foo();
program.append<JS::AssignmentExpression>(
JS::AssignmentOp::Assign,
make<JS::Identifier>("c"),
make<JS::Literal>(JS::Value(1)));
auto block = make<JS::BlockStatement>();
block->append<JS::VariableDeclaration>(
make<JS::Identifier>("a"),
make<JS::Literal>(JS::Value(5)));
block->append<JS::VariableDeclaration>(
make<JS::Identifier>("b"),
make<JS::Literal>(JS::Value(7)));
block->append<JS::ReturnStatement>(
make<JS::BinaryExpression>(
JS::BinaryOp::Plus,
make<JS::BinaryExpression>(
JS::BinaryOp::Plus,
make<JS::Identifier>("a"),
make<JS::Identifier>("b")),
make<JS::Identifier>("c")));
program.append<JS::FunctionDeclaration>("foo", move(block));
program.append<JS::CallExpression>("foo");
}