From 11f810a5f31cc94a9a146e8b228aae74a087af85 Mon Sep 17 00:00:00 2001 From: Luna Date: Mon, 1 Jul 2019 15:55:19 -0300 Subject: [PATCH] add basic parameter parsing --- examples/hello.v | 4 ++-- src/ast.zig | 10 ++++++++++ src/parser.zig | 47 ++++++++++++++++++++++++++++++++++++++++++++--- 3 files changed, 56 insertions(+), 5 deletions(-) diff --git a/examples/hello.v b/examples/hello.v index 46cc8fd..93536f3 100644 --- a/examples/hello.v +++ b/examples/hello.v @@ -1,3 +1,3 @@ -fn main() { - println("hello world!"); +fn main(a int) { + // println("hello world!"); } diff --git a/src/ast.zig b/src/ast.zig index a2b1834..365ef26 100644 --- a/src/ast.zig +++ b/src/ast.zig @@ -3,14 +3,24 @@ const tokens = @import("tokens.zig"); const Token = tokens.Token; pub const NodeList = std.ArrayList(*Node); +pub const ParamList = std.ArrayList(*ParamDecl); pub const NodeType = enum { Root, FnDecl, }; +pub const ParamDecl = struct { + param_name: Token, + + // TODO types + param_type: Token, +}; + pub const FnDecl = struct { func_name: Token, + params: ParamList, + body: NodeList, }; pub const Node = union(NodeType) { diff --git a/src/parser.zig b/src/parser.zig index 76b8c59..cd15872 100644 --- a/src/parser.zig +++ b/src/parser.zig @@ -106,9 +106,17 @@ pub const Parser = struct { return Result.CompileError; } - fn mkFnDecl(self: *Parser, name: Token) !*ast.Node { + fn mkFnDecl(self: *Parser, name: Token, params: ast.ParamList) !*ast.Node { var node = try self.allocator.create(Node); - node.* = Node{ .FnDecl = ast.FnDecl{ .func_name = name } }; + node.* = Node{ + .FnDecl = ast.FnDecl{ + .func_name = name, + .params = params, + + // TODO replace by arg when statements work + .body = ast.NodeList.init(self.allocator), + }, + }; return node; } @@ -117,7 +125,40 @@ pub const Parser = struct { var name = try self.consumeSingle(.Identifier); _ = try self.consumeSingle(.LeftParen); - return try self.mkFnDecl(name); + var param_list = ast.ParamList.init(self.allocator); + + while (true) { + var tok = self.peek(); + + if (tok.ttype == .RightParen) break; + if (tok.ttype != .Identifier) { + try self.doError("expected identifier, got {}", tok.ttype); + } + + var typetok = try self.nextToken(); + if (typetok.ttype != .Identifier) { + try self.doError("expected identifier for type, got {}", typetok.ttype); + } + + var param = try self.allocator.create(ast.ParamDecl); + param.* = ast.ParamDecl{ .param_name = tok, .param_type = typetok }; + + std.debug.warn("param! {}\n", param); + try param_list.append(param); + } + + // function body + _ = try self.consumeSingle(.LeftBrace); + while (true) { + var tok = self.peek(); + if (tok.ttype == .RightBrace) break; + // TODO statements? + //var node = self.processToken(tok); + } + + _ = try self.consumeSingle(.RightBrace); + + return try self.mkFnDecl(name, param_list); } fn processToken(self: *Parser, token: Token) !*ast.Node {