Skip to content

Instantly share code, notes, and snippets.

@lhorie
Last active March 9, 2021 16:52
Show Gist options
  • Save lhorie/12b0b39697a87fc8444ea288b325f773 to your computer and use it in GitHub Desktop.
Save lhorie/12b0b39697a87fc8444ea288b325f773 to your computer and use it in GitHub Desktop.
zig async recursion
// test.zig
const std = @import("std");
pub const io_mode = .evented;
pub fn main() void {
parse("/somefile");
}
fn parse(file: []const u8) void {
const f = std.fs.openFileAbsolute(file, .{ .read = true }) catch return;
if (file.len != 0) parse("");
}
@lhorie
Copy link
Author

lhorie commented Mar 9, 2021

Error: '@Frame(parse)' depends on itself

@lhorie
Copy link
Author

lhorie commented Mar 9, 2021

solution appears to be to allocate the recursive frame in heap, like so:

// test.zig
const std = @import("std");

pub const io_mode = .evented;

pub fn main() void {
    const arena = &std.heap.ArenaAllocator.init(std.heap.page_allocator);
    const a = &arena.allocator;
    defer arena.deinit();
    
    parse(a, "/somefile");
}

fn parse(a: *std.mem.Allocator, file: []const u8) void {
    const f = std.fs.openFileAbsolute(file, .{ .read = true }) catch return;
    
    if (file.len != 0) {
        const frame = a.create(@Frame(parse)) catch return;
        frame.* = async parse(a, "");
        await frame;
    }
}

thanks @fengb

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment