Cleaning up

Suppose I have a syntax tree node like this

 pub const Spec = struct {
    definitions: Array(Definition),

    const Self = @This();

    pub fn init(a: mem.Allocator) Self {
        return .{
            .definitions = Array(Definition).init(a),
        };
    }

    pub fn deinit(self: *Self, a: mem.Allocator) void {
        for (self.definitions.items) |*x|
            x.deinit(a);
        self.definitions.deinit();
    }
};

The AST doesn’t live past the lifting into an intermediate representation.

Should I define a cleanup methods on each AST node or just rely on using an bump allocator?

I have cleanup methods all over the place but I’m wondering what the best style is.

It depends on what you want to do. If the lifetime of definitions as in your example is tightly coupled, meaning you’d want to free all of them at once every time, then I’d prefer to use an arena to make it simpler.

2 Likes

ASTs are usually perfect for bumping.

It’s rarely a thing that some bit of an AST outlives any other part.

Your easy path is Arena over mmap

2 Likes