Repository navigation
Closed as not planned
Closed as not planned
Copy link
Description
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 errdeferThis 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:
cleancorresponding todefer theCleanupFunction(resource);errcleancorresponding toerrdefer theCleanupFunction(resource);
- If you want to handle resources manually, you must use
nocleanto indicate that you accept
responsibility for the resource. Otherwise you geterror: 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.
Reacted by Tom, Hasen Judi, andrewchambers, Shawn Landden, Komu Wairagu, pixelherodev, DutchGhost, Seth, pfg, Joran Dirk Greef and 87 more
Reacted by Bjorn Pagen, xxxbxxx, Martijn Gerkes, Mark Yan, Diego Bellani, protty, praschke, PL Pery 🐢, Yay295, Alexander Drozdov and 2 more
Reacted by hadroncfy and Enigma Lav
Reacted by Alexandre HOUNDJAGO
Activity
kyle-github commentedon Feb 22, 2018
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 :-(
Ilariel commentedon Feb 22, 2018
@kyle-github I think it was #494
kyle-github commentedon Feb 22, 2018
@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.
tjpalmer commentedon Feb 23, 2018
@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.
hasenj commentedon Feb 27, 2018
I know this is bike shedding, but it reads kind of weird:
Sounds like "cleanly attempt to
get_something()".Maybe something more like
auto_closereads more natural.What exactly does errclean do? It sounds like "if no function call here annotated with
tryreturns 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:
ownortake.Another idea is to mention the cleaning strategy after:
And if desired maybe it can be customized:
And if no cleaning is needed:
But at this point it feels like the language is getting too complicated.
tjpalmer commentedon Feb 27, 2018
@hasenj Interesting. My keyword plan for autoclean was
own, which you intuitively feel would mean the opposite. And mynocleanwasdisown. 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 readclean tryas "autoclean" (or even "be clean with") "the thing I tried and succeeded on" anderrcleanas "autoclean this on error" and I'm quite happy with the "errdefer" symmetry.tjpalmer commentedon Feb 27, 2018
On the other hand, with this proposal in place, you could possibly drop the ad hoc
deferand friends entirely.isaachier commentedon Jul 12, 2018
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.
Hejsil commentedon Jul 12, 2018
@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:
cleanon scope exit. Aka you own this resource and is not gonna pass it uperrcleanon scope exit. Aka, you own this resource when an error occurs.noclean, and is expected to pass the ownership.77 remaining items
PeyTy commentedon May 4, 2023
@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
preservefeels likestaticlifetime from Rust too.What you're proposing here would essentially make Zig a Rust 2.0 (😉)
matu3ba commentedon May 4, 2023
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.
InKryption commentedon May 4, 2023
Bringing up an idea inspired by a discord conversation from a while ago:
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'sinitanddeinitwill work fine with the first argument rule, but wouldn't work well withAllocator'sallocandfree, since the first argument tofreeis theAllocator. Not 100% sure how to rectify this. One idea might be to mark in the resource-freeing function which parameter receives the resource, something likeand 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.Edit 2: another idea would be to make the syntax look like this:
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.
InKryption commentedon May 5, 2023
OK, a slightly revised version of the proposed ideas after some amount of deliberation:
To put some of this into more concrete terms:
An annotation on a function of the form
#nameindicates 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(...), ornoclean.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).defer(...)anderrdefer(...), the result location is represented implicitly by_, and all other relevant arguments must be passed as well. This effectively is the same asdefering orerrdefering 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.defered clean up function should run immediately.In essence, this is purely a formalization of the extremely common-place pattern of paired
init()anddeinit(), turning code likeinto
PeyTy commentedon May 6, 2023
@InKryption consider this, what comes at
????InKryption commentedon May 6, 2023
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).whatisaphone commentedon May 8, 2023
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:
std.Thread.joinandstd.Thread.detachInKryption commentedon May 8, 2023
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.
whatisaphone commentedon May 9, 2023
(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
andrewrk commentedon May 29, 2023
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.
eira-fransham commentedon Nov 26, 2025
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
TypeInfosuch as: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
Foogave 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 likefn no_baz(..) void { return; }. That would encourage devs to make APIs that make leaking memory explicit at the usage site.