1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-05-28 11:05:09 +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

@ -56,7 +56,7 @@ Value Interpreter::run(const ScopeNode& scope_node)
void Interpreter::enter_scope(const ScopeNode& scope_node)
{
m_scope_stack.append({ scope_node });
m_scope_stack.append({ scope_node, {} });
}
void Interpreter::exit_scope(const ScopeNode& scope_node)
@ -70,4 +70,34 @@ void Interpreter::do_return()
dbg() << "FIXME: Implement Interpreter::do_return()";
}
void Interpreter::declare_variable(String name)
{
m_scope_stack.last().variables.set(move(name), js_undefined());
}
void Interpreter::set_variable(String name, Value value)
{
for (ssize_t i = m_scope_stack.size() - 1; i >= 0; --i) {
auto& scope = m_scope_stack.at(i);
if (scope.variables.contains(name)) {
scope.variables.set(move(name), move(value));
return;
}
}
global_object().put(move(name), move(value));
}
Value Interpreter::get_variable(const String& name)
{
for (ssize_t i = m_scope_stack.size() - 1; i >= 0; --i) {
auto& scope = m_scope_stack.at(i);
auto value = scope.variables.get(name);
if (value.has_value())
return value.value();
}
return global_object().get(name);
}
}