aboutsummaryrefslogtreecommitdiff
path: root/src/InternArena.zig
blob: 5dba21e11c4c34e07ebcdfecc5ce76b29746407f (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
306
307
308
309
310
311
312
313
314
315
316
map: std.AutoArrayHashMapUnmanaged(void, void) = .{},
items: std.MultiArrayList(Item) = .{},
extra: std.ArrayListUnmanaged(u32) = .{},

const InternArena = @This();
const std = @import("std");
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;

const KeyAdapter = struct {
    intern_arena: *const InternArena,

    pub fn eql(ctx: @This(), a: Key, b_void: void, b_map_index: usize) bool {
        _ = b_void;
        return ctx.intern_arena.indexToKey(@intToEnum(Index, b_map_index)).eql(a);
    }

    pub fn hash(ctx: @This(), a: Key) u32 {
        _ = ctx;
        return a.hash();
    }
};

pub const Key = union(enum) {
    int_type: struct {
        signedness: std.builtin.Signedness,
        bits: u16,
    },
    ptr_type: struct {
        elem_type: Index,
        sentinel: Index,
        alignment: u16,
        size: std.builtin.TypeInfo.Pointer.Size,
        is_const: bool,
        is_volatile: bool,
        is_allowzero: bool,
        address_space: std.builtin.AddressSpace,
    },
    array_type: struct {
        len: u64,
        child: Index,
        sentinel: Index,
    },
    vector_type: struct {
        len: u32,
        child: Index,
    },
    optional_type: struct {
        payload_type: Index,
    },
    error_union_type: struct {
        error_set_type: Index,
        payload_type: Index,
    },
    simple: Simple,

    pub fn hash(key: Key) u32 {
        var hasher = std.hash.Wyhash.init(0);
        switch (key) {
            .int_type => |int_type| {
                std.hash.autoHash(&hasher, int_type);
            },
            .array_type => |array_type| {
                std.hash.autoHash(&hasher, array_type);
            },
            else => @panic("TODO"),
        }
        return @truncate(u32, hasher.final());
    }

    pub fn eql(a: Key, b: Key) bool {
        const KeyTag = std.meta.Tag(Key);
        const a_tag: KeyTag = a;
        const b_tag: KeyTag = b;
        if (a_tag != b_tag) return false;
        switch (a) {
            .int_type => |a_info| {
                const b_info = b.int_type;
                return std.meta.eql(a_info, b_info);
            },
            .array_type => |a_info| {
                const b_info = b.array_type;
                return std.meta.eql(a_info, b_info);
            },
            else => @panic("TODO"),
        }
    }
};

pub const Item = struct {
    tag: Tag,
    /// The doc comments on the respective Tag explain how to interpret this.
    data: u32,
};

/// Represents an index into `map`. It represents the canonical index
/// of a `Value` within this `InternArena`. The values are typed.
/// Two values which have the same type can be equality compared simply
/// by checking if their indexes are equal, provided they are both in
/// the same `InternArena`.
pub const Index = enum(u32) {
    none = std.math.maxInt(u32),
    _,
};

pub const Tag = enum(u8) {
    /// An integer type.
    /// data is number of bits
    type_int_signed,
    /// An integer type.
    /// data is number of bits
    type_int_unsigned,
    /// An array type.
    /// data is payload to Array.
    type_array,
    /// A type or value that can be represented with only an enum tag.
    /// data is Simple enum value
    simple,
    /// An unsigned integer value that can be represented by u32.
    /// data is integer value
    int_u32,
    /// An unsigned integer value that can be represented by i32.
    /// data is integer value bitcasted to u32.
    int_i32,
    /// A positive integer value that does not fit in 32 bits.
    /// data is a extra index to BigInt.
    int_big_positive,
    /// A negative integer value that does not fit in 32 bits.
    /// data is a extra index to BigInt.
    int_big_negative,
    /// A float value that can be represented by f32.
    /// data is float value bitcasted to u32.
    float_f32,
    /// A float value that can be represented by f64.
    /// data is payload index to Float64.
    float_f64,
    /// A float value that can be represented by f128.
    /// data is payload index to Float128.
    float_f128,
};

pub const Simple = enum(u32) {
    f16,
    f32,
    f64,
    f80,
    f128,
    usize,
    isize,
    c_short,
    c_ushort,
    c_int,
    c_uint,
    c_long,
    c_ulong,
    c_longlong,
    c_ulonglong,
    c_longdouble,
    anyopaque,
    bool,
    void,
    type,
    anyerror,
    comptime_int,
    comptime_float,
    noreturn,
    @"anyframe",
    null_type,
    undefined_type,
    enum_literal_type,
    @"undefined",
    void_value,
    @"null",
    bool_true,
    bool_false,
};

pub const Array = struct {
    len: u32,
    child: Index,
};

pub fn deinit(ia: *InternArena, gpa: Allocator) void {
    ia.map.deinit(gpa);
    ia.items.deinit(gpa);
    ia.extra.deinit(gpa);
}

pub fn indexToKey(ia: InternArena, index: Index) Key {
    const item = ia.items.get(@enumToInt(index));
    const data = item.data;
    return switch (item.tag) {
        .type_int_signed => .{
            .int_type = .{
                .signedness = .signed,
                .bits = @intCast(u16, data),
            },
        },
        .type_int_unsigned => .{
            .int_type = .{
                .signedness = .unsigned,
                .bits = @intCast(u16, data),
            },
        },
        .type_array => {
            const array_info = ia.extraData(Array, data);
            return .{ .array_type = .{
                .len = array_info.len,
                .child = array_info.child,
                .sentinel = .none,
            } };
        },
        .simple => .{ .simple = @intToEnum(Simple, data) },

        else => @panic("TODO"),
    };
}

pub fn get(ia: *InternArena, gpa: Allocator, key: Key) Allocator.Error!Index {
    const adapter: KeyAdapter = .{ .intern_arena = ia };
    const gop = try ia.map.getOrPutAdapted(gpa, key, adapter);
    if (gop.found_existing) {
        return @intToEnum(Index, gop.index);
    }
    switch (key) {
        .int_type => |int_type| {
            const tag: Tag = switch (int_type.signedness) {
                .signed => .type_int_signed,
                .unsigned => .type_int_unsigned,
            };
            try ia.items.append(gpa, .{
                .tag = tag,
                .data = int_type.bits,
            });
        },
        .array_type => |array_type| {
            const len = @intCast(u32, array_type.len); // TODO have a big_array encoding
            assert(array_type.sentinel == .none); // TODO have a sentinel_array encoding
            try ia.items.append(gpa, .{
                .tag = .type_array,
                .data = try ia.addExtra(gpa, Array{
                    .len = len,
                    .child = array_type.child,
                }),
            });
        },
        else => @panic("TODO"),
    }
    return @intToEnum(Index, ia.items.len - 1);
}

fn addExtra(ia: *InternArena, gpa: Allocator, extra: anytype) Allocator.Error!u32 {
    const fields = std.meta.fields(@TypeOf(extra));
    try ia.extra.ensureUnusedCapacity(gpa, fields.len);
    return ia.addExtraAssumeCapacity(extra);
}

fn addExtraAssumeCapacity(ia: *InternArena, extra: anytype) u32 {
    const fields = std.meta.fields(@TypeOf(extra));
    const result = @intCast(u32, ia.extra.items.len);
    inline for (fields) |field| {
        ia.extra.appendAssumeCapacity(switch (field.field_type) {
            u32 => @field(extra, field.name),
            Index => @enumToInt(@field(extra, field.name)),
            i32 => @bitCast(u32, @field(extra, field.name)),
            else => @compileError("bad field type"),
        });
    }
    return result;
}

fn extraData(ia: InternArena, comptime T: type, index: usize) T {
    const fields = std.meta.fields(T);
    var i: usize = index;
    var result: T = undefined;
    inline for (fields) |field| {
        @field(result, field.name) = switch (field.field_type) {
            u32 => ia.extra.items[i],
            Index => @intToEnum(Index, ia.extra.items[i]),
            i32 => @bitCast(i32, ia.extra.items[i]),
            else => @compileError("bad field type"),
        };
        i += 1;
    }
    return result;
}

test "basic usage" {
    const gpa = std.testing.allocator;

    var ia: InternArena = .{};
    defer ia.deinit(gpa);

    const i32_type = try ia.get(gpa, .{ .int_type = .{
        .signedness = .signed,
        .bits = 32,
    } });
    const array_i32 = try ia.get(gpa, .{ .array_type = .{
        .len = 10,
        .child = i32_type,
        .sentinel = .none,
    } });

    const another_i32_type = try ia.get(gpa, .{ .int_type = .{
        .signedness = .signed,
        .bits = 32,
    } });
    try std.testing.expect(another_i32_type == i32_type);

    const another_array_i32 = try ia.get(gpa, .{ .array_type = .{
        .len = 10,
        .child = i32_type,
        .sentinel = .none,
    } });
    try std.testing.expect(another_array_i32 == array_i32);
}