DIP69 - Implement scope for escape proof references

Walter Bright via Digitalmars-d digitalmars-d at puremagic.com
Thu Dec 4 12:38:11 PST 2014


On 12/4/2014 4:55 AM, bearophile wrote:
> I am not expert in such things, but here are few comments and questions.
>
>> Errors for scope violations are only reported in @safe code.
>
> This seems acceptable only if the compiler switch "-scope" implies functions to
> be @safe by default and @system on request, because currently lot of D
> programmers don't apply annotations like @safe to their D code. Opt-in safety
> doesn't work well (and in D we still have the problems caused by null pointers
> and references).

Safety by default is outside of the sco[pe (!) of this discussion. Also, you can 
merely put:

     @safe:

at the beginning of a module and it is now all safe.

> Also consider an annotation like "!scope" or "@escape" for the opposite purpose.

That's part of a more general issue of negation of attributes.


>> Delegates currently defensively allocate closures with the GC. Few actually
>> escape, and with scope only those that actually escape need to have the
>> closures allocated.<
>
> So there's no need for extra annotations to make delegates @nogc in most cases?

Marking delegates as @nogc does not affect the closure, as the closure is 
allocated when the enclosing function is entered.



> Regarding array literals, some people proposed a syntax for fixed-size arrays to
> avoid heap-allocations (the "s" after the array literal):
>
> void foo(int[2]) {}
> void bar(int[]) {}
> void main() @nogc {
>      foo([1, 2]s);
>      bar([1, 2]s);
> }
>
>
> Is DIP69 able to infer those arrays can be both stack-allocated? Is the "s"
> annotations still useful?

It's an idea worth exploring.


> Regarding the benefits, is escape analysis going to be used to allocate
> _automatically_ some small dynamic arrays and classes/structs on the stack
> instead of heap?

This is an optimization opportunity that scope enables.


> And is escape analysis going to automatically give hints to the GC to deallocate
> faster GC-allocated memory that doesn't escape?
>
> void foo() {
>      // Both dynamic arrays don't escape foo
>
>      // Automatically stack allocated.
>      auto a = new int[3];
>
>      // Heap-allocated but deterministically
>      // deleted at the end of foo scope.
>      auto b = new int[10_000];
> }

Another optimization opportunity.



More information about the Digitalmars-d mailing list