Skip to content

Commit

Permalink
feat: Added defer keyword
Browse files Browse the repository at this point in the history
  • Loading branch information
alinalihassan committed May 18, 2022
1 parent b80c074 commit c1e8e92
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 6 deletions.
16 changes: 12 additions & 4 deletions src/liblesma/Backend/Codegen.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -441,7 +441,7 @@ void Codegen::visit(FuncDecl *node) {
FunctionType *FT = FunctionType::get(visit(node->getReturnType()), paramTypes, false);
Function *F = Function::Create(FT, linkage, name, *TheModule);

// deferStack.push({});
deferStack.push({});

BasicBlock *BB = BasicBlock::Create(*TheContext, "entry", F);
Builder->SetInsertPoint(BB);
Expand All @@ -459,8 +459,12 @@ void Codegen::visit(FuncDecl *node) {
}
visit(node->getBody());

// auto instrs = deferStack.top();
// deferStack.pop();
auto instrs = deferStack.top();
deferStack.pop();

if (!isReturn)
for (auto inst: instrs)
visit(inst);

if (visit(node->getReturnType()) == Builder->getVoidTy() && !isReturn)
Builder->CreateRetVoid();
Expand Down Expand Up @@ -606,6 +610,10 @@ void Codegen::visit(Return *node) {
if (Builder->GetInsertBlock()->getParent() == TopLevelFunc)
throw CodegenError(node->getSpan(), "Return statements are not allowed at top-level");

// Execute all defered statements
for (auto inst: deferStack.top())
visit(inst);

isReturn = true;
if (node->getValue() == nullptr)
Builder->CreateRetVoid();
Expand All @@ -614,7 +622,7 @@ void Codegen::visit(Return *node) {
}

void Codegen::visit(Defer *node) {
throw CodegenError(node->getSpan(), "Defer functionality unimplemented!");
deferStack.top().push_back(node->getStatement());
}

void Codegen::visit(ExpressionStatement *node) {
Expand Down
2 changes: 1 addition & 1 deletion src/liblesma/Backend/Codegen.h
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ namespace lesma {

std::stack<llvm::BasicBlock *> breakBlocks;
std::stack<llvm::BasicBlock *> continueBlocks;
std::stack<std::vector<llvm::Value *>> deferStack;
std::stack<std::vector<Statement *>> deferStack;

std::vector<std::string> ObjectFiles;
llvm::Function *TopLevelFunc;
Expand Down
2 changes: 1 addition & 1 deletion src/liblesma/Frontend/Lexer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -370,7 +370,7 @@ Token *Lexer::AddIdentifierToken() {

auto tok = AddToken(Token::GetIdentifierType(std::string(begin_loc.getPointer(), loc.getPointer()), GetLastToken()));

// If it's an 'else if' multiword keyword, remove the last token (which is an 'else' in this case)
// If it's a multi-word keyword, remove the last token
if (tok->type == TokenType::ELSE_IF || tok->type == TokenType::IS_NOT)
tokens.pop_back();

Expand Down

0 comments on commit c1e8e92

Please sign in to comment.