[First Draft] Add @gc as a Function Attribute

Quirin Schroll qs.il.paperinik at gmail.com
Mon Jun 17 13:24:22 UTC 2024


On Sunday, 16 June 2024 at 08:13:33 UTC, ryuukk_ wrote:
> Why couldn't attributes accept a parameter, perhaps a flag
>
> `@gc(:yes | :local)`

Attributes taking booleans would be a separate DIP. As I wrote in 
my answer to Rikki, local nogc should not be an attribute at all.

C++ made `noexcept` take a boolean. C++ also made `noexcept` a 
unary operator that returns a boolean if the expression inside 
uses only `noexcept` stuff.

D could easily do the same with `nothrow` and `pure` (as those 
are first-class keywords). It makes less sense for `@safe` (a 
program is supposed to be UB-free anyways), but it would make 
sense for `@nogc`.
I don’t think D would be clever to follow C++’s syntax with a 
prefix operator. [My preferred syntax would be 
postfix](https://issues.dlang.org/show_bug.cgi?id=23797) `is 
pure`, `is nothrow`, `is @nogc`, and yes, even `is @safe`. Those 
would operate on types, though, meaning you’d have to write 
`typeof({ expression; }) is @nogc`. The `typeof` returns a 
function pointer or delegate type which has attributes inferred 
and those attributes can be queried using the new syntax.

You could use these together:
```d
void higherOrderFunction(DG)(scope DG callback) @safe(DG is 
@safe) @nogc(DG is @nogc)
{ … }
```

As for the query for member function attributes that are also 
type qualifiers, I’d suggest a syntax similar to the one I 
proposed in [Issue 
20010)](https://issues.dlang.org/show_bug.cgi?id=20010): `DG is 
...const`.

For example, a template could have an `if (DG is ... const pure)` 
restriction so that it’s guaranteed the callback’s results can be 
cached. (If a delegate isn’t `const` it can maintain state in its 
context, and if it’s not pure, it can maintain state globally.)


More information about the dip.development mailing list