| ▲ | RossBencina 12 hours ago | |||||||
Good to see Borland's __closure extension got a mention. Something I've been thinking about lately is having a "state" keyword for declaring variables in a "stateful" function. This works just like "static" except instead of having a single global instance of each variable the variables are added to an automatically defined struct, whose type is available using "statetype(foo)" or some other mechanism, then you can invoke foo as with an instance of the state (in C this would be an explicit first parameter also marked with the "state" parameter.) Stateful functions are colored in the sense that if you invoke a nested stateful function its state gets added to the caller's state. This probably won't fly with separate compilation though. | ||||||||
| ▲ | vintagedave 10 hours ago | parent | next [-] | |||||||
Yes, though it was a remarkably brief mention. I believe Borland tried to standardise it back in 2002 or so,* along with properties. (I was the C++Builder PM, but a decade and a half after that attempt.) C++Builder’s entire UI system is built around __closure and it is remarkably efficient: effectively, a very neat fat pointer of object instance and method. [*] Edit: two dates on the paper, but “bound pointer to member” and they note the connection to events too: https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2002/n13... | ||||||||
| ▲ | tyushk 5 hours ago | parent | prev | next [-] | |||||||
Would this be similar to how Rust handles async? The compiler creates a state machine representing every await point and in-scope variables at that point. Resuming the function passes that state machine into another function that matches on the state and continues the async function, returning either another state or a final value. | ||||||||
| ▲ | 1f60c 9 hours ago | parent | prev | next [-] | |||||||
> a "state" keyword for declaring variables in a "stateful" function Raku (née Perl 6) has this! https://docs.raku.org/language/variables#The_state_declarato... | ||||||||
| ▲ | fuhsnn 10 hours ago | parent | prev | next [-] | |||||||
I dreamed up a similar idea[1] upon reading the author's closure proposal, it's also really close to async coroutines. [1] https://github.com/ThePhD/future_cxx/issues/55#issuecomment-... | ||||||||
| ▲ | juvoly 12 hours ago | parent | prev [-] | |||||||
That sounds cool, but this quickly gets complicated. Some aspects that need to be addressed: - where does the automatically defined struct live? Data segment might work for static, but doesn't allow dynamic use. Stack will be garbage if closure outlives function context (ie. callback, future). Heap might work, but how do you prevent leaks without C++/Rust RAII? - while a function pointer may be copied or moved, the state area probably cannot. It may contain pointers to stack object or point into itself (think Rust's pinning) - you already mention recursion, compilation - ... | ||||||||
| ||||||||