summaryrefslogtreecommitdiff
path: root/src/symtable.zig
blob: f426ef8906dda876bce8405b2be03e1b495d91fe (plain)
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
const std = @import("std");
const pars = @import("parser.zig");

const Scope = struct {
    par: ?*Scope,
    symbs: std.StringHashMap(Symbol),
};

pub const Symbol = union(enum) {
    Type: SymbType,
    Value: SymbValue,
};

pub const SymbType = union(enum) {
    Void,
    Integer,
    Character,
    String,
    Function: struct {
        input: []const SymbType,
        output: *SymbType,
    },
    pub fn toSymb(self: SymbType) Symbol {
        return Symbol{ .Type = self };
    }
    pub fn toString(self: SymbType, allocator: std.mem.Allocator) error{OutOfMemory}![]const u8 {
        return switch (self) {
            .Integer => "i32",
            .Character => "u8",
            .String => "[u8]",
            .Function => |fun| blk: {
                const output = try fun.output.toString(allocator);
                var argstring: []const u8 = "";
                if (fun.input.len != 0) {
                    argstring = try fun.input[0].toString(allocator);
                    for (1..fun.input.len) |i| {
                        const inputTyp = [_][]const u8{
                            argstring,
                            try fun.input[i].toString(allocator),
                        };
                        argstring = try std.mem.join(allocator, ", ", &inputTyp);
                    }
                }
                break :blk try std.fmt.allocPrint(allocator, "fn({s})->{s}", .{ argstring, output });
            },
            else => "void",
        };
    }
    pub fn toTypeIdent(self: SymbType, allocator: std.mem.Allocator) error{OutOfMemory}!pars.TypeIdent {
        return pars.TypeIdent{
            .ident = try self.toString(allocator),
            .list = switch (self) {
                .String => true,
                else => false,
            },
        };
    }
};

pub const SymbValue = struct {
    typ: SymbType,
    id: u32,
    mut: bool,
    pub fn toSymb(self: SymbValue) Symbol {
        return Symbol{ .Value = self };
    }
};

pub const SymbolTable = struct {
    par: ?*SymbolTable,
    scope: ?*Scope = null,
    allocator: std.mem.Allocator,

    pub fn init(allocator: std.mem.Allocator) error{OutOfMemory}!*SymbolTable {
        const scope = try allocator.create(Scope);
        scope.par = null;
        scope.symbs = std.StringHashMap(Symbol).init(allocator);
        const table = try allocator.create(SymbolTable);
        table.* = SymbolTable{
            .par = null,
            .scope = scope,
            .allocator = allocator,
        };
        return table;
    }

    pub fn deinit(self: *SymbolTable) void {
        if (self.scope) |scope| {
            var iter = scope.symbs.iterator();
            while (iter.next()) |entry| {
                switch (entry.value_ptr.*) {
                    .Type => |t| switch (t) {
                        .Function => |f| {
                            self.allocator.destroy(f.output);
                            self.allocator.free(f.input);
                        },
                        else => {},
                    },
                    else => {},
                }
            }
            scope.symbs.deinit();
            self.allocator.destroy(scope);
        }
        self.allocator.destroy(self);
    }

    pub fn makeChild(self: *SymbolTable) error{OutOfMemory}!*SymbolTable {
        const scope = try self.allocator.create(Scope);
        scope.par = self.scope;
        scope.symbs = try self.scope.?.symbs.clone();
        const stable: *SymbolTable = try self.allocator.create(SymbolTable);
        stable.* = .{
            .par = self,
            .scope = scope,
            .allocator = self.allocator,
        };
        return stable;
    }

    pub fn parent(self: SymbolTable) ?*SymbolTable {
        if (self.par) |par|
            return par;
        return null;
    }

    pub fn contains(self: SymbolTable, ident: []const u8) bool {
        if (self.scope) |scope| return scope.symbs.contains(ident);
        return false;
    }

    pub fn get(self: SymbolTable, ident: []const u8) ?Symbol {
        if (self.scope) |scope| return scope.symbs.get(ident) orelse if (self.parent()) |par| par.get(ident) else null;
        return null;
    }

    pub fn getValue(self: SymbolTable, ident: []const u8) ?SymbValue {
        if (self.get(ident)) |symbol|
            return switch (symbol) {
                .Value => |value| value,
                else => null,
            };

        return null;
    }

    pub fn getMut(self: *SymbolTable, ident: []const u8) ?Symbol {
        if (self.get(ident)) |symbol|
            return switch (symbol) {
                .Value => null,
                else => symbol,
            };
        return null;
    }

    pub fn getType(self: *SymbolTable, typ: pars.TypeIdent) ?SymbType {
        if (self.get(typ.ident)) |symb| return symb.Type;
        return null;
    }

    pub fn insert(self: *SymbolTable, ident: []const u8, symbol: Symbol) !bool {
        // std.debug.print("Inserted {s} as {any}\n", .{ ident, symbol });
        if (self.scope) |scope| {
            if (scope.symbs.getEntry(ident)) |_| return false;
            try scope.symbs.put(ident, symbol);
            return true;
        }
        return false;
    }
};

