Difference between revisions of "DIP69"

From D Wiki
Jump to: navigation, search
(Fundamentals of scope)
 
(43 intermediate revisions by one other user not shown)
Line 62: Line 62:
 
=== Definitions ===
 
=== Definitions ===
  
==== Lifetime ====
+
==== Visibility vs. lifetime ====
  
Any object exists for a specific period of time, with a well defined beginning and end point: from the
+
For each value <tt>v</tt> within a program we define the notion of <i>lexical visibility</i> denoted as <tt>visibility(v)</tt>, akin to the lexical extent through which the value can be accessed.
point it is created (memory allocated and possibly constructor call), to the point it is released (possibly a call to the destructor followed by memory reclamation). This is called its ''lifetime''.
+
* For an rvalue, the visibility is the expression within it is used.
A reference that points to an object whose lifetime has ended is a dangling reference.
+
* For a named variable in a scope, the visibility is the lexical scope of the variable per the language rules.
Use of such references can cause all kinds of errors, and must therefore be prevented.  
+
* For a module-level variable, visibility is considered infinite. Notation: <tt>visibility(v) = &infin;</tt>.
  
The lifetime of values is based on order in which they are introduced, lexical scope, and the <tt>static</tt> storage class when present. The following rules define a hierarchy of lifetimes:
+
Due to language scoping rules, visibilities cannot partially intersect or "cross": for any two values, either they are not simultaneously visible at all, or one's visibility is included within the other's. We define a partial order among visibilities: <tt>visibility(v1) <= visibility(v2)</tt> if <tt>v2</tt> is visible through all portions of program when <tt>v1</tt> is visible (including the case where both values have infinite visibilities). If two variables have disjoint visibilities, they are unordered.
  
* Data with static duration is considered to have infinite lifetime. The following data has static duration:
+
We also define <i>lifetime</i> for each value, which is the extent during which a value can be safely used.
** string literals;
+
* For types without indirections such as <tt>int</tt>, visibility and lifetime are equal for rvalues and lvalues.
** variables defined at module level;
+
* For all global and <tt>static</tt> variables, lifetime is infinite.
** variables introduced with <tt>static</tt>;
+
* For values allocated on the garbage collected heap, lifetime is infinite whilst visibility is dependent on the references in the program bound to those values.
** variables introduced with <tt>enum</tt> declarations that do not construct an enumerated type.
+
* For an unrestricted pointer, visibility is dictated by the usual lexical scope rules. Lifetime, however is dictated by the lifetime of the data to which the pointer points to.
* Inside functions, a variable's lifetime starts at the point of its declaration and ends with the lexical scope it is defined in. Variables are destroyed in reverse order of their creation. Therefore a variable defined in a scope has a strictly longer lifetime than those defined after it within the same scope. Variables in nested scopes have lifetimes correspondingly nested.
 
* An rvalue's lifetime is temporary; it lives till the end of the largest expression that it appears in.
 
** Rvalues are created in left-to-right lexical order and destroyed in order reverse of creation.
 
* Members of a <tt>struct</tt>, <tt>class</tt>, or statically-sized array have lifetimes enclosed within the lifetime of the aggregate itself and ordered lexically as well.
 
  
Given any two values <tt>v1</tt> and <tt>v2</tt>, exactly one of these statements is true:
+
Examples:
* <tt>v1</tt> has a strictly longer lifetime than <tt>v2</tt>, meaning <tt>v1</tt> is constructed before <tt>v2</tt> and destroyed after <tt>v2</tt>;
 
* <tt>v2</tt> has a strictly longer lifetime than <tt>v1</tt>, meaning <tt>v2</tt> is constructed before <tt>v1</tt> and destroyed after <tt>v1</tt>;
 
* Both <tt>v1</tt> and <tt>v2</tt> have infinite lifetime.
 
  
It is never the case that two lifetimes intersect, i.e. it is impossible to create values <tt>v1</tt> and <tt>v2</tt> such that <tt>v1</tt> is constructed before <tt>v2</tt> but <tt>v2</tt> is destroyed after <tt>v1</tt>. (This concerns language rules; manual calls to constructors, destructors, and/or memory allocation functions may impose arbitrary orderings.)
+
<syntaxhighlight lang=D>
 +
void fun1() {
 +
    int x; // starting here, x becomes visible and also starts "living"
 +
    int y = x + 42; // lifetime(42) and visibility(42) last through the initialization expression
 +
    ...
 +
  // lifetime(y) and visibility(y) end here, just before those of x
 +
  // lifetime(x) and visibility(x) end here
 +
}
  
We define a total ordering of lifetimes: either <tt>lifetime(v1) < lifetime(v2)</tt>, <tt>lifetime(v1) > lifetime(v2)</tt>, or both <tt>lifetime(v1)</tt> and <tt>lifetime(v2)</tt> are infinite. We casually say "<tt>v1</tt> is shorter-lived than <tt>v2</tt>" (or "<tt>v2</tt> is longer-lived than <tt>v1</tt>") if <tt>lifetime(v1) <= lifetime(v2)</tt>.
+
void fun2() {
 +
    int * p; // visibility(p) occurs from here through the end of the function
 +
    // at this point lifetime(p) is infinite because it is null and lifetime(null) is infinite
 +
    if (...) {
 +
        int x;
 +
        p = &x; // lifetime(p) is now equal to lifetime(x)
 +
    }
 +
    // here lifetime(p) may have ended but p is still visible
 +
}
 +
</syntaxhighlight>
 +
 
 +
If a value is visible but its lifetime has ended, the program is in a dangerous, albeit not necessarily incorrect state. The program becomes undefined if the value of which lifetime has ended is actually used.
 +
 
 +
