www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 18788] New: static arrays with a length specified at runtime

https://issues.dlang.org/show_bug.cgi?id=18788

          Issue ID: 18788
           Summary: static arrays with a length specified at runtime
                    should dynamically allocate on the stack
           Product: D
           Version: D2
          Hardware: All
                OS: All
            Status: NEW
          Severity: enhancement
          Priority: P1
         Component: dmd
          Assignee: nobody puremagic.com
          Reporter: slavo5150 yahoo.com

Consider the following contrived example in C:

---main.c
#include <stdio.h>
#include <string.h>

int writeln(char* s)
{
    size_t len = strlen(s);
    size_t newLen = len + 1;
    char buf[newLen + 1];     // dynamically allocated on the stack
    memcpy(buf, s, len);
    buf[len] = '\n';
    buf[newLen] = '\0';
    fprintf(stdout, buf);
}

int main()
{
    writeln("Hello, World!");
    return 0;
}

I think D should do something similar with static arrays, but currently the
following fails to compile:

---main.d
import core.stdc.string;
import core.stdc.stdio;

void writeln(string s)
{
    size_t len = s.length;
    size_t newLen = len + 1;
    char[newLen + 1] buf;     // Error: variable newLen cannot be read at
compile time
    memcpy(buf.ptr, s.ptr, len);
    buf[len] = '\n';
    buf[newLen] = '\0';
    fprintf(stdout, buf.ptr);
}

int main()
{
    writeln("Hello, World!");
    return 0;
}

Templates or mixins may be able to be used to workaround this limitation, but
would ultimately result in code bloat if used extensively, and one of the use
cases for this is in the domain of resource constrained microcontrollers.

A possible implementation would be to have an alloca-equivalent druntime hook
with hopefully a much better name, and have the compiler generate a call to it
when appropriate.  The d runtime hook could then forward to the platform's
`alloca`, if one exists, or a custom D implementation could be implemented and
optimized for each platform.

Perhaps `scope` could also even play an interesting roll here.

--
Apr 21 2018