aboutsummaryrefslogtreecommitdiff
path: root/src/parse.zig
diff options
context:
space:
mode:
Diffstat (limited to 'src/parse.zig')
-rw-r--r--src/parse.zig45
1 files changed, 33 insertions, 12 deletions
diff --git a/src/parse.zig b/src/parse.zig
index 1dda517..cadc489 100644
--- a/src/parse.zig
+++ b/src/parse.zig
@@ -12,6 +12,21 @@ pub const Stmt = struct {
pub const Type = union(enum) {
expr: *const Expr,
};
+
+ pub fn fmt(self: Stmt, file_source: []const u8) Format {
+ return .{ .data = .{ self, file_source } };
+ }
+
+ const Format = std.fmt.Formatter(struct {
+ fn format(data: struct { Stmt, []const u8 }, comptime f: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
+ const self, const file_source = data;
+ _ = f;
+ _ = options;
+ return switch (self.type) {
+ .expr => |expr| writer.print("{};", .{expr.fmt(file_source)}),
+ };
+ }
+ }.format);
};
pub const Expr = struct {
@@ -33,8 +48,8 @@ pub const Expr = struct {
plus,
minus,
- pub fn format(self: Op, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
- _ = fmt;
+ pub fn format(self: Op, comptime f: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
+ _ = f;
_ = options;
try writer.writeByte(switch (self) {
.plus => '+',
@@ -50,16 +65,23 @@ pub const Expr = struct {
};
};
- pub fn format(self: Expr, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
- _ = fmt;
- _ = options;
- switch (self.type) {
- .integer_literal => try writer.print("<int>", .{}),
- .bin_op => |bin_op| try writer.print("({} {} {})", .{ bin_op.lhs, bin_op.op, bin_op.rhs }),
- .call => |call| try writer.print("({} {})", .{ call.proc, call.arg }),
- .identifier => try writer.print("<identifier>", .{}),
- }
+ pub fn fmt(self: Expr, file_source: []const u8) Format {
+ return .{ .data = .{ self, file_source } };
}
+
+ const Format = std.fmt.Formatter(struct {
+ fn format(data: struct { Expr, []const u8 }, comptime f: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
+ const self, const file_source = data;
+ _ = f;
+ _ = options;
+ switch (self.type) {
+ .integer_literal => try writer.print("{}", .{self.loc.getInt(file_source)}),
+ .bin_op => |bin_op| try writer.print("({} {} {})", .{ bin_op.lhs.fmt(file_source), bin_op.op, bin_op.rhs.fmt(file_source) }),
+ .call => |call| try writer.print("({} {})", .{ call.proc.fmt(file_source), call.arg.fmt(file_source) }),
+ .identifier => try writer.print("{s}", .{self.loc.getIdent(file_source)}),
+ }
+ }
+ }.format);
};
pub fn statements(allocator: Allocator, lexer: *Lexer) ![]Stmt {
@@ -120,7 +142,6 @@ pub fn callExpr(allocator: Allocator, lexer: *Lexer) !*Expr {
pub fn primaryExpr(allocator: Allocator, lexer: *Lexer) !*Expr {
const token = lexer.next();
- // std.debug.print("term {}\n", .{token});
return allocate(Expr, allocator, switch (token.type) {
.left_paren => {
const res = expression(allocator, lexer);