I've painted myself into a corner with comptime and I'm seeking advice

I didn’t know it was possible to create a comptime program that was so large it would no longer compile. I kept raising @setEvalBranchQuota to fix it, but now, by passing maxInt(u32), the compiler just segfaults. I have to assume I’m either missing something obvious to work around this or I’ve been misusing comptime altogether. After investing several weeks into this tool already, I wanted to see if anyone had insight into how salvageable this project is.

I work in transportation and this is a cli/library for my job. There are a range of versions of raw/processed geodata this library has to pull from. My solution to this was to create a multi-step build system that embedded these files at comptime. When I originally wrote it I just parsed these json files and created the derived hashmaps I needed at runtime. I decided this wasn’t good enough, and I got greedy.

To get around not being able to parse json at comptime, I made a build module that turned the json into zon and handed it + a manifest off to the final program. By largely copying the StaticStringMap implementation, I made a generalized comptime map that would make these maps “instantly” available at runtime. (there’s a lot more to the system but hopefully you get the picture)

pub fn Map(
    comptime K: type, // has to be an int
    comptime V: type, // hopefully a struct, if it's an array we gotta do something else I think
) type {
    return struct {
        kvs: *const KVs = &empty_kvs,

        pub const KV = struct {
            key: K,
            value: V,
        };

        const KVs = struct {
            keys: [*]const K,
            values: [*]const V,
            len: u32,
        };

        const Self = @This();

        const empty_kvs = KVs{
            .keys = &empty_keys,
            .values = &empty_vals,
            .len = 0,
        };
        const empty_keys = [0]K{};
        const empty_vals = [0]V{};
        const empty_len_indexes = [0]u32{};

        // same deal as StaticStringMap
        // has to be a list of struct { K, V }
        pub inline fn init(comptime kvs_list: anytype) Self {
            comptime {
                var self = Self {};
                @setEvalBranchQuota(std.math.maxInt(u32));

                // this is a dogshit sort but it's comptime so you can't get mad at me
                var keys: [kvs_list.len]K = undefined;
                for(kvs_list, 0..kvs_list.len) |kv, i| {
                    const key, const val = kv;
                    _ = val;
                    keys[i] = key;
                }
                std.mem.sort(K, &keys, {}, std.sort.asc(K));
                
                var values: [kvs_list.len]V = undefined;
                for(keys, 0..keys.len) |sorted_key, i| {
                    const index = blk: {
                        for(kvs_list, 0..kvs_list.len) |kv, j| {
                            const key, const val = kv;
                            _ = val;
                            if(key == sorted_key) {
                                break :blk j;
                            }
                        }
                        unreachable;
                    };
                    const key, const val = kvs_list[index];
                    _ = key;

                    values[i] = val;
                }

                const final_keys = keys;
                const final_values = values;

                self.kvs = &.{
                    .keys = &final_keys,
                    .values = &final_values,
                    .len = @intCast(kvs_list.len),
                };

                return self;
            }
        }

        pub fn get(self: Self, key: K) ?V {
            // TODO: keys are sorted, do a binary search
            // but I just want to see if it compiles

            for(self.kvs.keys, 0..self.kvs.len) |map_key, i| {
                if(map_key == key) {
                    return self.kvs.values[i];
                }
            }

            return null;
        }
    };
}

This worked, but compile times ballooned to an insane degree. This should have been a warning, but I pressed on. I made it pretty far and the library is ok and functional, but now that I need to add a set of maps that was derived from 2 other maps, I’ve hit my head on the setEvalBranchQuota ceiling.

I’m sure I’m not the first person to obsessively pre-compute to this degree. Where did I go wrong

Keep an eye on this issue:

It hasn’t been a top priority issue for some time, but at some point it will become the focus.

In the meantime, remember that anything you can do at compile-time you can also do at build-time. And at build-time, run-time is compile-time! :zany_face:

Silliness aside, I do think that generating code or data as a build step is the best thing to do when you run into limitations like this. You might even be able to get something out of it as a consolation prize, for instance, making it easier to inspect and visualize those intermediate artifacts.

I do think that generating code or data as a build step is the best thing to do when you run into limitations like this

If I understand correctly, I believe that’s what I’m already doing? The json → zon conversion happens as its own build step with a separate executable. I could probably try splitting some of it into yet another step though

But then you’re processing that zon into something else at comptime right? you could do that at build-time as well.

Edit: also I’m sure you already checked this but make sure you’re not doing anything O(N^2)…

Sounds like a job for @embedFile().

You seem to use text format (json or zon) and parse it at comptime. You should convert text to binary format and just embed the binary file.

The trouble with embedFile() is I’m making a map that holds structs that have methods on them, not just raw text. To Andrew’s point though, I will try splitting zon → struct conversion into its own step. A bit shaky on the details but I’ll do some reading. My hope is I won’t have to turn the zon into structs, turn those struct into zon, then “de-anonymize” them in the final program. Either way thank you for the insight!

You can use std.mem.bytesAsSlice:

