Skip to content

ability to annotate functions which allocate resources, with a way to deallocate the returned resources #782

Closed as not planned

Description

@andrewrk

This pattern is extremely common in zig code:

    const err_pipe = try makePipe();
    errdefer destroyPipe(err_pipe);

    var in_file = try os.File.openRead(allocator, source_path);
    defer in_file.close();

    var atomic_file = try AtomicFile.init(allocator, dest_path, mode);
    defer atomic_file.deinit();

    var direct_allocator = std.heap.DirectAllocator.init();
    defer direct_allocator.deinit();

    var arena = std.heap.ArenaAllocator.init(&direct_allocator.allocator);
    defer arena.deinit();

Generally:

    const resource = allocateResource();
    defer deallocateResource(resource); // or errdefer

This proposal is to

  • make it harder to forget to clean up a resource
  • make it easier to clean up resources

Strategy:

  • Functions which allocate resources are annotated with the corresponding cleanup function.
  • New keywords, corresponding to the defer keywords:
    • clean corresponding to defer theCleanupFunction(resource);
    • errclean corresponding to errdefer theCleanupFunction(resource);
  • If you want to handle resources manually, you must use noclean to indicate that you accept
    responsibility for the resource. Otherwise you get error: must specify resource cleanup strategy.

The above code example becomes:

    const err_pipe = errclean try makePipe();
    var in_file = clean try os.File.openRead(allocator, source_path);
    var atomic_file = clean try AtomicFile.init(allocator, dest_path, mode);
    var direct_allocator = clean std.heap.DirectAllocator.init();
    var arena = clean std.heap.ArenaAllocator.init(&direct_allocator.allocator);

How to annotate cleanup functions:

// std.mem.Allocator
fn create(self: &Allocator, comptime T: type) !&T
    cleanup self.destroy(_)
{
    const slice = try self.alloc(T, 1);
    return &slice[0];
}

// function pointer field of struct
allocFn: fn (self: &Allocator, byte_count: usize, alignment: u29) Error![]u8
            cleanup self.freeFn(self, _),

// std.os.File
pub fn openRead(allocator: &mem.Allocator, path: []const u8) OpenError!File
    cleanup _.close()

Having functions which allocate a resource mention their cleanup functions will make generated documentation more consistent and helpful.

