Array literals' default type

Steven Schveighoffer schveiguy at yahoo.com
Fri Oct 9 07:14:03 PDT 2009


On Fri, 09 Oct 2009 09:27:01 -0400, Don <nospam at nospam.com> wrote:

> Steven Schveighoffer wrote:
>> On Fri, 09 Oct 2009 08:34:31 -0400, Don <nospam at nospam.com> wrote:
>>
>>>
>>> I don't understand why runtime-determined array literals even exist.
>>> They're not literals!!!
>>> They cause no end of trouble. IMHO we'd be *much* better off without  
>>> them.
>>  I don't agree.  Here is a runtime decided array literal:
>>  void foo(int a, int b, int c)
>> {
>> auto x = [a, b, c];
>> }
>>  The alternatives are:
>
>> // template function
>>  auto x = createArray(a, b, c);
>>  // mixin?
>>  Although the template function looks nice, it adds bloat.
>
> There's no bloat. You just need a type-safe variadic.
> T[] createArray(T)(T[] args...);
>
> One function per type. That's the best you're ever going to do with  
> run-time construction anyway.
> Actually, there's horrific bloat present right now. Look at the code  
> generated when you use an array literal.

If you have a function that takes a typesafe variadic array, what is the  
compiler going to do to pass that data into the function?  Push it on the  
stack, call a function, and then the function is going to do the same  
thing a literal would do, reading the data off the stack?  How is that not  
worse than an array literal generating code to build an array?  Not to  
mention the added symbol bloat.

Generated code isn't bloat if it's the minimal work that has to be done to  
get what you want.

>>  On top of that, what if a, b, and c are runtime decide, then during  
>> development, or with a new compiler, they can now be CTFE decided?  Now  
>> you are calling some function when they *could* be in a literal.
>
> This is exactly the problem.
> They should ALWAYS require CTFE evaluation.
>
> EG:
> immutable(double)[] tableOfSines = [ sin(0.0), sin(PI/4), sin(PI/2),  
> sin(3*PI/4), sin(1)];
>
> Obviously, these values should be be compile-time evaluated. But how  
> does the compiler know that? It can't.
> Right now, this is done at run-time.

I'm not extremely well-versed in what triggers CTFE, but it seems logical  
to me that the compiler can determine that it can be evaluated at  
compile-time, assuming sin is marked as pure (or maybe even if it isn't).   
What am I missing?

>
> Runtime array creation is a prime candidate for moving from language to  
> libraries.

It is a solution, but I think the better solution is you just write what  
you want and the compiler figures out the best move.  Whether it's heap  
allocated or not, created at runtime or not, is an implementation detail I  
don't think the user needs to worry about.

Come to think of it, the same thing goes for static initializers.  What a  
pain it is to do:

int x;

static this()
{
   x = foo();
}

instead of just

int x = foo();

-Steve



More information about the Digitalmars-d mailing list