const StructWithMethod = struct {
    text: [7]u8,
    integer: u32,
    float: f32,

    fn method(self: *const StructWithMethod) f64 {
        return @as(f64, self.integer) + self.float;
    }
};

test "generate" {
    const io = std.testing.io;
    const file = try std.Io.Dir.cwd().createFile(io, "binary_data", .{});
    defer file.close(io);
    const slice: []const StructWithMethod = &.{
        .{ .text = @splat('a'), .integer = 2, .float = 3.0 },
        .{ .text = @splat('b'), .integer = 5, .float = 7.0 },
    };
    try file.writeStreamingAll(io, std.mem.sliceAsBytes(slice));
}

const raw_binary = @embedFile("binary_data");
const aligned_binary: [raw_binary.len]u8 align(@alignOf(StructWithMethod)) = raw_binary.*;

test "embed" {
    const slice: []const StructWithMethod = std.mem.bytesAsSlice(StructWithMethod, &aligned_binary);
    try std.testing.expectEqual(5, slice[0].method());
    try std.testing.expectEqual(12, slice[1].method());
}

oh shit that is exactly what I needed, thank you

Make sure to check that the compiler did not mess up the layout of the struct. Make the struct extern if it did.

Can you :check_box_with_check: my answer as solution instead of Andrew’s?

update:

I’ll keep this marked as solved because I think it put me on the right track, but for my specific use case I’m not quite there. Hopefully this extra info will help someone else.

First I want to share this code I should’ve put it in my original post

pub inline fn makeZonMap(comptime T: type, opts: ZonOptions) comptime_map.Map(u24, T) {
    const process_string = if(opts.proccessed) "processed" else "geodata";

    const num_geodata = comptime blk: {
        @setEvalBranchQuota(1000000);
        break :blk Embed.getNumGeodata(opts.path, process_string);
    };

    const embed_option_list: [num_geodata]EmbedOptions = comptime blk: {
        var list: [num_geodata]EmbedOptions = undefined;
        for (manifest.manifest, 0..manifest.manifest.len) |item, i| {
            var version_buf: [24]u8 = undefined;
            const semver = SemVer {
                .major = item.version.major,
                .minor = item.version.minor,
            };

            const version = std.fmt.bufPrint(&version_buf, "{}", .{ semver.toKey() }) catch unreachable;
            const embed_options = EmbedOptions {
                .processed = opts.proccessed,
                .version_text = version,
                .path = opts.path,
            };
            list[i] = embed_options;
        }
        break :blk list;
    };

    const kvs: [num_geodata]struct{ u24, T } = comptime blk: {
        var kvs_buf: [num_geodata]struct{ u24, T } = undefined;
        for(embed_option_list, 0..num_geodata) |options, i| {
            const zon = z: {
                const ZonT = Embed.getGeoDataZonType(options);
                const zon_struct = Embed.getGeoDataZonFromType(options, ZonT);
                const spline_zon = T.init(zon_struct);
                break :z spline_zon;
            };
            const commit_num = std.fmt.parseInt(u24, options.version_text, 10) catch unreachable;

            kvs_buf[i] = .{ commit_num, zon };
        }
        const kvs_final = kvs_buf;
        break :blk kvs_final;
    };

    const map = comptime comptime_map.Map(u24, T).init(kvs);

    return map;
}

This is the evil function I wrote that was making all those maps in the first place. I’ve gotten rid of it now.

So far I’ve split the build into an extra step that creates the binary artifacts in a way that tees up the comptime map in the final executable. Stored as []struct { u24, T }

fn makeMapData(comptime T: type, arena: std.mem.Allocator) [manifest.manifest.len]struct { u24, T } {
    const opts: EmbedOptions = T.embed_opts;
    const versions: [manifest.manifest.len]u24 = blk: {
        var versions_buf: [manifest.manifest.len]u24 = undefined;
        inline for(manifest.manifest, 0..) |man, i| {
            versions_buf[i] = SemVer.new(man.version.major, man.version.minor).toKey();
        }
        const final = versions_buf;
        break :blk final;
    };
    const pre = if(opts.processed) "processed" else "geodata";

    const values: [manifest.manifest.len]T = blk: {
        var values_buf: [manifest.manifest.len]T = undefined;
        for (versions, 0..) |ver, i| {
            const fetch_path = std.fmt.allocPrint(
                arena, 
                "{s}/{}/{s}", 
                .{ pre, ver, opts.path }
            ) catch unreachable;

            const json_data = getGeoDataJson(fetch_path);

            const json = T.fromJson(arena, json_data) catch |err| {
                std.debug.panic("couldn't parse json for {s} - {any}", .{ fetch_path, err });
            };
            values_buf[i] = json;
        }

        const final = values_buf;
        break :blk final;
    };

    const kvs: [manifest.manifest.len]struct { u24, T } = blk: {
        var buf: [manifest.manifest.len]struct { u24, T } = undefined;
        for(versions, values, 0..) |k, v, i| {
            buf[i] = .{ k, v };
        }
        const final = buf;
        break :blk final;
    };

    return kvs;
}

I liked the binary solution because it skipped all the zon parsing that was bogging everything down. Problem is, the struct values in those key/value pairs have members of varying lengths, so trying to write it as bytes like in the above code block doesn’t work.

