Skip to content

Commit

Permalink
fix: ✨ allow empty return in void functions
Browse files Browse the repository at this point in the history
  • Loading branch information
alinalihassan committed Mar 3, 2022
1 parent b078f03 commit b3bde14
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 3 deletions.
2 changes: 1 addition & 1 deletion TODO.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
## Bug fixes
- [x] Parser expects exactly one newline at the end of the file
- [x] Disallow return in top level
- [ ] Allow return void
- [x] Allow return void

## Refactoring
- [ ] Replace SourceLocation by Span
Expand Down
13 changes: 11 additions & 2 deletions src/Backend/Codegen.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -339,19 +339,24 @@ void Codegen::visit(FuncDecl *node) {
// auto instrs = deferStack.top();
// deferStack.pop();

if (visit(node->getReturnType()) == Builder->getVoidTy())
if (visit(node->getReturnType()) == Builder->getVoidTy() && !isReturn)
Builder->CreateRetVoid();

isReturn = false;

// Verify function
std::string output;
llvm::raw_string_ostream oss(output);
if (llvm::verifyFunction(*F, &oss)) {
F->print(outs());
throw CodegenError("Invalid Function {}\n{}", node->getName(), output);
}

// Insert Function to Symbol Table
Scope = Scope->getParent();
Scope->insertSymbol(node->getName(), F, F->getFunctionType());

// Reset Insert Point to Top Level
Builder->SetInsertPoint(&TopLevelFunc->back());
}

Expand Down Expand Up @@ -422,7 +427,11 @@ void Codegen::visit(Return *node) {
if (Builder->GetInsertBlock()->getParent() == TopLevelFunc)
throw CodegenError("Return statements are not allowed at top-level\n");

Builder->CreateRet(visit(node->getValue()));
isReturn = true;
if (node->getValue() == nullptr)
Builder->CreateRetVoid();
else
Builder->CreateRet(visit(node->getValue()));
}

void Codegen::visit(Defer * /*node*/) {
Expand Down
1 change: 1 addition & 0 deletions src/Backend/Codegen.h
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ namespace lesma {
std::stack<std::vector<llvm::Value *>> deferStack;
llvm::Function *TopLevelFunc;
bool isBreak = false;
bool isReturn = false;

public:
std::vector<ThreadSafeModule> Modules;
Expand Down
4 changes: 4 additions & 0 deletions src/Frontend/Parser.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,10 @@ Statement *Parser::ParseContinue() {
Statement *Parser::ParseReturn() {
auto loc = Peek()->loc;
Consume(TokenType::RETURN);
if (Check(TokenType::NEWLINE) || Peek()->type == TokenType::EOF_TOKEN) {
ConsumeNewline();
return reinterpret_cast<Statement *>(new Return(loc, nullptr));
}
auto val = ParseExpression();
ConsumeNewline();
return reinterpret_cast<Statement *>(new Return(loc, val));
Expand Down

0 comments on commit b3bde14

Please sign in to comment.