vig/src/ast.zig

104 lines
2.3 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);
pub const ConstList = std.ArrayList(SingleConst);
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,
ConstDecl,
2019-08-23 14:57:49 +00:00
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 SingleConst = struct {
name: Token,
// TODO expr
value: Token,
};
pub const Node = union(NodeType) {
Root: NodeList,
FnDecl: FnDecl,
ConstDecl: ConstList,
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
},
.ConstDecl => |consts| {
print(ident, "ConstDecl ({} consts)\n", consts.len);
for (consts.toSlice()) |const_decl| {
print(
ident + 1,
"'{}' = '{}'\n",
const_decl.name.lexeme,
const_decl.value.lexeme,
);
}
},
2019-08-23 18:42:50 +00:00
.Root => {
for (node.Root.toSlice()) |child| {
printNode(child, ident + 1);
}
},
2019-08-23 18:42:50 +00:00
else => {
print(ident, "unknown node: {}\n", node);
},
}
}