aboutsummaryrefslogtreecommitdiff
path: root/src/parse.zig
blob: b509fe7979b50dec79a8dbf6848af9ec47d9f952 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
const std = @import("std");
const Allocator = std.mem.Allocator;

const root = @import("root");
const Lexer = root.Lexer;
const Token = root.Lexer.Token;

fn Fmt(T: type) type {
    return std.fmt.Formatter(struct {
        fn format(
            data: struct { T, []const u8, usize },
            comptime _: []const u8,
            _: std.fmt.FormatOptions,
            writer: anytype,
        ) !void {
            const self, const file_source, const indent = data;
            return self.format(writer, file_source, indent);
        }
    }.format);
}

pub fn fmt(tree: anytype, source: []const u8, indent: usize) Fmt(@TypeOf(tree)) {
    return .{ .data = .{ tree, source, indent } };
}

pub const Block = struct {
    loc: Lexer.Location,
    stmts: []Stmt,

    fn format(self: Block, writer: anytype, source: []const u8, indent: usize) !void {
        try writer.writeAll("{\n");
        for (self.stmts) |stmt| {
            try writer.print("{}\n", .{fmt(stmt, source, indent + 4)});
        }
        try writer.writeByteNTimes(' ', indent);
        try writer.writeAll("}");
    }
};

pub const Stmt = struct {
    loc: Lexer.Location,
    type: Type,

    pub const Type = union(enum) {
        expr: *const Expr,
        declare_var: DeclareVar,
        block: Block,

        pub const DeclareVar = struct {
            ident: Lexer.Location,
            value: *const Expr,
        };
    };

    fn format(self: Stmt, writer: anytype, source: []const u8, indent: usize) !void {
        try writer.writeByteNTimes(' ', indent);
        return switch (self.type) {
            .expr => |expr| writer.print("{};", .{fmt(expr, source, indent)}),
            .block => |b| writer.print("{}", .{fmt(b, source, indent)}),
            .declare_var => |declare_var| writer.print("let {s} = {};", .{
                declare_var.ident.getIdent(source),
                fmt(declare_var.value, source, indent),
            }),
        };
    }
};

pub const Expr = struct {
    loc: Lexer.Location,
    type: Type,

    pub const Type = union(enum) {
        integer_literal,
        bin_op: BinOp,
        call: Call,
        identifier,

        pub const BinOp = struct {
            lhs: *const Expr,
            rhs: *const Expr,
            op: Op,

            const Op = enum {
                plus,
                minus,

                pub fn format(self: Op, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void {
                    try writer.writeByte(switch (self) {
                        .plus => '+',
                        .minus => '-',
                    });
                }
            };
        };

        pub const Call = struct {
            proc: *const Expr,
            arg: *const Expr,
        };
    };

    fn format(self: Expr, writer: anytype, source: []const u8, indent: usize) !void {
        switch (self.type) {
            .integer_literal => try writer.print("{}", .{self.loc.getInt(source)}),
            .bin_op => |bin_op| {
                try writer.print("{} {} {}", .{ fmt(bin_op.lhs, source, indent), bin_op.op, fmt(bin_op.rhs, source, indent) });
            },
            .call => |call| {
                try writer.print("{}({})", .{ fmt(call.proc, source, indent), fmt(call.arg, source, indent) });
            },
            .identifier => try writer.print("{s}", .{self.loc.getIdent(source)}),
        }
    }
};

const ParseError = error{ OutOfMemory, ExpectedRightParen, UnexpectedToken, ExpectedSemicolon };

pub fn block(allocator: Allocator, lexer: *Lexer) !Block {
    const left_curly = try mustEat(lexer, .left_curly);
    var stmts: std.ArrayList(Stmt) = .init(allocator);
    while (lexer.peek().type != .right_curly) {
        try stmts.append(try statement(allocator, lexer));
    }
    const right_curly = try mustEat(lexer, .right_curly);
    return .{
        .loc = left_curly.loc.combine(right_curly.loc),
        .stmts = try stmts.toOwnedSlice(),
    };
}

pub fn statement(allocator: Allocator, lexer: *Lexer) ParseError!Stmt {
    switch (lexer.peek().type) {
        .let => {
            const let = lexer.next();
            const ident = try mustEat(lexer, .identifier);
            _ = try mustEat(lexer, .equal);
            const value = try expression(allocator, lexer);
            const semicolon = try mustEat(lexer, .semicolon);
            return .{
                .loc = let.loc.combine(semicolon.loc),
                .type = .{ .declare_var = .{ .ident = ident.loc, .value = value } },
            };
        },
        .left_curly => {
            const b = try block(allocator, lexer);
            return .{
                .loc = b.loc,
                .type = .{ .block = b },
            };
        },
        else => {
            var expr = try expression(allocator, lexer);
            const semicolon = lexer.next();
            if (semicolon.type != .semicolon) return error.ExpectedSemicolon;
            return .{
                .loc = expr.loc.combine(semicolon.loc),
                .type = .{ .expr = expr },
            };
        },
    }
}

pub fn expression(allocator: Allocator, lexer: *Lexer) ParseError!*Expr {
    return parseTerms(allocator, lexer);
}

pub fn parseTerms(allocator: Allocator, lexer: *Lexer) !*Expr {
    var lhs = try parseInvocations(allocator, lexer);
    while (true) {
        const op: Expr.Type.BinOp.Op = switch (lexer.peek().type) {
            .plus => .plus,
            .minus => .minus,
            else => break,
        };
        _ = lexer.next();

        const rhs = try parseInvocations(allocator, lexer);
        lhs = try allocate(Expr, allocator, .{
            .loc = lhs.loc.combine(rhs.loc),
            .type = .{ .bin_op = .{ .lhs = lhs, .op = op, .rhs = rhs } },
        });
    }
    return lhs;
}

pub fn parseInvocations(allocator: Allocator, lexer: *Lexer) !*Expr {
    var proc = try parsePrimaryExpr(allocator, lexer);
    while (true) {
        if (lexer.peek().type != .left_paren) break;
        _ = lexer.next();
        const arg = try expression(allocator, lexer);
        _ = try mustEat(lexer, .right_paren);
        proc = try allocate(Expr, allocator, .{
            .loc = proc.loc.combine(arg.loc),
            .type = .{ .call = .{ .proc = proc, .arg = arg } },
        });
    }
    return proc;
}

pub fn parsePrimaryExpr(allocator: Allocator, lexer: *Lexer) !*Expr {
    const token = lexer.next();
    return allocate(Expr, allocator, switch (token.type) {
        .left_paren => {
            const res = expression(allocator, lexer);
            const right_paren = lexer.next();
            if (right_paren.type != .right_paren)
                return error.ExpectedRightParen;
            return res;
        },
        .integer_literal => .{ .loc = token.loc, .type = .integer_literal },
        .identifier => .{ .loc = token.loc, .type = .identifier },
        else => |t| {
            std.debug.print("Expected '(', integer literal, or identifier. Got {}\n", .{t});
            return error.UnexpectedToken;
        },
    });
}

fn mustEat(lexer: *Lexer, ty: Lexer.Token.Type) !Lexer.Token {
    const token = lexer.next();
    if (token.type != ty) {
        std.debug.print("Expected {}. Got {}\n", .{ ty, token.type });
        return error.UnexpectedToken;
    }
    return token;
}

fn allocate(T: type, allocator: Allocator, t: T) !*T {
    const res = try allocator.create(T);
    res.* = t;
    return res;
}