vig/src/ast.zig

80 lines
1.7 KiB
Zig
Raw Normal View History

const std = @import("std");
2019-06-05 23:29:03 +00:00
const tokens = @import("tokens.zig");
const Token = tokens.Token;
pub const NodeList = std.ArrayList(*Node);
2019-08-23 18:52:04 +00:00
pub const ParamList = std.ArrayList(ParamDecl);
2019-08-23 14:57:49 +00:00
// TODO convert FnCall to something like PrefixOp / InfixOp / SuffixOp
pub const NodeType = enum {
Root,
FnDecl,
2019-08-23 14:57:49 +00:00
FnCall,
String,
};
2019-07-01 18:55:19 +00:00
pub const ParamDecl = struct {
2019-08-23 18:52:04 +00:00
name: Token,
2019-07-01 18:55:19 +00:00
// TODO types
2019-08-23 18:52:04 +00:00
typ: Token,
2019-07-01 18:55:19 +00:00
};
pub const FnDecl = struct {
2019-07-01 18:25:07 +00:00
func_name: Token,
2019-07-01 18:55:19 +00:00
params: ParamList,
body: NodeList,
};
2019-08-23 14:57:49 +00:00
pub const FnCall = struct {
func_name: Token,
arguments: NodeList,
};
pub const Node = union(NodeType) {
Root: NodeList,
FnDecl: FnDecl,
2019-08-23 14:57:49 +00:00
FnCall: FnCall,
String: Token,
2019-06-05 23:29:03 +00:00
};
pub fn mkRoot(allocator: *std.mem.Allocator) !*Node {
var node = try allocator.create(Node);
node.* = Node{ .Root = NodeList.init(allocator) };
return node;
2019-06-05 23:29:03 +00:00
}
2019-08-23 18:42:50 +00:00
fn print(ident: usize, comptime fmt: []const u8, args: ...) void {
var i: usize = 0;
while (i < ident) : (i += 1) {
std.debug.warn("\t");
}
std.debug.warn(fmt, args);
}
pub fn printNode(node: *Node, ident: usize) void {
switch (node.*) {
2019-08-23 18:52:04 +00:00
.FnDecl => |decl| {
print(ident, "FnDecl name='{}'\n", decl.func_name.lexeme);
for (decl.params.toSlice()) |param| {
print(
ident + 1,
"param: '{}' {}\n",
param.name.lexeme,
param.typ.lexeme,
);
}
2019-08-23 18:42:50 +00:00
},
.Root => {
for (node.Root.toSlice()) |child| {
printNode(child, ident + 1);
}
},
else => {
print(ident, "unknown node: {}\n", node);
},
}
}