Did the implicit conversion from special slice expression to static array ever work?
Quirin Schroll
qs.il.paperinik at gmail.com
Thu Sep 22 10:50:28 UTC 2022
In the [Expression § Slice Conversion to Static
Array](https://dlang.org/spec/expression.html#slice_to_static_array), at the end of the section, it says:
> Certain other forms of slice expression can be implicitly
> converted to a static array when the slice length can be known
> at compile-time.
And you find this table (assuming `e` is an expression that
contains no side effects and `a` and `b` are compile-time known
integers):
| Form | The length calculated at compile time |
|-------------------|---------------------------------------|
| `arr[]` | `arr.length` if known at compile-time |
| `arr[a .. b]` | `b - a` |
| `arr[e-a .. e]` | `a` |
| `arr[e .. e+b]` | `b` |
| `arr[e-a .. e+b]` | `a + b` |
| `arr[e+a .. e+b]` | `b - a` if `a` ≤ `b` |
| `arr[e-a .. e-b]` | `a - b` if `a` ≥ `b` |
Has it ever worked?
Expanding on the code example
```d
int[] da = [1, 2, 3];
int i = da[0]; // runtime variable
int[2] sa2 = da[i .. i + 2];
assert(sa2 == [2, 3]);
// my tests
int[1] sa1 = da[i .. i + 2]; // core.exception.RangeError
int[3] sa3 = da[i .. i + 2]; // core.exception.RangeError
```
It seems like there is not attempt made to check the lengths at
compile-time. The specification in a sense promised me a compile
error here.
On the other hand, I tried with this code:
```d
void f(T, size_t n)(T[n] array) { }
void main()
{
int[] xs = [1,2,3,4,5,6];
size_t i = 2;
f(xs[i .. i+3]); // compile error
}
```
It did not work with any compiler supported by
[run.dlang.io](https://run.dlang.io/) (LDC and any DMD since
2.064, including beta and nightly).
If it does work in other contexts, either this feature should be
removed (it does not work consistently) or be improved so that it
lives up to its promise. If nothing like that is implemented, the
section should be removed from the spec.
More information about the Digitalmars-d
mailing list