add basic parameter parsing

This commit is contained in:
Luna 2019-07-01 15:55:19 -03:00
parent 4f7478d7b2
commit 11f810a5f3
3 changed files with 56 additions and 5 deletions

View file

@ -1,3 +1,3 @@
fn main() { fn main(a int) {
println("hello world!"); // println("hello world!");
} }

View file

@ -3,14 +3,24 @@ const tokens = @import("tokens.zig");
const Token = tokens.Token; const Token = tokens.Token;
pub const NodeList = std.ArrayList(*Node); pub const NodeList = std.ArrayList(*Node);
pub const ParamList = std.ArrayList(*ParamDecl);
pub const NodeType = enum { pub const NodeType = enum {
Root, Root,
FnDecl, FnDecl,
}; };
pub const ParamDecl = struct {
param_name: Token,
// TODO types
param_type: Token,
};
pub const FnDecl = struct { pub const FnDecl = struct {
func_name: Token, func_name: Token,
params: ParamList,
body: NodeList,
}; };
pub const Node = union(NodeType) { pub const Node = union(NodeType) {

View file

@ -106,9 +106,17 @@ pub const Parser = struct {
return Result.CompileError; 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); 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; return node;
} }
@ -117,7 +125,40 @@ pub const Parser = struct {
var name = try self.consumeSingle(.Identifier); var name = try self.consumeSingle(.Identifier);
_ = try self.consumeSingle(.LeftParen); _ = 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 { fn processToken(self: *Parser, token: Token) !*ast.Node {