summaryrefslogtreecommitdiff
path: root/Libraries/LibJS/AST.cpp
diff options
context:
space:
mode:
authorAndreas Kling <kling@serenityos.org>2020-03-09 21:13:55 +0100
committerAndreas Kling <kling@serenityos.org>2020-03-09 21:49:20 +0100
commit1382dbc5e19cb16b3eee672745d3782188ed5749 (patch)
tree6a6748e2b55b7893c1a5f8c116293d33be1f5e49 /Libraries/LibJS/AST.cpp
parentac3c19b91cd4c8785707952cf890e6c496c33790 (diff)
downloadserenity-1382dbc5e19cb16b3eee672745d3782188ed5749.zip
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.
Diffstat (limited to 'Libraries/LibJS/AST.cpp')
-rw-r--r--Libraries/LibJS/AST.cpp60
1 files changed, 60 insertions, 0 deletions
diff --git a/Libraries/LibJS/AST.cpp b/Libraries/LibJS/AST.cpp
index 2e6acb947c..acac0b3273 100644
--- a/Libraries/LibJS/AST.cpp
+++ b/Libraries/LibJS/AST.cpp
@@ -393,4 +393,64 @@ void WhileStatement::dump(int indent) const
body().dump(indent + 1);
}
+Value Identifier::execute(Interpreter& interpreter) const
+{
+ return interpreter.get_variable(string());
+}
+
+void Identifier::dump(int indent) const
+{
+ print_indent(indent);
+ printf("Identifier \"%s\"\n", m_string.characters());
+}
+
+Value AssignmentExpression::execute(Interpreter& interpreter) const
+{
+ ASSERT(m_lhs->is_identifier());
+ auto name = static_cast<const Identifier&>(*m_lhs).string();
+ auto rhs_result = m_rhs->execute(interpreter);
+
+ switch (m_op) {
+ case AssignmentOp::Assign:
+ interpreter.set_variable(name, rhs_result);
+ break;
+ }
+ return rhs_result;
+}
+
+void AssignmentExpression::dump(int indent) const
+{
+ const char* op_string = nullptr;
+ switch (m_op) {
+ case AssignmentOp::Assign:
+ op_string = "=";
+ break;
+ }
+
+ ASTNode::dump(indent);
+ print_indent(indent + 1);
+ printf("%s\n", op_string);
+ m_lhs->dump(indent + 1);
+ m_rhs->dump(indent + 1);
+}
+
+Value VariableDeclaration::execute(Interpreter& interpreter) const
+{
+ interpreter.declare_variable(name().string());
+ if (m_initializer) {
+ auto initalizer_result = m_initializer->execute(interpreter);
+ interpreter.set_variable(name().string(), initalizer_result);
+ }
+ return js_undefined();
+}
+
+
+void VariableDeclaration::dump(int indent) const
+{
+ ASTNode::dump(indent);
+ m_name->dump(indent + 1);
+ if (m_initializer)
+ m_initializer->dump(indent + 1);
+}
+
}