Skip to content

Commit

Permalink
support func prototype ( can use cstdlib now!)
Browse files Browse the repository at this point in the history
  • Loading branch information
rapiz1 committed Nov 3, 2021
1 parent 05d4aa0 commit 0615993
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 5 deletions.
6 changes: 5 additions & 1 deletion parser.cc
Original file line number Diff line number Diff line change
Expand Up @@ -322,7 +322,11 @@ FunDecl* Parser::funDecl(Type retType, Token id) {

consume(RIGHT_PAREN, "Expect `)` as argument list ends");

BlockStmt* b = blockStmt();
BlockStmt* b = nullptr;
if (match(1, LEFT_BRACE))
b = blockStmt();
else
consume(SEMICOLON, "Expect `,` after function prototype");

return new FunDecl(id.lexeme, a, b, retType);
}
Expand Down
2 changes: 1 addition & 1 deletion parser.h
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ class Parser {
VarDecl* varDecl(Type type, Token id); // TYPE ('['SIZE']')? IDENTIFIER
// (EQUAL EXPRESSION)? ;
FunDecl* funDecl(Type type,
Token id); // TYPE IDENTIFIER '(' ARGS? ')' BLOCK
Token id); // TYPE IDENTIFIER '(' ARGS? ')' BLOCK?
Args args(); // TYPE ID (, TYPE ID)*
RealArgs real_args(); // EXPR (, EXPR)*

Expand Down
14 changes: 11 additions & 3 deletions visitor.cc
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,7 @@ void CodeGenVisitor::visit(VarDecl* st) {
void CodeGenVisitor::visit(FunDecl* st) {
if (scope.isWrapped()) abortMsg("nested function is forbidden");
llvm::Function* F = l.mod->getFunction(st->identifier);
if (F) abortMsg("redefine func");
if (F && !F->empty()) abortMsg("redefine func");

std::vector<llvm::Type*> args;
for (auto [type, token] : st->args) {
Expand All @@ -281,6 +281,15 @@ void CodeGenVisitor::visit(FunDecl* st) {

F = llvm::Function::Create(FT, llvm::Function::ExternalLinkage,
st->identifier, l.mod.get());
if (st->body == nullptr) { // a prototype
size_t i = 0;
for (auto& a : F->args()) {
FormalArg formal = st->args[i++];
std::string name = formal.token.lexeme;
a.setName(name);
}
return;
}

// Create a new basic block to start insertion into.
llvm::BasicBlock* BB = llvm::BasicBlock::Create(*l.ctx, st->identifier, F);
Expand All @@ -302,8 +311,7 @@ void CodeGenVisitor::visit(FunDecl* st) {
}

v.visit(st->body);
if (llvm::verifyFunction(*F, &llvm::errs()))
; // abortMsg("verify error");
if (llvm::verifyFunction(*F, &llvm::errs())) abortMsg("verify error");
// F->eraseFromParent();
}
void CodeGenVisitor::visit(BlockStmt* st) {
Expand Down

0 comments on commit 0615993

Please sign in to comment.