From 2456d999d62ad3a4897f85042ac992725f9aa9d2 Mon Sep 17 00:00:00 2001 From: Markus Hauschild Date: Sat, 1 Jun 2013 20:29:32 +0200 Subject: [PATCH] Scoped Variables --- inc/AST/CodeGenVisitor.h | 6 ++++-- src/AST/CodeGenVisitor.cpp | 31 +++++++++++++++++++++---------- 2 files changed, 25 insertions(+), 12 deletions(-) diff --git a/inc/AST/CodeGenVisitor.h b/inc/AST/CodeGenVisitor.h index 06c3767..8dc3e16 100644 --- a/inc/AST/CodeGenVisitor.h +++ b/inc/AST/CodeGenVisitor.h @@ -31,7 +31,7 @@ public: virtual void visit(VariableDefinition* e); virtual void visit(LoadExpression* e); - void createAnonymousFunction(); + void JIT(Expression* e); private: void putNamedValue(const std::string& name, llvm::Value* value); llvm::Value* getNamedValue(const std::string& name); @@ -39,7 +39,9 @@ private: llvm::IRBuilder<>* builder_; llvm::FunctionPassManager* fpm_; llvm::Module* module_; - std::map namedValues_; + + int scope_; + std::vector> namedValues_; llvm::Value* value_; }; diff --git a/src/AST/CodeGenVisitor.cpp b/src/AST/CodeGenVisitor.cpp index 6bf0261..c1b85e9 100644 --- a/src/AST/CodeGenVisitor.cpp +++ b/src/AST/CodeGenVisitor.cpp @@ -3,8 +3,11 @@ CodeGenVisitor::CodeGenVisitor(llvm::Module* module, llvm::FunctionPassManager *fpm) { builder_ = new llvm::IRBuilder<>(llvm::getGlobalContext()); - module_ = module; fpm_ = fpm; + module_ = module; + + scope_ = 0; + namedValues_.push_back(std::map()); // create external for random_if std::vector argt(1, typeToLLVMType(Type::INT)); @@ -271,9 +274,11 @@ void CodeGenVisitor::visit(ReturnStatement* e) { } void CodeGenVisitor::visit(Scope* e) { - // TODO increment scope + scope_++; + namedValues_.push_back(std::map()); e->getSl()->accept(this); - // TODO decrement scope + namedValues_.pop_back(); + scope_--; } void CodeGenVisitor::visit(StatementList* e) { @@ -299,17 +304,23 @@ void CodeGenVisitor::visit(LoadExpression *e) { value_ = getNamedValue(e->getId()); } -void CodeGenVisitor::createAnonymousFunction() { - if (value_) { - value_->dump(); - } - // TODO implement +void CodeGenVisitor::JIT(Expression* e) { + // TODO implement ... } void CodeGenVisitor::putNamedValue(const std::string& name, llvm::Value* value) { - namedValues_[name] = value; + namedValues_[scope_][name] = value; } llvm::Value* CodeGenVisitor::getNamedValue(const std::string& name) { - return namedValues_[name]; + llvm::Value* v = 0; + + for (int i = scope_; i >= 0; i--) { + if (namedValues_[i][name] != 0) { + v = namedValues_[i][name]; + break; + } + } + + return v; }