/// basic example
pub const Locations = struct {
    coords: [][3]f64,
...

I could try a zon approach but then I feel like I’d be back to square one. For now I’ll try implementing some sort of runtime serialization + comptime deserialization and pretend I’m not reinventing protobufs

If you have many slices of the same type, you could store the slices in one contiguous memory and store indices + maybe length in your Locations struct, which would make it trivially serializable. (and possibly more cache friendly depending on how you access the data). You could check out Andrews “programming without pointers” video on this topic.

With this approach it is also trivial to deduplicate the slices, if that is something that would be useful to you.

Yeah that’s pretty much how I planned on implementing it. We’ll see how it goes

taking this out of context will be fun

Probably my last update. Again, thank you all for the input.

For the sake of time I did not create a whole serialization/deserialization schema for all my types. Maybe I’ll revisit that later, but just by setting some max values I could re-use all the existing code. For example:

// old implementation that was passed into makeZonMap
pub fn Zon() type {
    return struct {
        pub const Edge = struct {
            direction: Direction,
            line_code: [2]u8,
            line_length: f32,
            id: u32,
            line: LineSlice,
        };

        pub const Line = struct {
            lla: [3]f64,
            offset: f32,
            v: VertSlice,
        };

        pub const VertSlice = struct {
            start: u32 = 0,
            end: u32 = 0,
        };

        pub const LineSlice = struct {
            start: u32 = 0,
            end: u32 = 0,
        };

        pub const Data = struct {
            vs: [*]const [3]f64,
            vs_len: u32,

            lines: [*]const Line,
            lines_len: u32,

            edges: [*]const Edge,
            edges_len: u32,
        };

        data: *const Data = &empty_data,

        const empty_vs = [0][3]f64{};
        const empty_lines = [0]Line{};
        const empty_edges = [0]Edge{};
        const empty_data = Data {
            .vs = &empty_vs,
            .vs_len = 0,
            .lines = &empty_lines,
            .lines_len = 0,
            .edges = &empty_edges,
            .edges_len = 0,
        };

        const Self = @This();

        /// takes in the <tuple item>.@"1".zon from geodata.zon
        pub inline fn init(comptime zon: anytype) Self {
            comptime {
                var self = Self{};

                @setEvalBranchQuota(10000 * zon.edge_list.len);

                const num_edges: u32 = zon.edge_list.len;
                const num_lines: u32 = blk: {
                    var out: u32 = 0;
                    for(zon.edge_list) |edge| {
                        out += edge.line.len;
                    }
                    break :blk out;
                };
                const num_vs: u32 = blk: {
                    var out: u32 = 0;
                    for(zon.edge_list) |edge| {
                        for(edge.line) |segment| {
                            out += segment.v.len;
                        }
                    }
                    break :blk out;
                };

                var vs_buf: [num_vs][3]f64  = undefined;
                var vs_index = 0;
                var lines_buf: [num_lines]Line = undefined;
                var lines_index = 0;
                var edges_buf: [num_edges]Edge = undefined;
                var edges_index = 0;

                for(zon.edge_list) |edge| {
                    var new_line_list: LineSlice = undefined;
                    new_line_list.start = lines_index;
                    for(edge.line) |line| {
                        var new_vert_list: VertSlice = undefined;
                        new_vert_list.start = vs_index;
                        for(line.v) |v| {
                            vs_buf[vs_index] = v;
                            vs_index += 1;
                        }
                        new_vert_list.end = vs_index;

                        const new_line = Line {
                            .lla = line.lla,
                            .offset = line.offset,
                            .v = new_vert_list,
                        };

                        lines_buf[lines_index] = new_line;
                        lines_index += 1;
                    }
                    new_line_list.end = lines_index;

                    const new_edge = Edge {
                        .direction = Direction.fromLineCodeComptime(edge.line_code),
                        .line_code = edge.line_code,
                        .line_length = edge.line_length,
                        .line = new_line_list,
                        .id = edge.edgeId,
                    };

                    edges_buf[edges_index] = new_edge;
                    edges_index += 1;
                }

                const final_edges = edges_buf;
                const final_lines = lines_buf;
                const final_vs = vs_buf;

                self.data = &.{
                    .edges = &final_edges,
                    .edges_len = @intCast(num_edges),
                    .lines = &final_lines,
                    .lines_len = @intCast(num_lines),
                    .vs = &final_vs,
                    .vs_len = @intCast(num_vs),
                };

                return self;
            }
        }
...
/// current implementation, everything below this is pretty much the same
pub const Spline = extern struct {
    const MAX_VS = 70_000;
    const MAX_LINES = 9_000;
    const MAX_EDGES = 1_500;

    vs: [MAX_VS][3]f64,
    vs_len: u32,

    lines: [MAX_LINES]Line,
    lines_len: u32,

    edges: [MAX_EDGES]Edge,
    edges_len: u32,
...

EDIT: also I made the jump to 0.17.0 during this rework so this isn’t 1:1 but compile times have been noticeably faster so far! Like to an insane degree