ast: add return type to FnDecl

- ast: make FnDecl and Const print better as s-expressions
This commit is contained in:
Luna 2019-08-25 12:24:34 -03:00
parent 4534549f41
commit f9f6362c91
2 changed files with 26 additions and 17 deletions

View File

@ -28,6 +28,7 @@ pub const ParamDecl = struct {
pub const FnDecl = struct {
func_name: Token,
params: ParamList,
return_type: Token,
body: StmtList,
};
@ -140,36 +141,38 @@ fn print(ident: usize, comptime fmt: []const u8, args: ...) void {
pub fn printNode(node: *Node, ident: usize) void {
switch (node.*) {
.FnDecl => |decl| {
print(ident, "FnDecl name='{}'\n", decl.func_name.lexeme);
print(ident, "(fn {} (", decl.func_name.lexeme);
for (decl.params.toSlice()) |param| {
print(
ident + 1,
"param: '{}' {}\n",
param.name.lexeme,
param.typ.lexeme,
);
std.debug.warn("({} {}) ", param.name.lexeme, param.typ.lexeme);
}
std.debug.warn(") (\n");
for (decl.body.toSlice()) |stmt| {
printIdent(ident + 1);
printStmt(stmt);
std.debug.warn("\n");
}
print(ident, ")\n");
},
.ConstDecl => |consts| {
print(ident, "ConstDecl ({} consts)\n", consts.len);
print(ident, "(const (\n");
for (consts.toSlice()) |const_decl| {
print(
ident + 1,
"{} = ",
"({} ",
const_decl.name.lexeme,
);
printExpr(const_decl.expr);
std.debug.warn("\n");
std.debug.warn(")\n");
}
print(ident, "))\n");
},
.Root => {

View File

@ -120,12 +120,19 @@ pub const Parser = struct {
return false;
}
fn mkFnDecl(self: *Parser, name: Token, params: ast.ParamList, block: ast.StmtList) !*ast.Node {
fn mkFnDecl(
self: *Parser,
name: Token,
params: ast.ParamList,
return_type: Token,
block: ast.StmtList,
) !*ast.Node {
var node = try self.allocator.create(Node);
node.* = Node{
.FnDecl = ast.FnDecl{
.func_name = name,
.params = params,
.return_type = return_type,
.body = block,
},
};
@ -348,6 +355,8 @@ pub const Parser = struct {
while (self.peek().ttype != .RightParen) {
const param_name = try self.consumeSingle(.Identifier);
// TODO dedicated function to consume a type
const param_type = try self.consumeSingle(.Identifier);
try param_list.append(ast.ParamDecl{
@ -358,13 +367,10 @@ pub const Parser = struct {
_ = try self.consumeSingle(.RightParen);
// TODO return type
// TODO dedicated function to consume a type
const return_type = try self.consumeSingle(.Identifier);
var block = try self.parseBlock();
std.debug.warn("!fn name: {}\n", name);
return try self.mkFnDecl(name, param_list, block.Block);
var block_node = try self.parseBlock();
return try self.mkFnDecl(name, param_list, return_type, block_node.Block);
}
fn parseConstDecl(self: *@This()) !?*Node {