aboutsummaryrefslogtreecommitdiff
path: root/src/compile.zig
blob: ac7768e6eda5a23ae2b05bee3c1be15af4cf3cc4 (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
const std = @import("std");
const Allocator = std.mem.Allocator;
const root = @import("root");
const Token = root.Lexer.Token;
const parse = root.parse;
const Location = root.Lexer.Location;

pub const VReg = enum(u32) { _ };

pub const Instr = struct {
    loc: Location,
    type: Type,

    pub const Type = union(enum) {
        constant: Constant,
        bin_op: BinOp,
        proc_call: ProcCall,
    };

    pub const Constant = struct {
        dest: VReg,
        value: u64,

        pub fn sources(_: Constant) Sources {
            return Sources.init(0) catch unreachable;
        }
    };

    pub const BinOp = struct {
        dest: VReg,
        lhs: VReg,
        rhs: VReg,
        op: Op,

        const Op = enum {
            add,
            sub,
        };

        pub fn sources(self: BinOp) Sources {
            return Sources.fromSlice(&.{ self.lhs, self.rhs }) catch unreachable;
        }
    };

    pub const ProcCall = struct {
        dest: VReg,
        arg: VReg,
        proc: Proc,

        const Proc = enum {
            print,
            read_int,
        };

        pub fn sources(self: ProcCall) Sources {
            return Sources.fromSlice(&.{self.arg}) catch unreachable;
        }
    };

    pub fn sources(self: Instr) Sources {
        return switch (self.type) {
            inline else => |instr| instr.sources(),
        };
    }

    pub fn dest(self: *const Instr) ?VReg {
        return switch (self.type) {
            inline .constant, .bin_op, .proc_call => |s| s.dest,
        };
    }

    pub const Sources = std.BoundedArray(VReg, 2);
};

pub const Block = struct {
    // arguments: []Reg,
    instrs: []Instr,
    vreg_last_use: std.AutoHashMap(VReg, usize),

    fn init(allocator: Allocator, instrs: []Instr) !Block {
        var vreg_last_use: std.AutoHashMap(VReg, usize) = .init(allocator);
        for (0.., instrs) |i, instr| {
            for (instr.sources().slice()) |src|
                try vreg_last_use.put(src, i);
            if (instr.dest()) |dest|
                try vreg_last_use.put(dest, i);
        }
        return .{
            .instrs = instrs,
            .vreg_last_use = vreg_last_use,
        };
    }
};

pub fn compile(allocator: Allocator, source: []const u8, stmts: []parse.Stmt) !Block {
    const instrs: std.ArrayListUnmanaged(Instr) = try .initCapacity(allocator, 0);
    var ctx: CompileContext = .{
        .allocator = allocator,
        .source = source,
        .register_counter = 0,
        .scope = .empty,
        .instrs = instrs,
    };
    for (stmts) |stmt| {
        try ctx.compileStmt(stmt);
    }
    return .init(allocator, ctx.instrs.items);
}

const CompileContext = struct {
    allocator: Allocator,
    source: []const u8,
    register_counter: u32,
    scope: std.StringHashMapUnmanaged(VReg),
    instrs: std.ArrayListUnmanaged(Instr),

    const Self = @This();

    fn addInstr(self: *Self, instr: Instr) !void {
        try self.instrs.append(self.allocator, instr);
    }

    fn compileStmt(self: *Self, stmt: parse.Stmt) !void {
        switch (stmt.type) {
            .expr => |expr| _ = try self.compileExpr(expr),
            .declare_var => |declare_var| {
                const val = try self.compileExpr(declare_var.value);
                const name = declare_var.ident.getIdent(self.source);
                try self.scope.put(self.allocator, name, val);
            },
        }
    }

    fn compileExpr(self: *Self, expr: *const parse.Expr) !VReg {
        // This is not used by all expression types, but creating an unused virtual register is not a problem.
        const dest = self.register();
        switch (expr.type) {
            .integer_literal => try addInstr(self, .{
                .loc = expr.loc,
                .type = .{ .constant = .{ .dest = dest, .value = expr.loc.getInt(self.source) } },
            }),
            .bin_op => |binop| {
                const lhs = try self.compileExpr(binop.lhs);
                const rhs = try self.compileExpr(binop.rhs);
                try addInstr(self, .{
                    .loc = expr.loc,
                    .type = .{
                        .bin_op = .{
                            .dest = dest,
                            .lhs = lhs,
                            .rhs = rhs,
                            .op = switch (binop.op) {
                                .plus => .add,
                                .minus => .sub,
                            },
                        },
                    },
                });
            },
            .call => |call| {
                if (call.proc.type != .identifier) return error.CanOnlyCallIdentifiers;
                const proc = std.meta.stringToEnum(Instr.ProcCall.Proc, call.proc.loc.getIdent(self.source)) orelse return error.UnknownProcedure;

                const arg = try self.compileExpr(call.arg);
                try self.addInstr(.{
                    .loc = expr.loc,
                    .type = .{ .proc_call = .{ .dest = dest, .arg = arg, .proc = proc } },
                });
            },
            .identifier => {
                return self.scope.get(expr.loc.getIdent(self.source)) orelse return error.UnknownVariable;
            },
        }
        return dest;
    }

    fn register(self: *Self) VReg {
        const reg: VReg = @enumFromInt(self.register_counter);
        self.register_counter += 1;
        return reg;
    }
};