diff --git a/examples/var.funk b/examples/var.funk new file mode 100644 index 0000000000000000000000000000000000000000..d6e86898f4a8942041bfb57758591917b70928b2 --- /dev/null +++ b/examples/var.funk @@ -0,0 +1,2 @@ +numb test = 5; +print(test); \ No newline at end of file diff --git a/include/ast/declaration/VariableNode.h b/include/ast/declaration/VariableNode.h index 1e5b899d473e5f226329af662435de197e7ef3b9..f26d97efe025e1b296456f3ee919a372ca568c09 100644 --- a/include/ast/declaration/VariableNode.h +++ b/include/ast/declaration/VariableNode.h @@ -2,6 +2,7 @@ #include "ast/Node.h" #include "ast/expression/ExpressionNode.h" +#include "parser/Scope.h" #include "token/TokenType.h" namespace funk @@ -12,6 +13,7 @@ class VariableNode : public ExpressionNode public: VariableNode(const SourceLocation& location, const String& identifier, bool is_mutable, TokenType type, ExpressionNode* value); + VariableNode(const SourceLocation& location, const String& identifier); ~VariableNode() override; Node* evaluate() const override; diff --git a/source/ast/declaration/VariableNode.cc b/source/ast/declaration/VariableNode.cc index 0639e34998016008231c2c66f0a71eb0f6aec7d6..69958e164d361185867b997f3bf5deebb813c676 100644 --- a/source/ast/declaration/VariableNode.cc +++ b/source/ast/declaration/VariableNode.cc @@ -7,6 +7,12 @@ VariableNode::VariableNode( ExpressionNode{location}, identifier{identifier}, is_mutable{is_mutable}, type{type}, value{value} { } + +VariableNode::VariableNode(const SourceLocation& location, const String& identifier) : + ExpressionNode{location}, identifier{identifier} +{ +} + VariableNode::~VariableNode() { if (value) { delete value; } @@ -15,6 +21,12 @@ VariableNode::~VariableNode() Node* VariableNode::evaluate() const { + if (value == nullptr) + { + Node* result = Scope::instance().get(identifier); + if (result == nullptr) { throw RuntimeError(get_location(), "Undefined variable '" + identifier + "'"); } + return result; + } return new VariableNode(get_location(), identifier, is_mutable, type, value); } diff --git a/source/parser/Parser.cc b/source/parser/Parser.cc index eb66ad07773bfd2a15ee1526ae67accf0a8d60c6..4933598f627235fbb4c4e0f4ac3cf6baae4c6e24 100644 --- a/source/parser/Parser.cc +++ b/source/parser/Parser.cc @@ -328,7 +328,7 @@ Node* Parser::parse_identifier() new VariableNode(identifier.get_location(), identifier.get_lexeme(), false, TokenType::NONE, nullptr)); } - return new VariableNode(identifier.get_location(), identifier.get_lexeme(), false, TokenType::NONE, nullptr); + return new VariableNode(identifier.get_location(), identifier.get_lexeme()); } Node* Parser::parse_call(const Token& identifier)