This proposal ensures statically that variables in <tt>@safe</tt> code with the <tt>scope</tt> storage class have a lifetime that includes their visibility, so they are safe to use at all times.
  
 
By consequence of the above, inside a function:
 
By consequence of the above, inside a function:
* Parameters passed by <tt>ref</tt> or <tt>out</tt> are considered to have lifetime somewhere in the caller's scope;
+
* Parameters passed by <tt>ref</tt> or <tt>out</tt> are conservatively assumed to have lifetime somewhere in the caller's scope;
 
* Parameters passed by value have shorter lifetime than those passed by passed by <tt>ref</tt>/<tt>out</tt>, but longer than any locals defined by the function. The lifetimes of by-value parameters are ordered lexically.
 
* Parameters passed by value have shorter lifetime than those passed by passed by <tt>ref</tt>/<tt>out</tt>, but longer than any locals defined by the function. The lifetimes of by-value parameters are ordered lexically.
  
==== Ownership ====
+
==== Algebra of Lifetimes ====
  
A variable ''owns'' the data it contains if, when the lifetime of the variable is ended, the data can be destroyed. There can be at most one owner for any piece of data.
+
Certain expressions create values of which lifetime is in relationship with the participating value lifetimes, as follows:
  
Ownership may be ''transitive'', meaning anything reachable through the owned data is also owned, or ''head'' where only
+
<table border=1 cellpadding=4 cellspacing=0>
the top level reference is owned.
+
<tr><th>'''expression'''</th><th>'''lifetime'''</th><th>'''notes'''</th></tr>
 
+
<tr><td><tt>&amp;e</tt></td><td>lifetime(e)</td><td></td></tr>
==== View ====
+
<tr><td><tt>&amp;*e</tt></td><td>lifetime(e)</td><td></td></tr>
 
+
<tr><td><tt>e + integer</tt></td><td>lifetime(e)</td><td>Applies only when <tt>e</tt> is a pointer type</td></tr>
Other references to ''owned'' data are called ''views''. Views must not survive the end of the lifetime of the owner
+
<tr><td><tt>e - integer</tt></td><td>lifetime(e)</td><td>Applies only when <tt>e</tt> is a pointer type</td></tr>
of the data. A view v<sub>2</sub> may be taken of another view v<sub>1</sub>, and the lifetime of v<sub>2</sub> must be subset of the
+
<tr><td><tt>*e</tt></td><td>&infin;</td><td>lifetime is not transitive</td></tr>
lifetime of v<sub>1</sub>.
+
<tr><td><tt>e1, e2</tt></td><td>lifetime(e2)</td><td></td></tr>
Views may also be transitive or head.
+
<tr><td><tt>e1 = e2</tt></td><td>lifetime(e1)</td><td></td></tr>
 +
<tr><td><tt>e1 op= e2</tt></td><td>lifetime(e1)</td><td></td></tr>
 +
<tr><td><tt>e1 ? e2 : e3</tt></td><td>min(lifetime(e2), lifetime(e3))</td><td></td></tr>
 +
<tr><td><tt>e++</tt></td><td>lifetime(e)</td><td>Applies only when e is a pointer type. This has academic value only because pointer increment is disallowed in <tt>@safe</tt> code.</td></tr>
 +
<tr><td><tt>e--</tt></td><td>lifetime(e)</td><td>Applies only when e is a pointer type. This has academic value only because pointer decrement is disallowed in <tt>@safe</tt> code.</td></tr>
 +
<tr><td><tt>cast(T) e</tt></td><td>lifetime(e)</td><td>Applies only when both <tt>T</tt> and <tt>e</tt> have pointer type.</td></tr>
 +
<tr><td><tt>new</tt></td><td>&infin;</td><td>Allocates on the GC heap.</td></tr>
 +
<tr><td><tt>e.field</tt></td><td>lifetime(e)</td><td></td></tr>
 +
<tr><td><tt>e.func(args)</tt></td><td></td><td>See section dedicated to discussing methods.</td></tr>
 +
<tr><td><tt>func(args)</tt></td><td></td><td>See section dedicated to discussing functions.</td></tr>
 +
<tr><td><tt>e[]</tt></td><td>lifetime(e)</td><td></td></tr>
 +
<tr><td><tt>e[i..j]</tt></td><td>lifetime(e)</td><td></td></tr>
 +
<tr><td><tt>&e[i]</tt></td><td>lifetime(e)</td><td></td></tr>
 +
<tr><td><tt>e[i]</tt></td><td>&infin;</td><td></td></tr>
 +
<tr><td>''ArrayLiteral''</td><td>&infin;</td><td>Array literals are allocated on the GC heap</td></tr>
 +
<tr><td>''ArrayLiteral[constant]''</td><td>&infin;</td><td></td></tr>
 +
</table>
  
 
=== Aggregates ===
 
=== Aggregates ===
  
The following paragraphs define <tt>scope</tt> working on primitive types (such as <tt>int</tt>) and pointers thereof (such as <tt>int*</tt>). This is without loss of generality because aggregates can be handled by decomposition as follows:
+
The following sections define <tt>scope</tt> working on primitive types (such as <tt>int</tt>) and pointers thereof (such as <tt>int*</tt>). This is without loss of generality because aggregates can be handled by decomposition as follows:
  
 
* From a lifetime analysis viewpoint, a <tt>struct</tt> is considered a juxtaposition of its direct members. Passing a <tt>struct</tt> by value into a function is equivalent to passing each of its members by value. Passing a <tt>struct</tt> by <tt>ref</tt> is equivalent to passing each of its members by <tt>ref</tt>. Finally, passing a pointer to a <tt>struct</tt> is analyzed as passing a pointer to each of its members. Example:
 