Activity

  1. added
    proposal
    on Feb 22, 2018
  2. added this to the 0.3.0 milestone on Feb 22, 2018
  3. kyle-github commented on Feb 22, 2018

    @kyle-github

    Er... wasn't that something I proposed a few months ago in the discussion on resources and the use of "#" etc? I cannot seem to find the issue :-(

  4. Ilariel commented on Feb 22, 2018

    @Ilariel

    @kyle-github I think it was #494

  5. kyle-github commented on Feb 22, 2018

    @kyle-github

    @Ilariel, Ah, right. Thanks! I looked back, but not that far.

    I would like to see something like this proposal combined with some of the ideas in #494. I think (not carefully thought through!) that it might be possible to come close to Rust's ownership/borrow checker in power. Perhaps it is too easy to allow escapes for it to be workable, but even 90% coverage would catch a huge number of cases. Determining lifetime is not that simple, however.

  6. tjpalmer commented on Feb 23, 2018

    @tjpalmer

    @andrewrk I was imagining something like this though with different keywords, but these are good keywords, too. Perhaps also allow a default standard (like your common self.deinit) so all you have to do is say clean(up) on the function header if you conform?

    @kyle-github I also have some ideas about the "90% coverage" for borrow checking kind of thing, too, but I'd rather just see 1.0 first.

  7. hasenj commented on Feb 27, 2018

    @hasenj

    I know this is bike shedding, but it reads kind of weird:

    clean try get_something();
    

    Sounds like "cleanly attempt to get_something()".

    Maybe something more like auto_close reads more natural.

    What exactly does errclean do? It sounds like "if no function call here annotated with try returns an error, then don't auto close this resource at the end of this function", which sounds like you're implicitly taking owner ship of the resource without explicitly saying so.

    Maybe the default thing should be: if the function "throws" and the resource has not been assigned to any object that lives outside this scope, it's automatically closed, and there's no need to add any annotation for that.

    If you want the resource to not autoclose (even on errors), that sounds like it needs a special syntax, for example: own or take.

    Another idea is to mention the cleaning strategy after:

    try get_something() auto_clean;
    

    And if desired maybe it can be customized:

    try get_something() auto_clean(cleanup_function)
    

    And if no cleaning is needed:

    try get_something() without_clean;
    

    But at this point it feels like the language is getting too complicated.

  8. tjpalmer commented on Feb 27, 2018

    @tjpalmer

    @hasenj Interesting. My keyword plan for autoclean was own, which you intuitively feel would mean the opposite. And my noclean was disown. So many different ways to take implications (and I guess that's why bikeshedding).

    Personally, I still think the keywords clean, noclean, and so on from the proposal are clear. And I'm much happier with the prefix syntax, too. The object of the keyword is clearer to me. I read clean try as "autoclean" (or even "be clean with") "the thing I tried and succeeded on" and errclean as "autoclean this on error" and I'm quite happy with the "errdefer" symmetry.

  9. tjpalmer commented on Feb 27, 2018

    @tjpalmer

    On the other hand, with this proposal in place, you could possibly drop the ad hoc defer and friends entirely.

  10. modified the milestones: 0.3.0, 0.4.0 on Feb 28, 2018
  11. isaachier commented on Jul 12, 2018

    @isaachier
    Contributor

    So the main critique of RAII is that it is type based. That means you need to define a type for each lock/unlock, open/close, allocate/free, etc. Then again, idk a better alternative or how this is any different.

  12. Hejsil commented on Jul 12, 2018

    @Hejsil
    Contributor

    @monouser7dig
    RAII requires constructors, destructors, move semantics overridable copy semantics and wrapping everything in wrapper types (unique_ptr).

    This solution does not require any of these features, because either:

    • You clean on scope exit. Aka you own this resource and is not gonna pass it up
    • You errclean on scope exit. Aka, you own this resource when an error occurs.
    • You noclean, and is expected to pass the ownership.
  13. 77 remaining items

  14. PeyTy commented on May 4, 2023

    @PeyTy

    @tauoverpi what the key differences from Rust's borrow checker?
    To be honest, I don't see any notable differences, except the defaulting to non-linear.
    And preserve feels like static lifetime from Rust too.

    What you're proposing here would essentially make Zig a Rust 2.0 (😉)

  15. matu3ba commented on May 4, 2023

    @matu3ba
    Contributor

    References to linear things pretty much require borrowing (e.g &T and &const T) thus there needs to be a sense of ownership where stack locals are owned by the current block { ... } until returned to transfer ownership.

    Declaring ownership is not the main problem. Enforcing via solving the semantics however is, because otherwise annotations only describe intended semantics.

    The main problem of the Rust borrow checker is summarized here #2301 (comment), so it is a committed local optimum.

    More general formal systems would boil down to more expressive annotations taking into account how the formal system is solved, which are not possible to bake into the syntax as it would mean to enclose all possible formal systems to prove all possible properties.

    Something like #14656 would be necessary to cover these use cases.

  16. InKryption commented on May 4, 2023

    @InKryption
    Contributor

    Bringing up an idea inspired by a discord conversation from a while ago:

    fn make(ally: Allocator, n: usize) Allocator.Error!unmake#[]f16 {
        const result = try ally.alloc(f16, n);
        @memset(result, 0.5);
        return result; // coerces implicitly to the obligation
    }
    fn unmake(
        ret: []const f16,
        allocator: std.mem.Allocator,
    ) void {
        allocator.free(ret);
    }
    
    test {
        const ally = std.testing.allocator;
        // `defer(...)` is required to unwrap the result, and simultaneously does the
        // same thing as `defer unmake(slice1, ally);` all the required state except
        // for the result value itself must be passed as arguments - no closures or
        // contexts or whatever else
        // `errdefer(...)` may also be used for the behavior you'd expect
        const slice1 = try make(ally) defer(ally);
    
        // escape hatch to request to manage the resource manually, eliding automatic cleanup.
        // syntax doesn't matter, could be anything like `foo() noclean`.
        const slice2 = try make(ally) @noclean();
        unmake(slice2, ally);
    
        // this should be a compile error. "clean up unions" or whatever you want to call them
        // should never be stored. They should be treated like half opaque types,
        // in that using one as the type of a field or variable should be a compile error,
        // but should be allowed as the type of an expression (e.g. result of a function call,
        // in-place coercion with `@as`, etc). This helps to avoid double frees.
        const slice3 = try make(ally);
    }

    The pieces that comprise this are all very similar to other concepts brought up in this issue, but I feel this addresses a good bunch of the counter-points of those previous ideas.

    And to just quickly address the "no hidden control flow" argument that may be brought up against this, I would argue that there isn't any control flow that's truly hidden here, as the caller is explicitly forced to either opt-in or opt-out of the cleanup behavior, which effectively makes it as transparent as just deciding whether or not to call a function - it just happens that said function is being "recommended" to clean it up.

    Edit: it occurs to me that, with the syntax presented here, pairings like ArrayList's init and deinit will work fine with the first argument rule, but wouldn't work well with Allocator's alloc and free, since the first argument to free is the Allocator. Not 100% sure how to rectify this. One idea might be to mark in the resource-freeing function which parameter receives the resource, something like

    fn alloc(self: Allocator, comptime T: type, n: usize) Error!free#[]T {
        // -- snip --
    }
    fn free(self: Allocator, #ptr: anytype) void {
        // -- snip --
    }

    and when it comes to how the arguments end up passed, it should behave as if the resource argument is put between the relevant arguments to defer(...), e.g.

    fn make(ally: Allocator, n: usize, align_log2: Allocator.Log2Align) !unmake#[]align(1) i16 {
        // -- snip --
    }
    fn unmake(ally: Allocator, #slice: []const i16, align_log2: Allocator.Log2Align) void {
        // -- snip --
    }
    
    test {
        const ally = std.testing.allocator;
        const slice1 = try make(ally, 15, 0) defer(ally, 0); // the value is passed as if in between `ally` and `0`.
        const slice2 = try make(ally, 31, 4) errdefer(ally, 4); // ditto
        const slice3 = try make(ally, 63, 2) @noclean();
        defer unmake(ally, slice3, 2); // can still call as normal function
    }

    Edit 2: another idea would be to make the syntax look like this:

    const slice = try make(ally, 127, 0) defer(ally, _, 0);

    Which may look a bit odd, but keeps things simple, and is tangentially related to inference, with underscore being the same symbol that's used to infer array literal length.

  17. InKryption commented on May 5, 2023

    @InKryption
    Contributor

    OK, a slightly revised version of the proposed ideas after some amount of deliberation:

    const std = @import("std");
    
    // #unmake is an annotation of the whole function, not part of a type (syntax up for debate,
    // maybe use `@cleanup(unmake)`?)
    fn make(ally: Allocator, size: usize, align_log2: Allocator.Log2Align) E![]T #unmake {
        // -- snip --
    }
    fn unmake(ally: Allocator, slice: []T, align_log2: Allocator.Log2Align) void {
        // -- snip --
    }
    
    test {
        const ally = std.testing.allocator;
    
        // compiles fine, is the same as writing
        // ```
        // const slice1 = try make(ally, 31, 0);
        // defer unmake(ally, slice1, 0);
        // ```
        const slice1 = try make(ally, 31, 0) defer(ally, _, 0);
    
        // compiles fine, is the same as writing
        // ```
        // const slice2 = try make(ally, 127, 8);
        // errdefer unmake(ally, slice2, 8);
        // ```
        // caller takes responsibility for freeing the resource in
        // the absence of error
        const slice2 = try make(ally, 127, 8) errdefer(ally, _, 8);
    
        // this is the fine, it is the same as choosing to omit the
        // `defer unmake(ally, slice4, 4);` code - caller takes responsibility
        // for freeing the resource
        //
        // Syntax up for debate, maybe use a builtin like `@noclean()`, or maybe
        // an operator using the # symbol, or whatever else. Could also be prefix
        // instead of postfix to distinguish from normal defer auto-cleaning.
        const slice3 = try make(ally, 63, 4) noclean;
        defer unmake(ally, slice3, 4);
    
        // // this would be a compile error, it's the same as writing
        // // ```
        // // const slice4 = make(ally, 31, 0);
        // // defer unmake(ally, slice4, 0);
        // // ```
        // // basically, `E![]T` can't coerce to `[]T`
        // const slice4 = make(ally, 15, 2) defer(ally, _, 2);
    
        // this would be a compile error, because the expression resulting from
        // a function annotated with a clean up function is not annotated with
        // either a `defer`, `errdefer` or `noclean`.
        const slice5 = try make(ally, 7, 1);
    
        unmake(ally, slice2, 8); // don't forget to clean up after no errors occurred
    }

    To put some of this into more concrete terms:

    An annotation on a function of the form #name indicates that the result location of the expression of a call to the function is a resource that must be cleaned up. This does not type check against anything yet.

    When this function is called, the caller may transform the resulting expression in whatever arbitrary way is desired; we can say that the expression itself is flagged by the compiler as being the result of a call to a function that's annotated with a clean up procedure.
    If the expression is assigned to a variable, parameter, etc, without getting rid of this "flag" or "metadata" or however you'd like to call it, the compiler issues an error; the only way to get rid of this flagging is by annotating the expression with either defer(...), errdefer(...), or noclean.

    • With noclean, the resulting behavior is that of status-quo: no automatic clean up, the caller may do with the resource whatever they like (return it, clean it up manually or via a different method, etc).
    • With defer(...) and errdefer(...), the result location is represented implicitly by _, and all other relevant arguments must be passed as well. This effectively is the same as defering or errdefering the clean up function from the previously mentioned function annotation, with the aforementioned arguments. They will be as-if declared in the same scope as the result location.
      • The result location is passed implicitly by pointer or by value, with one level of dereference supported, as with method calls.
      • In the case of the result location being the discard identifier, the defered clean up function should run immediately.

    In essence, this is purely a formalization of the extremely common-place pattern of paired init() and deinit(), turning code like

    var list = try std.ArrayListUnmanaged(u8).initCapacity(allocator, 32);
    defer list.deinit(allocator);
    // -- snip --
    return try list.toOwnedSlice();

    into

    var list = try std.ArrayListUnmanaged(u8).initCapacity(allocator, 32)
        defer(_, allocator);
    // -- snip --
    return try list.toOwnedSlice() noclean;
  18. PeyTy commented on May 6, 2023

    @PeyTy

    @InKryption consider this, what comes at ????

    fn make_at_upper_scope(ally: Allocator, size: usize, align_log2: Allocator.Log2Align) E![]T #??? {
        return try make(ally, 31, 0) ???;
    }
    fn make(ally: Allocator, size: usize, align_log2: Allocator.Log2Align) E![]T #unmake {
        // -- snip --
    }
    fn unmake(ally: Allocator, slice: []T, align_log2: Allocator.Log2Align) void {
        // -- snip --
    }
    
    test {
        const ally = std.testing.allocator;
        const slice1 = try make_at_upper_scope(ally, 31, 0) defer(ally, _, 0) /* or what? */;
    }
  19. InKryption commented on May 6, 2023

    @InKryption
    Contributor

    Obligations definitely should not be implicit, as that essentially would start to fall under hidden control flow. Perhaps it could be part of type info, and be retrieved by a helper function as #obligation(make).

  20. whatisaphone commented on May 8, 2023

    @whatisaphone
    Contributor

    It might be too limiting to tie the return value directly to one particular cleanup function, because some resources can be cleaned up in more than one way. For example:

    • a DB transaction can be either committed or rolled back
    • std.Thread.join and std.Thread.detach
  21. InKryption commented on May 8, 2023

    @InKryption
    Contributor

    Well, in the thread case, those are cases wherein it wouldn't make sense to call either of those functions to "release" the resource. If we look at something like C++ or Rust, which have destructors for "resources", they also do not join nor detach in the destructors of their standard thread types.
    These annotations would be focused on the more common use case of resources which are tied to mostly linear scopes.

  22. whatisaphone commented on May 9, 2023

    @whatisaphone
    Contributor

    (It's a real minor point, but Rust does detach when you drop a JoinHandle)

    If more complex resources are out of scope, fair enough, just thought it was worth mentioning

  23. modified the milestones: 0.12.0, 0.11.0 on May 29, 2023
  24. andrewrk commented on May 29, 2023

    @andrewrk
    MemberAuthor

    I think having this issue open is confusing/misleading people. I'm not seriously considering this proposal and it's very likely that nothing will come of it. The only reason it was open was due to being possibly related to async cancellation. That is still an unsolved use case, but even so I'm confident the solution is not annotating resource-allocating functions with what is essentially destructors.

  25. eira-fransham commented on Nov 26, 2025

    @eira-fransham

    I think this should be a lint + documentation, such as "if this line isn’t followed by a defer/errdefer, the compiler should show an error pointing to the relevant line of documentation". With how Zig usually implements such things, a design that could work is something like a field on TypeInfo such as:

    const Foo = @Type(.{
      .struct = {
        // …
        .lints = .{
          .{
            .must_call = .{
              .decl = "baz", 
              .msg = "Should use defer {}.baz",
            },
          },
        },
      },
    });

    The specifics of that would need bikeshedding, of course. There could probably be an annotation that sets that so you don't need to use @Type(..) but you get the idea. I definitely don’t think it should be a new way of doing defer.

    Instead of a single function name, if the person defining Foo gave an array of function names, where you need to call any one of them to silence the lint, then developers could use a pattern where every.must_call-marked fn has a paired no-op fn that silences the warning explicitly. In this case, that could be another function like fn no_baz(..) void { return; }. That would encourage devs to make APIs that make leaking memory explicit at the usage site.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    proposal

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions