205 points · by ingve · 4y ago · 232 comments
I don't like the proposed syntax though, because it introduces a new meaning for the & operator. In all other uses, the & operator modifies the type of the operand, to be the opposite of the * operator.
In the proposed syntax, & becomes something a little bit different: a C++-style reference. I think it would introduce too much language confusion.
A more C-like syntax would be:
defer(captures-by-value; captures-by-reference) {}.
Defer() statements would be executed at scope-exit, in last-in first-out order. Standard block scoping would apply for anything declared inside of the defer().
But I don't think there's any need to differentiate between different captures. Capture by value is enough because what do you need in C if you need a reference? Capture the value of the pointer.
{
void *chunk = malloc(x);
defer (chunk, void **reference = &chunk) { ... }
...
}
This would allow you to operate on the value both from the defer declaration time and defer execution time, whichever it is that you need.Capture-by-value does have a weakness though, in that it requires allocation (whether stack or heap). Capture-by-reference doesn't have any storage overhead.
In my example, I suggested having both. But if we had to pick only one, capture-by-value would be the one to use.
But this still doesn't address the problem the change is used to contain. Should defer free a variable's value as it is when defer is used or the value at the end of the scope.
And is it really such huge change. I don't find it too far removed that it becomes confusing and I appreciate the additional control over what should be freed and where. You can imagine a scenario where a variable is being reused multiple times where this kind of additional control might be useful.
Capture-by-value takes a snapshot of the value instantly, and stores it until the block is executed.
Capture-by-reference waits to evaluate the variable until the block is executed.
Between the two, capture-by-reference is the least surprising behavior IMO. It acts like the deferred code is copy/pasted onto the end of the function.
Capture-by-value is the most flexible, and can also emulate capture-by-reference by using pointers. Any syntax should either support both, or only capture-by-value.
We are not using teletypes anymore, the days of confusing single character keywords should truly be over.
> This indicates that existing mechanism in compilers may have difficulties with a block model.
Erm. No. GCC's cleanup attribute is attached to nested blocks. Whatever that means for the conclusion there.
How is a pretty basic misunderstanding like this seeping into an ISO WG document?!?
[add.:] in case anyone wants to double check: https://gist.github.com/eqvinox/c062f5a46f3a60b1151fcdf3e91a...
There is no ISO magic ensuring working groups are all-knowing. There's an excellent chance that no members of WG14 have a deep in-depth knowledge of GCC, or that members who did they weren't particularly interested in that part of this paper (e.g. they were already staunchly for or against, remember ISO Working Groups are democratic, a proposal does not need consensus, so a working group member who thinks your idea is inherently good or bad might just skim the introduction, and move on)
I previously shared a "with" statement idea on HN that I thought fit with the rest of the language.
with (FILE *fp; fp = fopen(path, "wb"); fclose(fp)) {
...
} else {
perror("Failed to open file");
}
https://github.com/taeber/cwithhttps://news.ycombinator.com/item?id=23370693
edit: formatting
for(FILE *fp = fopen(path, "wb");
fp != NULL;
fclose(fp), fp = NULL) {
...
}If you are interested, I did provide a few macros[2], but as another commenter pointed out, they won't handle an early return. You can use "break" to exit early though:
#define with(declare, startup, cleanup, block) \
{ \
declare; \
if (( startup )) { \
do { \
block; \
} while(0); \
cleanup; \
} \
}
with (FILE *fp, fp = fopen(path, "rb"), fclose(fp), {
fread(buf, 1, sizeof(buf)-1, fp);
if (ferror(fp)) {
perror(path);
break;
}
printf("%s\n", buf);
success = 1;
})
There's also "withif" #define withif(declare, startup, cleanup, block, otherwise) \
{ \
declare; \
if (( startup )) { \
do { \
block; \
} while(0); \
cleanup; \
} otherwise; \
}
[1]https://github.com/taeber/cwithHere is a macro that can be used to emulate a defer
#define CONCAT_(a, b) a ## b
#define CONCAT(a, b) CONCAT_(a, b)
#define UNIQUENAME() CONCAT(i_, __LINE__)
#define SCOPE_(counter, init_stmt, exit_stmt) for (int counter = ((init_stmt), 1); counter--; (exit_stmt))
#define SCOPE(init_stmt, exit_stmt) SCOPE_(UNIQUENAME(), (init_stmt), (exit_stmt))
Granted it's a hack, but it can be useful at times. I've used something like it to define a large data hierarchy in code for example, as having to close all the nodes manually is tedious.You could wrap a second for-loop around the definition of the macro to at least be able to catch misplaced "break" statements.
const sprite_sheet_surface = c.SDL_LoadBMP("res/tile.bmp") orelse {
c.SDL_Log("Unable to create BMP surface from file: %s", c.SDL_GetError());
return error.SDLInitializationFailed;
};
defer c.SDL_FreeSurface(sprite_sheet_surface);Why "on function exit" style defers - already known to be a bad idea from Go - is beyond me. Such a solution more or less requires storage of potentially unbounded allocations.
Foo *f;
for (int i = 0; i < very_big_value; i++) {
f = get_foo(i);
// BOOM
defer return_foo(f);
}
I would sort of understand if this was proposed for a high level language garbage collection where actual memory usage is secondary.Is there something you can point me to about this? I write Go professionally and from a readability and utility standpoint I really like it in common scenarios. I hadn't heard its a know bad idea and am just curious. Thanks.
Making things more confusing, Rust is inferring scopes you never explicitly wrote, for example Rust brings a new scope into existence whenever you declare a variable with a let statement:
let good = something.iter().filter(is_good).count(); // good is a usize
let good = format!("{} of them were good", good); // a String
This is fairly idiomatic Rust, whereas it would sound alarm bells in a lot of languages because their shadowing is dangerous (if you hate shadowing you can tell Rust's linter to forbid this, but may find some other people's Rust hard to read so I suggest trying to see if you can live with it instead).Obviously that first variable named "good" is gone by the time there's a new variable named good, and so that usize was dropped (but, dropping a usize doesn't do anything interesting, beyond making life harder for a debugger on optimised code since this "variable" may never really exist in the machine code). On the other hand the String in that second variable named "good" has a potentially long lifetime, if it gets out of this local variable before the variable's scope ends.
Because Rust is tracking ownership, it will know whether the String is still in good when that scope ends (so the String gets dropped), or whether it was moved somewhere else (e.g. a big HashMap that lives long after this stack frame). Because it tracks borrowing, it will also notice if in the former case (where the String is to be dropped) there are outstanding references to that String alive anywhere. That's prohibited, the lifetime of the String ends here, so those references are erroneous, your program has an error which will be explained with perhaps a suggestion for how to fix it.
It doesn't matter what the defer does, if it's allocated in a for statement and doesn't go off until the surrounding function exits, then it's going to have to stuff tons of function pointers and parameters somewhere, presumably alloca'd onto the stack over and over.
That's not C. That shouldn't be C.
There are a dozen languages for doing clever dynamic magical things in code. C is still fairly straightforward. Use one of the other languages instead of bagging down C with complexity until it turns into another difficult C++ variant over time.
https://sentido-labs.com/en/library/cedro/202106171400/#defe...
Also a goto cleanup becomes complex if you have, say a dozen variables to cleanup.
Anyway, i think this is really syntaxtic sugar for the Cpp destructor. I peresume that the lambda will create an object, which will hook itself to the same mechanism that calls cpp destructors at the end of blocks.
And, as all major c compilers are also cpp compilers this seems a good idea to me. And ofcourse the lamda syntax seems same as cpp. So rhats where all this comes from.
The only other proposal I'm more interested in are the lambda approaches: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2890.pdf
double * const q = malloc(something);
/* use whatever magic new syntax here, 'q' will not change in this scope */
That wasn't so hard, in my opinion. They could simply let 'defer' fail if the referenced pointer isn't constant. Also, as a micro-wtf I was confused by the use of 'double', for a generic allocation I would have expected void.I don't know how well the proposed defer would work here but as long as you can look at actual variables (and not constants), you could do something like this:
int error = 0;
void *resource = malloc(N);
defer [&]{ if (error) free(resource); }
if ((error = do_stuff(resource)) != 0)
return NULL; // something went wrong, resource freed
if ((error = do_more_stuff()) != 0)
return NULL; // something went wrong, resource freed
return resource; // all ok, let the caller keep it1) I don't se why they chose function over scoped so please enlighten me 2) the proposal said there were debates whether defer free(ptr) refers to the ptr where the defer first appears, or to the current ptr that appears when the defer block is being executed. As someone mentioned, gotos already work in the latter way. Same goes with i++ in a for loop, I could do whatever I wanted with the i inside the for, and the i++ or the exit condition would use the latest value of i, not the value at the start of the block.
Wait, what? The whole point of defer is to let you do that. People like defer because it's different control flow. If that's why X doesn't like defer, X shouldn't use it. No big deal.
I don't like it either, but it allows for a simpler syntax, consider e.g. "f = fopen(...); if (f) { defer fclose(); }". You'd need special syntax for the defer to escape the block. Although this example is a bit forced, because usually you'd return from the function on error anyways.
* There is no generic way to say whether a defer should free up a variable based on the value it has when the defer was encountered, or a potentially-different value the variable might have when the defer is actually run. * So the best thing to do seemed to be to give the programmer the ability to make the choice. * Lambdas are the means they chose to make that happen.
But this all seems to stem from a desire to enable a use case beyond what an obvious use of a goto idiom would support.
"Whereas gcc’s cleanup attribute is attached to functions, POSIX’ cleanup functions and the try/finally are attached to possibly nested blocks.
This indicates that existing mechanism in compilers may have difficulties with a block model. So we only require it to be implemented for function bodies and make it implementation-defined if it is also offered for internal blocks.
Nevertheless, we think that it is important that the semantics for the feature are clearly specified for the case of blocks, such that all implementations that do offer such a feature follow the same semantics. Therefore it is also a constraint violation to ask for the feature for blocks on implementations that don’t have support for it."
To call this incompetent would be too kind. Completely wrong about the scope of gcc's cleanup attribute, wrong to omit the prior art from Dlang, utterly wrong about what it "indicates", wrong about making it implementation-defined ... and that's just this one section.
It would be a shame if this defer was limited to function scope. It would be very useful in nested blocks as well. But, I would still appreciate it.
defer and auto are the only things I would love to see in C.
for _, lock := range locks {
lock.Lock()
defer lock.Unlock()
}
To acquire locks in a loop and release them at the end of a function. Otherwise the previous lock would be dropped each time the loop executes.I've never seen the advantage to having a block structured defer: it's easy to add a new function, it's not always possible to remove a block.
Function-scope defer is something that surprises everyone I explain it to. Programmers naturally expect defer to be block-scoped.
that looks like a super big gotcha, hasn't there been enough bugs with alloca() being called in a loop yet to show how risky and unintuitive this is ? block-scoped is explicit and explicit is good
for _, lock := range locks {
lock.Lock()
// Do something with lock
}
And I don't really do Go, but in Rust, if I wanted to lock some arbitrary list of locks for a whole function, it would just be something like this at the top: let _ = locks.iter().map(|l| l.lock().unwrap()).collect::<Vec<_>>();If I had to choose between allowing that pattern and allowing reasonable usage in all control constructs, I'd choose the latter.
Is it worse than in C that there is no concept at all? Is it better that everyone is on their own to do it their own way every time?
I’m not above making the eaiser, but to your point when I see their example of:
double* q = malloc(something);
defer [qp = &q]{ free(*qp); };
That doesn’t look like the C that I know.What's the alternative, though? Sprinkle your code with try..finally's? RAII like in C++?
Otherwise a generic _bracket_ operator could be introduced, similar to Python's `with` statement. In C it might be a bit hard to parameterize, but even if it just requires you to use a void, it's still an improvement vs. not having anything at all. (Talking about language features so `__attribute__((__cleanup__))` doesn't count.)
Imagine something like this:
FILE* handle = bracket(fopen("data.bin", "rb"), fclose) {
fread(..., handle);
return;
fwrite(..., handle);
} // <-- implicitly calling fclose(handle), always
Edit: After writing this sample I could even an optional `else` block in case `fopen` returned `NULL`.Edit2: Of course, syntax fine-tuning would be welcome. For instance, `handle` should be restricted to the bracket's scope.
Also why is RAII bad? It's an awesome feature in C++.
I didn't mean it's bad (I used to be a C++ developer myself and enjoyed RAII a lot), just wondering what are the alternatives that the OP doesn't consider "hacks". RAII would require to introduce constructors/destructors in the language, with all the gotchas (and probably you'll want a full-fledged OOP after that), which is apparently against Go's design principles as a simple language.
>Auto-Closable interface with syntactic support.
I don't see much difference here in practice; the whole difference is that in C#, for example, you use "using" on a whole object, while in Go it's a "defer" on a specific method of the object (or a standalone function). You are not limited to a single method and can use it on any method you deem necessary.
Auto-closeable/RAII, however, is less flexible in ad hoc situations specific to a certain function (you have to define dummy classes just to make sure a function is called no matter what), Go allows to use "defer" on a lambda. Auto-closeable also ties control flow to an object, which makes sense in an OOP-focused language, but Go isn't one.
Zig has errdefer which only runs if an error occurred below the statement within that scope. It allows you to always keep cleanup locally, but you can still handle errors for your business logic somewhere else.
errdefer is cool, but I don't think C should support it. Mainly because you'd need to spec errors at a language level, and doing that today is probably impossible.
Anyway, this would be great to have in C as it would simplify how resources are handled.
The "implicitness" and hidden nature of destructors is a disadvantage, it's the unpleasant way it can introduce behavior which might be surprising.
I want "call this function later", not "allocate (and later deallocate and do stuff with) this object." Using objects with destructors is just a roundabout way to achieve the former and fails to express the intent directly. Even though it might have zero runtime cost, it's not free of conceptual baggage.
There is a reason why it was introduced in Go.
It seems barely more implicit than expression-3 in a for loop.
I don't feel like it's going too far for C.
Pragmatic point of view:
In 99% of cases, the developer doesn't care what the compiler produces and doesn't have to. A mechanism providing a complex control flow in the compiler output but is incredibly easy to read and reason about in the source code is useful in the vast majority of cases.
And for the 1% of cases where the programmer actually needs to know what the compiler produces, and / or full control over the control flow, the solution is simple: don't use `defer` and there, done, full control to the developer.
So where exactly is the downside?
They should have made it so that cleanup took an expression block:
void* foo __attribute__((cleanup({ free(foo); }))) = malloc(bar);
Or at least allow a statement expression returning a compile-time known function pointer: void* foo __attribute__((cleanup(({ void wrapper(void** p) { free(*p); }; wrapper })))) = malloc(bar);
Sure, it still looks ugly, but at least a single generic macro would be able to clean it up and make it look better.(Or, since the standard would be creating new names, have "cleanup" and "cleanup_ptr" instead. Assuming that this is a separate attribute namespace, which I believe it is[?])
FWIW, you do sometimes need the address of the variable. Particularly if it's some struct that is made a member of some container (e.g. linked list) temporarily - you need the original variable's address to unlink it.
Or you could just put up with C, like everybody else does, and be quietly thankful that the myriad layers of our modern, complex systems are being maintained by other people.
The point here is that the C working group should be standardizing existing practice and helping the existing users of C, and not striking out making bizarre new syntax choices and keywords which are completely unproven.
scope (exit), scope (failure), scope (success)
https://tour.dlang.org/tour/en/gems/scope-guardsCan someone explain to me how a feature used for freeing memory, closing file descriptors, releasing locks and all other cleanup scenarios are now possibly entering undefined behavior territory? I get that's not the intent but... Ugh...
But I agree, making this bit implementation defined is not cool. I don't have strong opinions on whether defer should be in C or not. It does seem like a potentially useful feature. Whatever they do though, I think they should do it right or not do it at all. The last thing I want is to bloat the language with half-assed features that you can't use half the time because they're not defined well enough. If people want implementation defined features, geez, just keep using compiler extensions until the WG can define a proper standard.
Apart from this bit, the proposal seems pretty decent to me. I kinda like the lambda syntax and the control it gives you over the value you capture. Just make it block scoped and don't leave it implementation defined.
try (MyCloseable c = useSomething()) {
// stuff
}
Why isn't this the path explored? The main difference would be not having extra nested blocks. That seems relatively minor, no? It can be improved arg list: try (MyCloseable c1 = useSomething(), ElseThing c2 = elseThing()) {
// stuff
}A great strength of C is that if you want more features you just go to a subset of C++, no need to add them to C. C++ is the big, ambitious, kitchen-sink language. When C++ exists we don't need to bloat C.
Fortran was originally carefully designed so that people who aren't compiler experts can generate very fast (and easily parallelized) code working with arrays the intuitive and obvious way. But later Fortran added OO and pointers making it much harder to auto-parallelize and avoid aliasing slowdown. Now that GPUs are rising it turns out that the original Fortran model of everything-is-array-or-scalar works really well for automatically offloading to the GPU. GPUs don't like method-lookup tables, nor do they like lambdas which are equivalent to stateful Objects with a single Apply method.
Scientists are moving to CUDA now, which on the GPU side deletes all these features that Fortran was bloated with. Now nVidia offers proprietary CUDA Fortran which is much more in the spirit of original Fortran, deleting OO and pointers for code that runs on GPU. If the ISO standards committee didn't ruin ISO Fortran for scientific computing by bloating it with trendy features we could all be running ISO Fortran automatically on CPUs and GPUs with identical code (or just a few pragmas) and not be locked in to proprietary nVidia CUDA.
But GPUs are now mainly used for crypto greed instead of science for finding cancer cures or making more aerodynamic aircraft so maybe it all doesn't matter anyway.
This is a rationalization, and a bad one. When your solution is "just pull in another programming language", you have a problem.
C doesn't need "defer" because C programmers have managed since the 1970s to implement operating systems, compilers, interpreters, editors, etc., just fine without it. Those who want a bigger C can use C++, this pond is big enough for two fish.
Good straw man there. Did I say all languages need to be exactly the same? This comment just looks like something you can fall back on to reject any feature addition to C. Its too bad really, as its sentiment like this that is killing the language. Many people are sick and tired of old, crusty C, where it takes close to a decade to add or change anything. I like the idea of a small, performant language, but when you put such a stranglehold on changes, you choke out most chances of innovation.
The fact that goto-based solutions and a non-standard GCC extension are common methods of resource cleanup in C today seems to suggest that a standardized language construct for resource cleanup would be appreciated.
> A great strength of C is that if you want more features you just go to a subset of C++, no need to add them to C.
What is C for then? Cleanup of function-scoped resources is a major concern in every large C codebase I've seen.
If one has trouble writing correct cleanup code conventionally (with "goto out" and a single function exit), then allowing them to use defer will only lead to more obscure issues.
And if defer is meant to make code slimmer, it still doesn't belong to C, because it leads to implicit execution and memory/stack allocation.
C is an explicit and verbose language. What you see is what you get. This is the spirit of the language. Unlike with, say, C++ where "a + b" may actually produce kilobytes of machine code, because + just happend to be overloaded.
I've written countless functions in this style and I don't enjoy it. I think it's better than the other styles of resource cleanup in C, but it's not ideal. In this style, whenever I add a resource to a function, I have to go to the top, add the declaration (with a sentinel value,) then go to the out label, check for the sentinel value and conditionally destroy it. I'd much rather add the declaration, initialization and destruction of the resource all in one place. That would make it much harder to forget the destruction, for one thing.
> And if defer is meant to make code slimmer, it still doesn't belong to C, because it leads to implicit execution and memory/stack allocation.
I don't get the implicit execution thing, and I don't see how it's like that C++ example. The only code that executes is written in the function itself, inside the defer block.
I don't see why block scoped defer should cause any more memory or stack allocation than a goto based cleanup handler. It's just a different way to organize the source code. In some instances it might actually allow you to omit some local variables (that otherwise would have to be optimized out by the compiler).
> C is an explicit and verbose language.
It's relatively explicit, I agree. However, defer doesn't change that much. You still see exactly what code runs inside your function. The only real change is that code's location. It's not that different from putting expression-3 in your loop header and having it be evaluated implicitly when you reach the end of the body or do a continue. If you wanted to be explicit, you'd ban for loops and use gotos in a while loop to replace continue. Umm, be my guest, but I prefer the less verbose approach.
And that gets me to the second point... C can be surprisingly terse despite requiring you to be rather explicit, and that's one of the things I really like about C. If anything I'd love to see features that allow it to be even more terse.
> Unlike with, say, C++ where "a + b" may actually produce kilobytes of machine code
Oh, I agree. I really don't want tons of hidden code in C. However, the deferred block is still explicitly coded inside your function and not at all hidden from you someplace else. So it's not like you need to go spelunking through a pile of headers and class definitions to discover that there are destructors running SQL queries when your function returns.
In that respect, defer remains very explicit and transparent so I'm ok with it.
Since I tend towards read-only instance data, I often live my life considering an object to mostly be a bag of closures with a shared outer scope.
While the first draft was released in 1983, the first ratified C standard was in 1989.
The first edition of "The C Programming Language" (from which I first learned the language) was published in 1978, over a decade before the language was standardized.
You are correct that C89 added function prototypes. However, contrary to your implication, C borrowed the concept and syntax from C++.
There's a notable difference between C's prototypes and C++'s ... `int foo();` in C is not a prototype, whereas in C++ it's equivalent to `int foo(void);` ... C had to maintain compatibility with K&R style declarations, whereas C++ didn't.
They make a classic mistake of trying to solve a problem by adding more complexity. They cannot decide on by-value or by-reference, so they take the convoluted C++ syntax to allow specifying one (as well as other semantics?).
It does not fit with C in my opinion. It will also hurt third party tools that wish to understand C source code, because they must inherit this complexity.
I would prefer a solution where they simply pick one (by ref / by value) and issue a compiler warning if the programmer has misunderstood. For example, pick by-value and issue a warning if a variable used inside the defer is reassigned later in the scope.
The point of this feature is to be non-cannonical RAII. I.e. it is about cleaning up a location. This data oriented approach is similar to how "locked data" is more correct and intuitive than "critical sections".
Now I get C being low level, so perhaps this is better, but I can't really imagine the thing I am cleaning up (as opposed to auxiliary info like an allocator to deallocate memory with) being captured by value.
BTW, speaking of moves, a "set this bool if I use this variable by value" feature would be very useful. Skip C++'s mistake and do Rust's model. Would work great with this feature.
I was wondering the same thing; what is the use-case for needing a capture-by-value option at scope exit?
Just make all captures a capture-by-reference and it works for all use-cases.
Projects that target only GCC and Clang can use __attribute__((cleanup)) without waiting a decade for it.
This is no longer true: https://devblogs.microsoft.com/cppblog/c11-and-c17-standard-...
> Support for Complex numbers is currently not planned and their absence is enforced with the proper feature test macros.
Sadly, there is no future for the C language with a corporation like them in the committee. Much better to look at Zig or Nim, they fill more or less the same space and are developed by smart and passionate people.
They have not sabotaged anything when the feature is optional to start with.
If ISO wanted everyone to actually support it, it wouldn't be optional.
> This indicates that existing mechanism in compilers may have difficulties with a block model. So we only require it to be implemented for function bodies and make it implementation-defined if it is also offered for internal blocks.
How will that work?
* no decision on access to variables
* lambdas are involved at all
* "appearance in blocks other than function bodies [is] implementation-defined"
They cited D in the implementation, but then used Go as the inspiration for the feature. The answer was staring them right there in the face, scope(exit) [1]. Or, you know, they could have cited Zig for the exact syntax they wanted [2].
This feature is completely unusable.
Let me demonstrate. You can't use this inside an if statement:
if (foo) {
const ptr = malloc(...);
defer [&]{ free(ptr); } // implementation defined. get fucked
}
Furthermore, it's go-style, so the defer runs at the end of the function. This is not only implementation defined, it's full-blown undefined behavior because `ptr` goes out of scope before the defer expression runs.Scope-based defer works great. Go-based defer is already problematic enough in Go; in C it's worse than not having defer in the language at all.
[1]: https://dlang.org/spec/statement.html#scope-guard-statement
So the reasonable policy would be to use the same cleanup method everywhere, to avoid footgun firing when code is edited.
C has had its heyday and should simply curl up and die.
people don't understand what "programming" is about anymore
C# is great, but it's not a systems language, it depends on piles of C/C++/etc code in order to run.
Of course you need a lot of binaries which were produced somewhere using low level languages in the process, and you probably need to comply with the C FFI to access a lot of libraries. But nothing that cannot be done with a different low level language.