parser: simplify parseBlock

This commit is contained in:
Luna 2019-08-26 14:59:14 -03:00
parent 1c8eda7305
commit c3f0b4b4d5

View file

@ -462,31 +462,27 @@ pub const Parser = struct {
.Struct => try self.parseStructDecl(), .Struct => try self.parseStructDecl(),
else => |ttype| blk: { else => |ttype| blk: {
self.doError("(basic) expected fn/const, got {}\n", ttype); self.doError("expected Fn, Const, Struct, got {}\n", ttype);
return Result.CompileError; return Result.CompileError;
}, },
}; };
} }
fn parseBlock(self: *@This()) !*Node { fn parseBlockInternal(self: *@This(), comptime T: type) !T {
var stmts = ast.StmtList.init(self.allocator); var stmts = T.init(self.allocator);
errdefer stmts.deinit(); errdefer stmts.deinit();
_ = try self.consumeSingle(.LeftBrace); _ = try self.consumeSingle(.LeftBrace);
while (self.peek().ttype != .RightBrace) { while (self.peek().ttype != .RightBrace) {
var stmt = try self.parseDecl(); var stmt = try self.parseStmt();
printer.printNode(try self.mkStmt(stmt), 0); printer.printNode(try self.mkStmt(stmt), 0);
try stmts.append(stmt); try stmts.append(stmt);
} }
_ = try self.consumeSingle(.RightBrace); _ = try self.consumeSingle(.RightBrace);
return try self.mkBlock(stmts); return stmts;
}
fn parseDecl(self: *@This()) !*Stmt {
return try self.parseStmt();
} }
fn parseStmt(self: *@This()) anyerror!*Stmt { fn parseStmt(self: *@This()) anyerror!*Stmt {
@ -495,27 +491,19 @@ pub const Parser = struct {
.Loop => try self.parseLoop(), .Loop => try self.parseLoop(),
.Println => try self.parsePrintln(), .Println => try self.parsePrintln(),
.Return => try self.parseReturn(), .Return => try self.parseReturn(),
// TODO make newlines tokens and consume newline?
else => try self.parseStmtExpr(), else => try self.parseStmtExpr(),
}; };
} }
/// Copy of parseBlock for blocks in statements /// Parse a list of statements.
fn parseBlock(self: *@This()) !*Node {
var stmts = try self.parseBlockInternal(ast.StmtList);
return try self.mkBlock(stmts);
}
/// parse blocks inside statements
fn parseStmtBlock(self: *@This()) !ast.Block { fn parseStmtBlock(self: *@This()) !ast.Block {
var block = ast.Block.init(self.allocator); var block = try self.parseBlockInternal(ast.Block);
errdefer block.deinit();
_ = try self.consumeSingle(.LeftBrace);
while (self.peek().ttype != .RightBrace) {
var stmt = try self.parseDecl();
printer.printNode(try self.mkStmt(stmt), 0);
try block.append(stmt);
}
_ = try self.consumeSingle(.RightBrace);
return block; return block;
} }