* From a lifetime analysis viewpoint, a <tt>struct</tt> is considered a juxtaposition of its direct members. Passing a <tt>struct</tt> by value into a function is equivalent to passing each of its members by value. Passing a <tt>struct</tt> by <tt>ref</tt> is equivalent to passing each of its members by <tt>ref</tt>. Finally, passing a pointer to a <tt>struct</tt> is analyzed as passing a pointer to each of its members. Example:
Line 131: Line 160:
 
=== Fundamentals of <tt>scope</tt> ===
 
=== Fundamentals of <tt>scope</tt> ===
  
The purpose of <tt>scope</tt> is to provide a means for ensuring the lifetime of a viewer is a subset of the lifetime of the viewee.
+
The <tt>scope</tt> storage class ensures that the lifetime of a pointer/reference is a shorter of the lifetime of the referred object. Dereferencing through a <tt>scope</tt> variable is guaranteed to be safe.
  
<tt>scope</tt> is a storage class, and affects declarations. It is not a type qualifier.
+
<tt>scope</tt> is a storage class, and affects declarations. It is not a type qualifier. There is no change to existing [http://dlang.org/attribute#scope <tt>scope</tt> grammar]. It fits in the grammar as a storage class.
There is no change to existing [http://dlang.org/attribute#scope <tt>scope</tt> grammar]. It fits in the grammar as a storage class.
 
  
Scope affects:
+
<tt>scope</tt> affects:
  
 
* local variables allocated on the stack
 
* local variables allocated on the stack
Line 144: Line 172:
 
* return value of functions
 
* return value of functions
  
It is ignored for other declarations. It is ignored for declarations that are not views.
+
It is ignored for other declarations. It is ignored for declarations that have no indirections.
  
 
<syntaxhighlight lang="D">
 
<syntaxhighlight lang="D">
scope enum e = 3;  // scope is ignored for enums
+
scope enum e = 3;  // ignored, no indirections
scope int i;      // scope is ignored because integers are not references and so are not views
+
scope int i;      // ignored no indirections
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Line 154: Line 182:
  
 
# A <tt>scope</tt> variable can only be initialized and assigned from values that have lifetimes longer than the variable's lifetime. (As a consequence a <tt>scope</tt> variable can only be assigned to <tt>scope</tt> variables that have shorter lifetime.)
 
# A <tt>scope</tt> variable can only be initialized and assigned from values that have lifetimes longer than the variable's lifetime. (As a consequence a <tt>scope</tt> variable can only be assigned to <tt>scope</tt> variables that have shorter lifetime.)
# A variable is inferred to be <tt>scope</tt> if it is initialized with a view that has a non-&infin; lifetime.
+
# A variable is inferred to be <tt>scope</tt> if it is initialized with a value that has a non-&infin; lifetime.
# A <tt>scope</tt> variable cannot be initialized with the address of a scoped variable.
+
# A <tt>scope</tt> variable cannot be initialized with the address of a <tt>scope</tt> variable.
# A <tt>scope ref</tt> parameter can be initialized with another <tt>scope ref</tt> variable&mdash;<tt>scope ref</tt> is idempotent.
+
# A <tt>scope ref</tt> parameter can be initialized with another <tt>scope ref</tt> parameter&mdash;<tt>scope ref</tt> is idempotent.
  
Basic operation:
+
Examples for each rule:
 +
 
 +
<syntaxhighlight lang="D">
 +
int global_var;
 +
int* global_ptr;
 +
 +
void bar(scope int* input);
 +
 +
void fun1() {
 +
    scope int* a = &global_var; // OK per rule 1, lifetime(&global_var) > lifetime(a)
 +
    a = &global_var;      // OK per rule 1, lifetime(&global_var) > lifetime(a)
 +
    int b;
 +
    a = &b; // Disallowed per rule 1, lifetime(&b) < lifetime(a)
 +
    scope c = &b; // OK per rule 1, lifetime(&b) > lifetime(c)
 +
    int* b;
 +
    a = b; // Disallowed per rule 1, lifetime(b) < lifetime(a)
 +
}
 +
 
 +
void fun2() {
 +
    auto a = &global_var; // OK, b is a regular int*
 +
    int b;
 +
    auto c = &b; // Per rule 2, c has scope storage class
 +
}
 +
 
 +
void fun3(scope int * p1) {
 +
    scope int** p2 = &p1; // Disallowed per rule 3
 +
    scope int* p3;
 +
    scope int** p4 = &p3; // Disallowed per rule 3
 +
}
 +
 
 +
void fun4(scope int * p1) {
 +
    bar(p1); // OK per rule 4
 +
}
 +
</syntaxhighlight>
 +
 
 +
A few more examples combining the rules:
  
 
<syntaxhighlight lang="D">
 
<syntaxhighlight lang="D">
Line 203: Line 266:
 
</syntaxhighlight>
 
</syntaxhighlight>
  
=== Return Statement ===
+
=== Interaction of <tt>scope</tt> with the <tt>return</tt> Statement ===
  
A view annotated with <tt>scope</tt> cannot be returned from a function.
+
A value containing indirections and annotated with <tt>scope</tt> cannot be returned from a function.
  
 
<syntaxhighlight lang="D">
 
<syntaxhighlight lang="D">
 
class C { ... }
 
class C { ... }
scope C c;
 
return c;  // Error
 
  
scope int i;
+
C fun1() {
return i;  // Ok, i is not a view
+
    scope C c;
 +
    ...
 +
    return c;  // Error
 +
}
 +
 
 +
int fun2() {
 +
    scope int i;
 +
    ...
 +
    return i;  // Ok, i has no indirections
 +
}
  
scope int* p;
+
scope int* fun3() {
return p;  // Error
+
    scope int* p;
return p+1; // Error, nice try!
+
    return p;  // Error
return &*p; // Error, won't work either
+
    return p+1; // Error, nice try!
 +
    return &*p; // Error, won't work either
 +
}
  
ref int func(scope ref int r, scope out int s)
+
ref int func(scope ref int r, scope out int s, ref int t)
 
{
 
{
 
     return r; // Error
 
     return r; // Error
 
     return s; // Error, 'out' is treated like 'ref'
 
     return s; // Error, 'out' is treated like 'ref'
 +
    return t; // fine
 
}
 
}
 
</syntaxhighlight>
 
</syntaxhighlight>
Line 231: Line 304:
 
==== Inference ====
 
==== Inference ====
  
Scope is inferred for function parameters if not specified, under the same circumstances as <tt>pure</tt>, <tt>nothrow</tt>, <tt>@nogc</tt>
+
<tt>scope</tt> is inferred for function parameters if not specified, under the same circumstances as <tt>pure</tt>, <tt>nothrow</tt>, <tt>@nogc</tt>,
and safety are inferred. Scope is not inferred for virtual functions.
+
and <tt>@safe</tt> are inferred. Scope is not inferred for virtual functions.
  
 
==== Overloading ====
 
==== Overloading ====
  
Scope does not affect overloading. If it did, then whether a variable was scope or not would affect the code path, making
+
<tt>scope</tt> does not affect overloading. If it did, then whether a variable was scope or not would affect the code path, making
 
scope inference impractical. It also makes turning scope checking on/off impractical.
 
scope inference impractical. It also makes turning scope checking on/off impractical.
  
Line 246: Line 319:
 
scope T u; func(u); // Error, ambiguous
 
scope T u; func(u); // Error, ambiguous
 
</syntaxhighlight>
 
</syntaxhighlight>
 
  
 
==== Implicit Conversion of Function Pointers and Delegates ====
 
==== Implicit Conversion of Function Pointers and Delegates ====
Line 308: Line 380:
 
==== Escaping via Return ====
 
==== Escaping via Return ====
  
The simple cases of this are disallowed:
+
The simple cases of this are already disallowed prior to this DIP:
  
 
<syntaxhighlight lang="D">
 
<syntaxhighlight lang="D">
Line 393: Line 465:
 
further annotation.
 
further annotation.
  
==== Scope Ref ====
+
==== <tt>scope ref</tt> ====
  
The above solution is correct, but a bit restrictive. After all, func(t, u) could be returning
+
The above solution is correct, but a bit restrictive. After all, <tt>func(t, u)</tt> could be returning
a reference to non-local u, not local t, and so should work. To fix this, introduce the concept
+
a reference to non-local <tt>u</tt>, not local <tt>t</tt>, and so should work. To fix this, introduce the concept
 
of <tt>scope ref</tt>:
 
of <tt>scope ref</tt>:
  
Line 450: Line 522:
  
 
<tt>out</tt> parameters are treated like <tt>ref</tt> parameters when <tt>scope</tt> is applied.
 
<tt>out</tt> parameters are treated like <tt>ref</tt> parameters when <tt>scope</tt> is applied.
 
=== Expressions ===
 
 
The ''lifetime'' of an expression is either &infin; or the lifetime of a single variable. Which it is can be statically
 
deduced by looking at the type and AST of the expression.
 
 
The root cases are:
 
 
<table border=1 cellpadding=4 cellspacing=0>
 
<tr><th class="donthyphenate">'''root case'''</th><th class="donthyphenate">'''lifetime'''</th></tr>
 
<tr><td>address of variable v</td><td>lifetime(v)</td></tr>
 
<tr><td>v containing value with references</td><td>lifetime(v)</td></tr>
 
<tr><td>otherwise</td><td>&infin;</td></tr>
 
</table>
 
 
 
More complex expressions can be reduced to be one of the root cases:
 
 
<table border=1 cellpadding=4 cellspacing=0>
 
<tr><th class="donthyphenate">'''expression'''</th><th class="donthyphenate">'''lifetime'''</th></tr>
 
<tr><td><tt>&amp;(*e)</tt></td><td>lifetime(e)</td></tr>
 
<tr><td><tt>*(&e + integer)</tt></td><td>lifetime(e)</td></tr>
 
<tr><td><tt>*((e1? &amp; e2 : &e3) + integer)</tt></td><td>min(lifetime(e2), lifetime(e3))</td></tr>
 
<tr><td><tt>*e</tt></td><td>&infin;</td></tr>
 
<tr><td><tt>e1,e2</tt></td><td>lifetime(e2)</td></tr>
 
<tr><td><tt>e1 = e2</tt></td><td>lifetime(e1)</td></tr>
 
<tr><td><tt>e1 op= e2</tt></td><td>lifetime(e1)</td></tr>
 
<tr><td><tt>e1 ? e2 : e3</tt></td><td>min(lifetime(e2), lifetime(e3))</td></tr>
 
<tr><td><tt>ptr + integer</tt></td><td>lifetime(ptr)</td></tr>
 
<tr><td><tt>e1 op e2</tt></td><td>min(lifetime(e1), lifetime(e2))</td></tr>
 
<tr><td><tt>op e</tt></td><td>lifetime(e)</td></tr>
 
<tr><td><tt>e++</tt></td><td>lifetime(e)</td></tr>
 
<tr><td><tt>e--</tt></td><td>lifetime(e)</td></tr>
 
<tr><td><tt>cast(type) e</tt></td><td>lifetime(e)</td></tr>
 
<tr><td><tt>new</tt></td><td>&infin;</td></tr>
 
<tr><td><tt>e.field</tt></td><td>lifetime(e)</td></tr>
 
<tr><td><tt>(*e).field</tt></td><td>lifetime(*e)</td></tr>
 
<tr><td><tt>e.func(args)</tt></td><td>min(lifetime(e, args), &infin;)</td></tr>
 
<tr><td><tt>func(args)</tt></td><td>min(lifetime(non-scope-ref args), &infin;)</td></tr>
 
<tr><td><tt>e[]</tt></td><td>lifetime(e)</td></tr>
 
<tr><td><tt>e[i..j]</tt></td><td>lifetime(e)</td></tr>
 
<tr><td><tt>e[i]</tt></td><td>lifetime(*e)</td></tr>
 
<tr><td>''ArrayLiteral''</td><td>min(lifetime(args))</td></tr>
 
<tr><td>''ArrayLiteral[constant]''</td><td>lifetime(ArrayLiteral[constant])</td></tr>
 
</table>
 
  
 
=== Classes ===
 
=== Classes ===
Line 528: Line 555:
 
instance on the stack. Fortunately, this can work with this new proposal, with an optimization that recognizes
 
instance on the stack. Fortunately, this can work with this new proposal, with an optimization that recognizes
 
that if a new class is unique, and assigned to a scope variable, then that instance can be placed on the stack.
 
that if a new class is unique, and assigned to a scope variable, then that instance can be placed on the stack.
 +
 +
=== Major Idioms Enabled ===
 +
 +
====Identity function====
 +
 +
<syntaxhighlight lang=D>
 +
T identity(T)(T x) { return x; } // overload 1
 +
ref T identity(T)(ref T x) { return x; } // overload 2
 +
</syntaxhighlight>
 +
 +
Even if the body of <tt>identity</tt> weren't available, the compiler can infer it is escaping its parameter.
 +
 +
If <tt>identity</tt> is applied to a <tt>scope</tt> variable (including <tt>scope ref</tt> parameters), then overload 2 is not a match because per the rules <tt>scope ref</tt> cannot bind to <tt>ref</tt>. Therefore, overload 1 will match. Example:
 +
 +
<syntaxhighlight lang=D>
 +
void fun(int a, ref int b, scope ref int c) {
 +
    auto x = identity(42); // rvalue, overload 1 matches
 +
    auto y = identity(a); // lvalue, overload 2 matches
 +
    auto z = identity(c); // scope ref value, overload 1 matches
 +
}
 +
</syntaxhighlight>
 +
 +
In fact both overloads can be integrated in a single signature:
 +
 +
<syntaxhighlight lang=D>
 +
auto ref T identity(T)(auto ref T x) { return x; }
 +
</syntaxhighlight>
 +
 +
====Owning Containers====
 +
 +
Containers that own their data will be able to give access to elements by <tt>scope ref</tt>. The compiler ensures that the references returned never outlive the container. Therefore, the container can deallocate its payload (subject to control of multiple container copies, e.g. by means of reference counting). A basic outline of a reference counted slice is shown below:
 +
 +
<syntaxhighlight lang=D>
 +
@safe struct RefCountedSlice(T) {
 +
    private T[] payload;
 +
    private uint* count;
 +
    this(size_t initialSize) {
 +
        payload = new T[initialSize];
 +
        count = new size_t;
 +
        *count = 1;
 +
    }
 +
    this(this) {
 +
        if (count) ++*count;
 +
    }
 +
    void opAssign(Container rhs) {
 +
        this.__dtor();
 +
        payload = rhs.payload;
 +
        count = rhs.count;
 +
        ++*count;
 +
    }
 +
    // Interesting fact #1: destructor can be @trusted
 +
    @trusted ~this()  {
 +
        if (count && !--*count) {
 +
            delete payload;
 +
            delete refs;
 +
        }
 +
    }
 +
    // Interesting fact #2: references to internals can be given away
 +
    scope ref T opIndex(size_t i) {
 +
        return payload[i];
 +
    }
 +
    ...
 +
}
 +
</syntaxhighlight>
 +
 +
<tt>RefCountedSlice</tt> mimics the semantics of <tt>T[]</tt> with the notable difference that the payload is deallocated automatically when it is no longer used. It is usable in <tt>@safe</tt> code because the compiler ensures statically a <tt>ref</tt> to an element may never outlive the slice.
  
 
=== Implementation Plan ===
 
=== Implementation Plan ===
 
 
Turning this on may cause significant breakage, and may also be found to be an unworkable design. Therefore, implementation stages will be:
 
Turning this on may cause significant breakage, and may also be found to be an unworkable design. Therefore, implementation stages will be:
  
Line 537: Line 629:
 
* replace warnings with deprecation messages
 
* replace warnings with deprecation messages
 
* replace deprecations with errors
 
* replace deprecations with errors
 +
 +
 +
[[Category: DIP]]

Latest revision as of 19:53, 1 September 2015

Title: Implement scope for escape proof references
DIP: 69
Version: 1
Status: Draft
Created: 2014-12-04
Last Modified: 2014-12-04
Authors: Marc Schütz, deadalnix, Andrei Alexandrescu and Walter Bright
Links: Proposals Discussions


Abstract

A garbage collected language is inherently memory safe. References to data can be passed around without concern for ownership, lifetimes, etc. But this runs into difficulty when combined with other sorts of memory management, like stack allocation, malloc/free allocation, reference counting, etc.

Knowing when the lifetime of a reference is over is critical for safely implementing memory management schemes other than tracing garbage collection. It is also critical for the performance of reference counting systems, as it will expose opportunities for elision of the inc/dec operations.

scope provides a mechanism to guarantee that a reference cannot escape lexical scope.

Benefits

  • References to stack variables can no longer escape.
  • 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.
  • @system code like std.internal.scopebuffer can be made @safe.
  • Reference counting systems need not adjust the count when passing references that do not escape.
  • Better self-documentation of encapsulation.

Definitions

Visibility vs. lifetime

For each value v within a program we define the notion of lexical visibility denoted as visibility(v), akin to the lexical extent through which the value can be accessed.

  • For an rvalue, the visibility is the expression within it is used.
  • For a named variable in a scope, the visibility is the lexical scope of the variable per the language rules.
  • For a module-level variable, visibility is considered infinite. Notation: visibility(v) = ∞.

Due to language scoping rules, visibilities cannot partially intersect or "cross": for any two values, either they are not simultaneously visible at all, or one's visibility is included within the other's. We define a partial order among visibilities: visibility(v1) <= visibility(v2) if v2 is visible through all portions of program when v1 is visible (including the case where both values have infinite visibilities). If two variables have disjoint visibilities, they are unordered.

We also define lifetime for each value, which is the extent during which a value can be safely used.

  • For types without indirections such as int, visibility and lifetime are equal for rvalues and lvalues.
  • For all global and static variables, lifetime is infinite.
  • For values allocated on the garbage collected heap, lifetime is infinite whilst visibility is dependent on the references in the program bound to those values.
  • For an unrestricted pointer, visibility is dictated by the usual lexical scope rules. Lifetime, however is dictated by the lifetime of the data to which the pointer points to.

Examples:

void fun1() {
    int x; // starting here, x becomes visible and also starts "living"
    int y = x + 42; // lifetime(42) and visibility(42) last through the initialization expression
    ...
   // lifetime(y) and visibility(y) end here, just before those of x
   // lifetime(x) and visibility(x) end here
}

void fun2() {
    int * p; // visibility(p) occurs from here through the end of the function
    // at this point lifetime(p) is infinite because it is null and lifetime(null) is infinite
    if (...) {
        int x;
        p = &x; // lifetime(p) is now equal to lifetime(x)
    }
    // here lifetime(p) may have ended but p is still visible
}

If a value is visible but its lifetime has ended, the program is in a dangerous, albeit not necessarily incorrect state. The program becomes undefined if the value of which lifetime has ended is actually used.

This proposal ensures statically that variables in @safe code with the scope storage class have a lifetime that includes their visibility, so they are safe to use at all times.

By consequence of the above, inside a function:

  • Parameters passed by ref or out are conservatively assumed to have lifetime somewhere in the caller's scope;
  • Parameters passed by value have shorter lifetime than those passed by passed by ref/out, but longer than any locals defined by the function. The lifetimes of by-value parameters are ordered lexically.

Algebra of Lifetimes

Certain expressions create values of which lifetime is in relationship with the participating value lifetimes, as follows:

expressionlifetimenotes
&elifetime(e)
&*elifetime(e)
e + integerlifetime(e)Applies only when e is a pointer type
e - integerlifetime(e)Applies only when e is a pointer type
*elifetime is not transitive
e1, e2lifetime(e2)
e1 = e2lifetime(e1)
e1 op= e2lifetime(e1)
e1 ? e2 : e3min(lifetime(e2), lifetime(e3))
e++lifetime(e)Applies only when e is a pointer type. This has academic value only because pointer increment is disallowed in @safe code.
e--lifetime(e)Applies only when e is a pointer type. This has academic value only because pointer decrement is disallowed in @safe code.
cast(T) elifetime(e)Applies only when both T and e have pointer type.
newAllocates on the GC heap.
e.fieldlifetime(e)
e.func(args)See section dedicated to discussing methods.
func(args)See section dedicated to discussing functions.
e[]lifetime(e)
e[i..j]lifetime(e)
&e[i]lifetime(e)
e[i]
ArrayLiteralArray literals are allocated on the GC heap
ArrayLiteral[constant]

Aggregates

The following sections define scope working on primitive types (such as int) and pointers thereof (such as int*). This is without loss of generality because aggregates can be handled by decomposition as follows:

  • From a lifetime analysis viewpoint, a struct is considered a juxtaposition of its direct members. Passing a struct by value into a function is equivalent to passing each of its members by value. Passing a struct by ref is equivalent to passing each of its members by ref. Finally, passing a pointer to a struct is analyzed as passing a pointer to each of its members. Example:
struct A { int x; float y; }
void fun(A a); // analyzed similarly to fun(int x, float y);
void gun(ref A a); // analyzed similarly to gun(ref int x, ref float y);
void hun(A* a); // analyzed similarly to hun(int* x, float* y);
  • Lifetimes of statically-sized arrays T[n] is analyzed as if the array were a struct with n fields, each of type T.
  • Lifetimes of built-in dynamically-sized slices T[] are analyzed as structs with two fields, one of type T* and the other of type size_t.
  • Analysis of lifetimes of class types is similar to analysis of pointers to struct types.
  • For struct members of aggregate type, decomposition may continue transitively.

Fundamentals of scope

The scope storage class ensures that the lifetime of a pointer/reference is a shorter of the lifetime of the referred object. Dereferencing through a scope variable is guaranteed to be safe.

scope is a storage class, and affects declarations. It is not a type qualifier. There is no change to existing scope grammar. It fits in the grammar as a storage class.

scope affects:

  • local variables allocated on the stack
  • function parameters
  • non-static member functions (applying to the this implicit parameter)
  • delegates (applying to their implicit environment)
  • return value of functions

It is ignored for other declarations. It is ignored for declarations that have no indirections.

scope enum e = 3;  // ignored, no indirections
scope int i;       // ignored no indirections

The scope storage class affects variables according to these rules:

  1. A scope variable can only be initialized and assigned from values that have lifetimes longer than the variable's lifetime. (As a consequence a scope variable can only be assigned to scope variables that have shorter lifetime.)
  2. A variable is inferred to be scope if it is initialized with a value that has a non-∞ lifetime.
  3. A scope variable cannot be initialized with the address of a scope variable.
  4. A scope ref parameter can be initialized with another scope ref parameter—scope ref is idempotent.

Examples for each rule:

int global_var;
int* global_ptr;
 
void bar(scope int* input);
 
void fun1() {
    scope int* a = &global_var; // OK per rule 1, lifetime(&global_var) > lifetime(a)
    a = &global_var;       // OK per rule 1, lifetime(&global_var) > lifetime(a)
    int b;
    a = &b; // Disallowed per rule 1, lifetime(&b) < lifetime(a)
    scope c = &b; // OK per rule 1, lifetime(&b) > lifetime(c)
    int* b;
    a = b; // Disallowed per rule 1, lifetime(b) < lifetime(a)
}

void fun2() {
    auto a = &global_var; // OK, b is a regular int*
    int b;
    auto c = &b; // Per rule 2, c has scope storage class 
}

void fun3(scope int * p1) {
    scope int** p2 = &p1; // Disallowed per rule 3
    scope int* p3;
    scope int** p4 = &p3; // Disallowed per rule 3
}

void fun4(scope int * p1) {
    bar(p1); // OK per rule 4
}

A few more examples combining the rules:

int global_var;
int* global_ptr;
 
void bar(scope int* input);
 
void foo() {
    scope int* a;
    a = &global_var;       // Ok, `global_var` has a greater lifetime than `a`
    scope b = &global_var; // Ok, type deduction
    int c;
 
    if(...) {
        scope x = a;       // Ok, copy of reference,`x` has shorter lifetime than `a`
        scope y = &c;      // Ok, lifetime(y) < lifetime(& c)
        int z;
        b = &z;            // Error, `b` will outlive `z`
        int* d = a;        // Ok: d is inferred to be `scope`
    }
 
    bar(a);                // Ok, scoped pointer is passed to scoped parameter
    bar(&c);               // Ok, lifetime(parameter input) < lifetime(c)
    int* e;
    e = &c;                // Error, lifetime(e's view) is &infin; and is greater than lifetime(c)
    a = e;                 // Ok, lifetime(a) < lifetime(e)
    scope int** f = &a;    // Error, rule 4
    scope int** h = &e;    // Ok
    int* j = *h;           // Ok, scope is not transitive
}

void abc() {
    scope int* a;
    int* b;
    scope ref int* c = a;  // Error, rule 5
    scope ref int* d = b;  // Ok
    int* i = a;            // Ok, scope is inferred for i
    global_ptr = d;        // Error, lifetime(d) < lifetime(global_ptr)
    global_ptr = i;        // Error, lifetime(i) < lifetime(global_ptr)
    int* j;
    global_ptr = j;        // Ok, j is not scope
}

Interaction of scope with the return Statement

A value containing indirections and annotated with scope cannot be returned from a function.

class C { ... }

C fun1() {
    scope C c;
    ...
    return c;   // Error
}

int fun2() {
    scope int i;
    ...
    return i;   // Ok, i has no indirections
}

scope int* fun3() {
    scope int* p;
    return p;   // Error
    return p+1; // Error, nice try!
    return &*p; // Error, won't work either
}

ref int func(scope ref int r, scope out int s, ref int t)
{
    return r; // Error
    return s; // Error, 'out' is treated like 'ref'
    return t; // fine
}

Functions

Inference

scope is inferred for function parameters if not specified, under the same circumstances as pure, nothrow, @nogc, and @safe are inferred. Scope is not inferred for virtual functions.

Overloading

scope does not affect overloading. If it did, then whether a variable was scope or not would affect the code path, making scope inference impractical. It also makes turning scope checking on/off impractical.

T func(scope ref T);
T func(ref T);

T t; func(t); // Error, ambiguous
scope T u; func(u); // Error, ambiguous

Implicit Conversion of Function Pointers and Delegates

scope can be added to parameters, but not removed.

alias int function(ref T) fp_t;
alias int function(scope ref T) fps_t;

int foo(ref T);
int bar(scope ref T);

fp_t fp = &bar;   // Ok, scope behavior is subset of non-scope
fps_t fp = &foo;  // Error, fps_t demands scope behavior

Inheritance

Overriding functions inherit any scope annotations from their antecedents. Scope is covariant, meaning it can be added to overriding functions.

class C
{
    int foo(ref T);
    int bar(scope ref T);
}

class D : C
{
    override int foo(scope ref T); // Ok, can add scope
    override int bar(ref T);       // Error, cannot remove scope
}

Mangling

Scope will require additional mangling, as it affects the interface of the function. In cases where scope is ignored, it does not contribute to the mangling. Scope parameters will be mangled with ???.

Nested Functions

Nested functions have more objects available than just their arguments:

ref T foo() {
  T t;
  ref T func() { return t; }
  return func();  // disallowed
}

Nested functions are analyzed as if each variable accessed outside of its scope was passed as a ref parameter. All parameters have scope inferred from how they are used in the function body.


Ref

Escaping via Return

The simple cases of this are already disallowed prior to this DIP:

T* func(T t) {
  T u;
  return &t; // Error: escaping reference to local t
  return &u; // Error: escaping reference to local u
}

But are easily circumvented:

T* func(T t) {
  T* p = &t;
  return p;  // no error detected
}

@safe currently deals with this by preventing taking the address of a local:

T* func(T t) @safe {
  T* p = &t; // Error: cannot take address of parameter t in @safe function func
  return p;
}

This is restrictive. The ref storage class was introduced which defines a special purpose pointer. ref can only appear in certain contexts, in particular function parameters and returns, only applies to declarations, cannot be stored, and cannot be incremented.

ref T func(T t) @safe {
  return t; // Error: escaping reference to local variable t
}

Ref can be passed down to functions:

void func(ref T t) @safe;
void bar(ref T t) @safe {
   func(t); // ok
}

But the following idiom is far too useful to be disallowed:

ref T func(ref T t) {
  return t; // ok
}

And if it is misused it can result in stack corruption:

ref T foo() {
  T t;
  return func(t); // currently, no error detected, despite returning pointer to t
}

The:

return func(t);

case is detected by all of the following conditions being true:


  • foo() returns by reference
  • func() returns by reference
  • func() has one or more parameters that are by reference
  • 1 or more of the arguments to those parameters are stack objects local to foo()
  • Those arguments can be @safe-ly converted from the parameter to the return type.

For example, if the return type is larger than the parameter type, the return type cannot be a reference to the argument. If the return type is a pointer, and the parameter type is a size_t, it cannot be a reference to the argument. The larger a list of these cases can be made, the more code will pass @safe checks without requiring further annotation.

scope ref

The above solution is correct, but a bit restrictive. After all, func(t, u) could be returning a reference to non-local u, not local t, and so should work. To fix this, introduce the concept of scope ref:

ref T func(scope ref T t, ref T u) {
  return t; // Error: escaping scope ref t
  return u; // ok
}

Scope means that the ref is guaranteed not to escape.

T u;
ref T foo() @safe {
  T t;
  return func(t, u); // Ok, u is not local
  return func(u, t); // Error: escaping scope ref t
}

This minimizes the number of scope annotations required.

Scope Function Returns

scope can be applied to function return values (even though it is not a type qualifier). It must be applied to the left of the declaration, in the same way ref is:


int* foo() scope;     // applies to 'this' reference
scope: int* foo();    // applies to 'this' reference
scope { int* foo(); } // applies to 'this' reference
scope int* foo();     // applies to return value

The lifetime of a scope return value is the lifetime of an rvalue. It may not be copied in a way that extends its life.

int* bar(scope int*);
scope int* foo();
...
return foo();         // Error, lifetime(return) > lifetime(foo())
int* p = foo();       // Error, lifetime(p) is &infin;
bar(foo());           // Ok, lifetime(foo()) > lifetime(bar())
scope int* q = foo(); // error, lifetime(q) > lifetime(rvalue)

This enables scope return values to be safely chained from function to function; in particular it also allows a ref counted struct to safely expose a reference to its wrapped type.

Out Parameters

out parameters are treated like ref parameters when scope is applied.

Classes

Scope class semantics are equivalent to a pointer to a struct.

Static Arrays

Scope static array semantics are equivalent to a scope struct:

T[3] a;
struct A { T t0, t1, t2; } A a;

@safe

Errors for scope violations are only reported in @safe code.

Breaking Existing Code

Some code will no longer work. Although inference will take care of a lot of cases, there are still some that will fail.

int i,j;
int* p = &i;  // Ok, scope is inferred for p
int* q;
q = &i;   // Error: too late to infer scope for q

Currently, scope is ignored except that a new class use to initialize a scope variable allocates the class instance on the stack. Fortunately, this can work with this new proposal, with an optimization that recognizes that if a new class is unique, and assigned to a scope variable, then that instance can be placed on the stack.

Major Idioms Enabled

Identity function

T identity(T)(T x) { return x; } // overload 1
ref T identity(T)(ref T x) { return x; } // overload 2

Even if the body of identity weren't available, the compiler can infer it is escaping its parameter.

If identity is applied to a scope variable (including scope ref parameters), then overload 2 is not a match because per the rules scope ref cannot bind to ref. Therefore, overload 1 will match. Example:

void fun(int a, ref int b, scope ref int c) {
    auto x = identity(42); // rvalue, overload 1 matches
    auto y = identity(a); // lvalue, overload 2 matches
    auto z = identity(c); // scope ref value, overload 1 matches
}

In fact both overloads can be integrated in a single signature:

auto ref T identity(T)(auto ref T x) { return x; }

Owning Containers

Containers that own their data will be able to give access to elements by scope ref. The compiler ensures that the references returned never outlive the container. Therefore, the container can deallocate its payload (subject to control of multiple container copies, e.g. by means of reference counting). A basic outline of a reference counted slice is shown below:

@safe struct RefCountedSlice(T) {
    private T[] payload;
    private uint* count;
    this(size_t initialSize) {
        payload = new T[initialSize];
        count = new size_t;
        *count = 1;
    }
    this(this) {
        if (count) ++*count;
    }
    void opAssign(Container rhs) {
        this.__dtor();
        payload = rhs.payload;
        count = rhs.count;
        ++*count;
    }
    // Interesting fact #1: destructor can be @trusted
    @trusted ~this()  {
        if (count && !--*count) {
            delete payload;
            delete refs;
        }
    }
    // Interesting fact #2: references to internals can be given away
    scope ref T opIndex(size_t i) {
        return payload[i];
    }
    ...
}

RefCountedSlice mimics the semantics of T[] with the notable difference that the payload is deallocated automatically when it is no longer used. It is usable in @safe code because the compiler ensures statically a ref to an element may never outlive the slice.

Implementation Plan

Turning this on may cause significant breakage, and may also be found to be an unworkable design. Therefore, implementation stages will be:

  • enable new behavior with a compiler switch -scope
  • remove -scope, issue warning when errors are detected
  • replace warnings with deprecation messages
  • replace deprecations with errors