Crow programming language

andy andy-hanson at protonmail.com
Thu Feb 15 23:46:10 UTC 2024


On Thursday, 15 February 2024 at 15:24:37 UTC, IchorDev wrote:

> You can make a scope with `nothrow`, `@nogc`, etc.:

I've been setting `@safe @nogc pure nothrow:` at the top of 
(almost) every module, but then I still have to do it at the top 
of each struct in the module (if it has functions) and after each 
delegate type.

> If you make global variables `immutable`, you can access them 
> in `pure` functions.

Is it as simple as that? I'd have to cast away the `immutable` 
when adding a new interned string though. Is that still the 
correct way to do it?

> I think you're not meant to cast away `scope`?? `scope` is 
> meant to guarantee that a variable doesn't escape the given 
> scope; casting it away breaks that guarantee, so why use it? If 
> you're using it for memory allocation, be careful... it's not 
> meant for that.

I declare a parameter `scope` whenever it's true — the memory 
isn't retained anywhere — even if I can't prove that to the 
compiler, so it needs to be trusted instead. This comes up a lot 
because `scope` only applies one level deep, so if I need a 
pointer to something `scope`, I'm forced to cast away the 
scopeness of the pointee. This happens if I need to put it in a 
`struct` since `struct`s can't contain `ref`s, only pointers.

     @safe @nogc:

     void main() {
         int i = 3;
         scope S s = S(&i);
         foo(s);
     }

     struct S { int* ptr; }

     struct Ctx {
         private S* s;
     }

     void foo(scope ref S s) {
         scope Ctx ctx = Ctx(ptrTrustMe(s));
         bar(ctx);
     }

     void bar(scope ref Ctx ctx) {}

     @trusted T* ptrTrustMe(T)(scope ref T x) {
         size_t res = cast(size_t) &x;
         return cast(T*) res;
     }


More information about the Digitalmars-d-announce mailing list