pub const Populator = struct {
    id: u32,
    allocator: std.mem.Allocator,

    fn reserveId(self: *Populator) u32 {
        defer self.id += 1;
        return self.id;
    }

    pub fn init(allocator: std.mem.Allocator) Populator {
        return .{
            .id = 1,
            .allocator = allocator,
        };
    }

    pub fn populateSymtable(self: *Populator, node: *const pars.Node) !void {
        switch (node.*) {
            .Stmt => |stmt| {
                const table: *SymbolTable = stmt.symtable;
                switch (stmt.kind) {
                    .defVar => |*variable| {
                        const symbol: Symbol = try self.buildValueSymb(
                            table,
                            try variable.expr.inferType(self.allocator, table),
                            true,
                        );
                        if (!try table.insert(variable.ident.ident, symbol)) return error.FailedToInsert;
                    },
                    .defValue => |value| {
                        const symbol: Symbol = try self.buildValueSymb(
                            table,
                            try value.expr.inferType(self.allocator, table),
                            false,
                        );
                        // std.debug.print("Value: {s}\nSymbol: {any}\n", .{ value.ident.ident, symbol });
                        if (!try table.insert(value.ident.ident, symbol)) return error.FailedToInsert;
                    },
                    .block => {
                        const children = try stmt.children(self.allocator);
                        defer self.allocator.free(children);
                        for (children) |child| try self.populateSymtable(&child);
                    },
                    .function => |fun| {
                        const bodyTable = if (fun.block == null) stmt.symtable else fun.block.?.symtable;
                        const symbol: Symbol = try self.buildFunctionSymb(
                            bodyTable,
                            fun.args,
                            fun.retType,
                        );

                        if (!try table.insert(fun.ident.ident, symbol)) return error.FailedToInsert;
                        if (fun.block == null) return;
                        const block = fun.block.?.asNode();
                        try self.populateSymtable(&block);
                    },
                    .assignVar => |assign| _ = {
                        const expectedType = try if (table.getValue(assign.ident.ident)) |symbol| try symbol.typ.toTypeIdent(self.allocator) else error.UnknownIdentifier;
                        const actualType = try assign.expr.inferType(self.allocator, table);
                        if (!std.mem.eql(u8, actualType.ident, expectedType.ident)) return error.IncorrectType;
                    },
                    .exit => |exit| _ = try exit.inferType(self.allocator, table),
                    .expr => {},
                    .ifstmt => for (try stmt.children(self.allocator)) |c| try self.populateSymtable(&c),
                    .whileStmt => for (try stmt.children(self.allocator)) |c| try self.populateSymtable(&c),

                    // else => |unim| return errorblk: {
                    //     std.debug.print("Error: Unimplemented: {any}\n", .{unim});
                    //     break :errorblk error.Unimplemented;
                    // },
                }
            },
            else => {
                for (try node.children(self.allocator)) |child|
                    try self.populateSymtable(&child);
            },
        }
    }

    fn buildFunctionSymb(
        self: *Populator,
        table: *SymbolTable,
        args: []const pars.FunctionArg,
        retType: ?pars.TypeIdent,
    ) !Symbol {
        var inputArr = std.ArrayList(SymbType).init(self.allocator);
        for (args) |arg| {
            // std.debug.print("{s}: {s}\n", .{ arg.ident, arg.typ.ident });
            const argSymb = try self.buildValueSymb(table, arg.typ, false);
            if (!try table.insert(arg.ident, argSymb)) return error.FailedToInsert;
            try inputArr.append(table.getType(arg.typ) orelse SymbType.Void);
        }
        const input = try inputArr.toOwnedSlice();

        const output = try self.allocator.create(SymbType);
        output.* = if (retType) |typ| table.getType(typ).? else SymbType.Void;
        const typ = SymbType{
            .Function = .{
                .output = output,
                .input = input,
            },
        };
        const id = self.reserveId();
        var argstring: []const u8 = "";
        if (input.len != 0) {
            argstring = try input[0].toString(self.allocator);
            for (1..input.len) |i|
                argstring = try std.mem.join(self.allocator, ",", &[_][]const u8{ argstring, try input[i].toString(self.allocator) });
        }

        const name = try std.fmt.allocPrint(self.allocator, "fn({s})->{s}", .{ argstring, try output.toString(self.allocator) });
        _ = try table.insert(name, typ.toSymb());

        return Symbol{
            .Value = SymbValue{
                .mut = true,
                .id = id,
                .typ = typ,
            },
        };
    }

    fn buildValueSymb(self: *Populator, table: *SymbolTable, typ: pars.TypeIdent, mutable: bool) !Symbol {
        if (table.getType(typ)) |newTyp| {
            const value = SymbValue{
                .typ = newTyp,
                .id = self.reserveId(),
                .mut = mutable,
            };
            return value.toSymb();
        }
        return error.UnknownType;
    }
};