Repository navigation
Description
This proposal is a counter-proposal to #158 and #473.
Introducing a new sigil: #. It works like &, %, [], and ? in that you can prefix a type and get a new type:
fn alloc(count: size_t) -> #[]u8 {
// ...
}
fn free(x: []u8) {
// ...
}How it works is that it recognizes that a value transfers ownership. So you need syntax in order to deal with the resource appropriately:
fn foo() {
const slice_resource = alloc(10);
slice_resource[1] = 2; // error: resource deallocation not specified
}You can use the ## prefix operator to "unwrap" the resource. This acknowledges that you will take
ownership of the data and deal with cleaning it up properly.
fn foo() {
const slice = ##alloc(10);
slice[1] = 2; // now it works
free(slice);
}The ## prefix operator is always safe and codegens to a no-op. It simply is a visual representation that the code manually deals with ownership of resources.
More often, however, you will use defer or %defer to handle resource cleanup. These keywords are extended to support unwrapping this type:
fn foo() {
const slice = alloc(10) defer |s| free(s);
slice[1] = 2; // now it works
}
fn foo() {
const slice = alloc(10) %defer |s| free(s);
slice[1] = 2; // now it works
}When you use these syntaxes, you are communicating that you have handled the cleanup of the resource appropriately.
When %defer is used, there is still a manual component to the resource management, when the function does not return from the block the %defer is in with an error. The resource type is only meant to aid in visibility of resource management. When you see ## in code, you should be wondering where the resource is cleaned up and trying to understand how the resource ownership is managed. ## can also inform zig what might be the best thing to do when undefined behavior is encountered in ReleaseSafe mode (see #426 ).
Note: $ instead of # is OK. The # sigil was chosen based on likelihood of being present on international keyboards, but I have no actual data. Research needed.
Note: _ = foo() where foo returns a #T should not be allowed, and likewise if foo returns a %T.
Activity
thejoshwolfe commentedon Sep 23, 2017
Here's an actual real example of code that could benefit from the semantics in this proposal: https://github.com/thejoshwolfe/consoline/blob/master/consoline.h (search for "free").
One more aspect to consider is an example from the link above, where a function returns a disposable array of disposable strings. I'm not sure if/how this proposal relates to that usecase, but below is what I would write in Zig, and then I added some
#sigils where I thought they made sense. Then I added comments about the type of things changing, which requires a lot of hand waving.The above is a simplification of the usecase from the link above where a function provides a list of autocomplete suggestions as a list of strings. In that usecase, it made sense to me that the strings and the list itself would all be deleted by the receiver of the suggestions.
The
#sigil is starting too look inadequate compared to what I really wanted to express in the comments above. I wanted to be able to say "the type of this variable is something that has been deallocated, and so the pointer value is now undefined and a safety error to use." and "the type of this variable is now a newly allocated thing that will be cleaned up on error.".All this analysis might be possible maybe, but also this is starting to look a lot like Rust's borrow checking. Is that where this is headed?
kyle-github commentedon Sep 23, 2017
I think this is quite interesting. The purpose of this is to help enforce handling of the "resource," right?
One could extend this a bit by having the resource allocation/creation function specify the default cleanup handler:
Now when you use it, you get a form of RAII:
In this case, resource_cleanup is automatically called. If you use your ## notation, then that is skipped.
I think most of the use cases will be using a "standard" cleanup function anyway, so you are going to be removing boilerplate most of the time. It does have the disadvantage that you now are starting to have some "magic" in the code, but in this case the idiom would be so common that I think it might be OK.
If the compiler can determine that you did not clean up something then it should be able to correct that when given a default cleanup function.
I am not thrilled about the syntax of where the defer is done, but it does keep in all in one place. I would keep the use of the sigil in both the allocator and the cleanup function for symmetry. The allocator returns a type of '#foo' so the cleanup function should take that as its argument.
kyle-github commentedon Sep 23, 2017
@thejoshwolfe, I am not sure what #[]#[]u8 would mean? How would you allocate that? If you were filling up an array of strings, it seems like you would need to strip off the "#" for the individual strings. I think that this does not really nest all that clearly. Would you have the string destructor inside the outer array destructor? If you did that, then you had to use '##' or something...
Note that I am waving my hands vigorously as to how this might be implemented. A simple function pointer prepended or appended to the underlying type would work though that starts to become a lot of wrapping when combined with ? and %.
thejoshwolfe commentedon Sep 23, 2017
@kyle-github I updated my comment above with much more detail (again).
kyle-github commentedon Sep 23, 2017
Sorry for my slowness here. It is a little more clear after the second edit. However , I am not tracking where "result" comes from in freeSliceOfSlice()... Copy/paste error?
In the allocator, you have this:
There are a couple things here I am missing :-(
result[i] = %return allocate(["free me".len]u8);is going to overwrite the empty slice that allocate made. In freeSlice() something is freed. Does this work ifslice.ptris zero?%returnin the inner allocation loop?thejoshwolfe commentedon Sep 23, 2017
@kyle-github responding to your "default cleanup handler", it's too contrary to the zen of zig to have hidden control flow, like RAII destructors or default function calls at block exit. The way an idea like that would fit into Zig is that instead of the compiler implicitly calling a function, the compiler would just give a compile error until you write the function call explicitly in your code.
kyle-github brings up a new point, which is that it might not be enough to
free()a resource. You might need a specificdeinitfunction based on theinitfunction you used to get the resource. I noticed that instd.ArrayListandstd.Bufferuse theinitanddeinitpattern. You don't just want tofreean ArrayList; you need todeinitit, or else you'll leak the underlying buffer. This also means that the resource management concept extends beyond just pointers and slices, but byval objects like ArrayList can need resource management too (because they are keeping a pointer/slice behind the scenes).So this leads to putting a comptime function pointer in the type of the object itself, which is going to be an awful lot of verbosity in the type.
Again, this has a lot of associated hand waving.
kyle-github commentedon Sep 23, 2017
@thejoshwolfe there is a slippery slope to constructors/destructors there :-)
The point about allowing a default defer was that Zig already does a number of things to make certain idioms really clean (like all the
%handling, which I love!). By allowing the "constructor" function to be any arbitrary function and the destructor to be an arbitrary function, you still get the ability to simulate constructors/destructors if you want or to do other things such as simulating RAII or something akin to Python'swith(with some gyrations).I guess I assumed that the resource concept would extend past memory to include pretty much anything that has a setup and teardown requirement.
Perhaps a managed resource is different enough to make it a first class entity in Zig? To take @thejoshwolfe 's example, perhaps there is a type, similar to
struct, calledresourcethat has an init and de-init function? Very handwavy....Or maybe something along the lines of Python's
withas a new construct. Very explicit and clear what you mean to do.Ilariel commentedon Sep 23, 2017
While throwing a compile error for not handling the resource seems a good way to handle this within scope of Zig Zen, what about copying and moving said resources?
Should there be a @copyResource(src,dst,with_function) and similar move operation available?
Would ownership be tracked or would the resources be special immutable references/ptrs until you unwrap them?
kyle-github commentedon Sep 23, 2017
Since this is getting a bit far afield, what are the use cases that @andrewrk is trying to cover?
Here was what I assumed:
How about something a little different:
#as @andrewrk mentioned to indicate that something needs explicit management.#sigil.##to prefix the type of the parameter.Very, very handwaved, but I hope you can see the flow. As far as I can tell, this works with @thejoshwolfe 's example of init/de-init for buffers that are passed by value.
kyle-github commentedon Sep 23, 2017
Er, looking at this, probably better to reverse the meaning of
##and#because there will be a lot fewer consumer/clean up functions than users of a managed value.kyle-github commentedon Sep 23, 2017
This is a bit speculative since I do not know how Zig is implemented in LLVM, but it looks like a few simple additions to compiler checking make the check for whether a managed resource is handled or not simple:
-- If the value is returned, then the function's caller takes responsibility.
-- if the value is explicitly passed to a consumer function, then the value is handled and any use of the value after that point is an error.
-- if the value is passed to a consumer function via defer, then the value is handled.
I think that this means that all managed/not managed checking is local to a function.
15 remaining items
kyle-github commentedon Sep 24, 2017
@Ilariel yes, that is the part.
I was thinking about this a little bit this morning (it is morning here). Are the
@copyResourceand@moveResourceactually needed as special build-in functions?Here's the reference counting example (heavily snipped for brevity):
Please excuse the handwaved parts. I think if you do this right you do not need the special functions.
PavelVozenilek commentedon Sep 24, 2017
I do not get this proposal but it seems to be some variant of C++'s smart pointers. Smart pointer is just one of possible implementations of ownership management, rather low level and (in C++) quite confusing.
Another option is to have containers which manage (or not) lifetime of their items stored as pointers. This is arguably higher level, and IMHO more intuitive to think about. One project employing this technique is Ultimate++ ( https://www.ultimatepp.org/ ), C++ IDE with their own stdlib and their own unique approach to everything else.
kyle-github commentedon Sep 24, 2017
This is a simplistic reference counting wrapper (not at all complete). It is being used here as a way to show the need (or lack thereof) for special copy/move functions and control over whether a type is assignable or not. It is not a "real" implementation, just a driver for the discussion.
There are several things discussed in this issue and perhaps they should be broken into their own issues:
#sigil to mark types requiring specific management. This started with @andrewrk's proposal and then has diverged in other directions.Ilariel commentedon Sep 24, 2017
@kyle-github, I think you forgot the "#" sigils, but I think everyone will get it, and yes as you said there might not be a other reason for them to be builtins than the names after all they wouldn't really do anything other than communicate the intent I think
@PavelVozenilek The smart pointers happened to just be the easiest "more complex" example. Containers and allocators could be used as an example too.
Ilariel commentedon Sep 24, 2017
To recap about the resource type and the # sigil. Is this correct?
Resource type
PavelVozenilek commentedon Sep 24, 2017
Yes another resource management technique (for memory) - allocator which keeps track of unfreed blocks and shows them as error. My implementation it described in #480. To extend it to other resources is (relatively) easy.
No special syntax was needed, no rules to learn, problematic allocation were identified precisely by file/line or even with stack trace.
Similar approach is used by language Lobster ( http://www.strlen.com/lobster/ ). Unfreed memory is reported at the end of app run.
Language Pony ( https://www.ponylang.org/ ) has opposite approach. It uses very complicated system for ownership, invented to make multithreaded data races impossible.
Ilariel commentedon Sep 25, 2017
Having an allocator that tracks allocations for debugging and profiling is good and it sure helps you debug your memory leaks. However the resource type could make some of bugs and runtime crashes into compile errors which would be more ideal at least according to my interpretation of Zig Zen.
Perhaps ideally we would use an allocator like yours as an resource which gets freed and it will then report the improper usage.
kyle-github commentedon Sep 27, 2017
I think the combination of the
#checking and preventing assignment (that seems a lot more handwaved right now) would be a good base. It does not force anything, but will allow the compiler to catch 90% of the most common error: errors of omission.As far as I understand the Zen of Zig, this seems like a good balance. And, neither of these need to add any runtime overhead if I guess correctly.
pluto439 commentedon Nov 14, 2017
I don't get it, too many words.
Type code + result, or code + error messages. Even if they are fake.
I don't understand in what order I should read
const slice = alloc(10) defer |s| free(s);, my eyes just zigzag.andrewrk commentedon Jan 19, 2018
too clumsy