Confusing "Error: only one index allowed to index [...]"
Bastiaan Veelo
Bastiaan at Veelo.net
Wed Jan 2 20:20:12 UTC 2019
I have been a bit confused by the fact that indexing syntax is
opposite for two similar constructs, and that their error
messages are very similar but misleading. The syntax is
unfortunate but not easily fixable, my question is: Could and
should we fix the error messages, and how.
The first case:
```
int[3][3] matrix;
matrix[1,1] = 7; // Error: only one index allowed to index
`int[3][3]`
matrix[1][1] = 7; // OK
writeln(matrix[1]); // OK
```
What I find misleading is "only one index allowed" because
`[1][1]` are two indices and clearly allowed. The message should
neither be "only two indices allowed" as the last line
illustrates. Fact is that `[1,1]` is the syntax applicable for
when `opIndex` or `opIndexAssign` is defined, which isn't in this
case (and can't be). So, maybe a better message would be: "no
opIndexAssign defined for `int[3][3]`. Did you mean `[1][1]`?"
Now an example when `opIndexAssign` is defined (reduced):
```
struct A
{
int[] _payload;
alias _payload this;
int opIndexAssign(int value, size_t i1, size_t i2) {return
value;}
}
A a;
a[1,1] = 7; // OK
a[1][1] = 7; // Error: only one index allowed to index `int`
```
Contrary to the first example, here `[1,1]` is the correct
syntax. If instead mistakenly `[1][1]` is used, by means of the
alias, the indices apply to `_payload`, which of course just
takes one index. Ideally (but I imagine this would be difficult
to implement) the compiler would recognise the presence of
`opIndex` or `opIndexAssign` and ask "... Did you mean`[1,1]`?"
Still, I think there is an error in the current message; it
should either be "only one index allowed to index `int[]`"
(notice the slice) or "cannot index `int`" (when the first `[1]`
selects an element in `_payload` and the second `[1]` tries to
index that).
Is it appropriate and feasible to change these messages to make
it more obvious that the wrong syntax is being used?
(I know how to file issues, just wanted to air this here first.)
Thanks,
Bastiaan.
More information about the Digitalmars-d
mailing list