scope for array parameters
Alex Rønne Petersen
alex at lycus.org
Tue Sep 4 13:18:09 PDT 2012
On 04-09-2012 22:13, Benjamin Thaut wrote:
> To make functions definitions more expressive and give the compiler more
> information to optimize I propose to make array function parameters
> extendable with 'scope' such as follows:
>
> size_t find(scope float[] haystack, float needle){ ... }
>
> This would give the compiler the information that the array haystack
> only has to be valid as long as the scope of the function find is valid.
> As soon as the function scope is left, the array does not need to be
> valid any more. This would greatly help when programming without a GC to
> know, if the array one passes to the function will be saved internally
> or if it only needs to be valid for the duration in which the function
> is executed. Also it would allow the compiler to optimize array literals
> such as:
>
> find([1,2,3,4,5], 5)
>
> The function call would not allocate on the heap, but would allocate the
> array literal on the stack, as the compiler knows that is only has to be
> valid for the scope of find.
>
> Passing a scope array to another function which does not have the scope
> annotation should be an error. Assining a a scope array to a non local
> variable should be an error too. You could go really fancy on checking
> scoped function parameters but for a start simple rules should be enough.
>
> The same could be done with references and pointers. The purpose of this
> would be to allow the compiler to do more static checking on the usage
> of the passed arguments and make the function definitions contain
> information if the passed references will be saved internally or not.
>
> I do understand that non-gc programming is not considered often for the
> D-Programming Language, but it would be nice if this idea does not get
> ignored completely.
>
> What do you think about this idea?
>
> Kind Regards
> Benjamin Thaut
This is already what scope does today. See http://dlang.org/function.html:
"references in the parameter cannot be escaped (e.g. assigned to a
global variable)"
It's just that the compiler doesn't actually enforce it fully.
--
Alex Rønne Petersen
alex at lycus.org
http://lycus.org
More information about the Digitalmars-d
mailing list