From e2438f143b722d944e778cf4ead13673d45fc816 Mon Sep 17 00:00:00 2001 From: Luna Date: Mon, 1 Jul 2019 15:25:07 -0300 Subject: [PATCH] work towards FnDecl ast node --- src/ast.zig | 2 +- src/parser.zig | 34 ++++++++++++++++++++++++++-------- 2 files changed, 27 insertions(+), 9 deletions(-) diff --git a/src/ast.zig b/src/ast.zig index 4de4f03..a2b1834 100644 --- a/src/ast.zig +++ b/src/ast.zig @@ -10,7 +10,7 @@ pub const NodeType = enum { }; pub const FnDecl = struct { - func_name: []const u8, + func_name: Token, }; pub const Node = union(NodeType) { diff --git a/src/parser.zig b/src/parser.zig index e43588e..6142051 100644 --- a/src/parser.zig +++ b/src/parser.zig @@ -90,26 +90,44 @@ pub const Parser = struct { return Result.CompileError; } - fn mkFnDecl(self: *Parser, name: []const u8) !*ast.Node { - var node = try self.allocator.create(Node.FnDecl); - node.* = Node.FnDecl{ .name = name }; + fn consumeSingle(self: *Parser, ttype: TokenType) !Token { + if (self.check(ttype)) return self.advance(); + + var buf_main: [1000]u8 = undefined; + var buf = try std.fmt.bufPrint( + buf_main[0..], + "expected {}, got {}", + ttype, + self.peek().ttype, + ); + try self.tokenError(self.peek(), buf); + + return Result.CompileError; + } + + fn mkFnDecl(self: *Parser, name: Token) !*ast.Node { + var node = try self.allocator.create(Node); + node.* = Node{ .FnDecl = ast.FnDecl{ .func_name = name } }; return node; } fn functionDecl(self: *Parser) !*ast.Node { // get the name var name = try self.consume(.Identifier, "expected function name"); + _ = try self.consumeSingle(.LeftParen); return try self.mkFnDecl(name); } - fn processToken(self: *Parser, token: Token) Result!ast.Node { - switch (token.ttype) { - //.Fn => try self.functionDecl(), + fn processToken(self: *Parser, token: Token) !*ast.Node { + var node = switch (token.ttype) { + .Fn => try self.functionDecl(), else => blk: { try self.doError("TODO handle {}\n", token.ttype); return Result.CompileError; }, - } + }; + + return node; } pub fn parse(self: *Parser) !*ast.Node { @@ -128,7 +146,7 @@ pub const Parser = struct { if (token.ttype == .EOF) break; var node = try self.processToken(token); - try root.Root.append(&node); + try root.Root.append(node); } else { continue; }