add return statements

This commit is contained in:
Luna 2019-08-25 23:16:13 -03:00
parent 8f44cbea23
commit c0c93183cb
3 changed files with 36 additions and 2 deletions

View file

@ -32,4 +32,6 @@ fn main(a int) int {
}
cock_and_ball_torture('cbt', 1, 2, 3)
return 23
}

View file

@ -125,6 +125,13 @@ pub const Stmt = union(enum) {
If: IfStmt,
Loop: LoopStmt,
Return: ReturnStmt,
pub const ReturnStmt = struct {
keyword: Token,
value: *Expr,
};
pub fn mkPrintln(allocator: *std.mem.Allocator, expr: *Expr) !*Stmt {
var stmt = try allocator.create(Stmt);
stmt.* = Stmt{ .Println = expr };
@ -164,6 +171,18 @@ pub const Stmt = union(enum) {
return stmt;
}
pub fn mkReturn(allocator: *std.mem.Allocator, tok: Token, value: *Expr) !*Stmt {
var stmt = try allocator.create(Stmt);
stmt.* = Stmt{
.Return = ReturnStmt{
.keyword = tok,
.value = value,
},
};
return stmt;
}
};
pub const Node = union(NodeType) {
@ -361,6 +380,12 @@ pub fn printStmt(ident: usize, stmt: *Stmt) void {
std.debug.warn(")\n");
},
.Return => |ret| {
std.debug.warn("(return ");
printExpr(ret.value);
std.debug.warn(")\n");
},
else => std.debug.warn("UnknownStmt-{}", @tagName(stmt.*)),
}
}

View file

@ -464,6 +464,7 @@ pub const Parser = struct {
.If => try self.parseIfStmt(),
.Loop => try self.parseLoop(),
.Println => try self.parsePrintln(),
.Return => try self.parseReturn(),
// TODO make newlines tokens and consume newline?
else => try self.parseStmtExpr(),
@ -525,14 +526,20 @@ pub const Parser = struct {
return try Stmt.mkLoop(self.allocator, expr, body);
}
fn parseReturn(self: *@This()) !*Stmt {
const tok = try self.consumeSingle(.Return);
const expr = (try self.parseExpr()).Expr;
return try Stmt.mkReturn(self.allocator, tok, expr);
}
fn parsePrintln(self: *@This()) !*Stmt {
_ = try self.consumeSingle(.Println);
_ = try self.consumeSingle(.LeftParen);
var expr = try self.parseExpr();
var expr = (try self.parseExpr()).Expr;
_ = try self.consumeSingle(.RightParen);
return try Stmt.mkPrintln(self.allocator, expr.Expr);
return try Stmt.mkPrintln(self.allocator, expr);
}
fn parseStmtExpr(self: *@This()) !*Stmt {