Confusing "Error: only one index allowed to index [...]"
Steven Schveighoffer
schveiguy at gmail.com
Wed Jan 2 22:08:18 UTC 2019
On 1/2/19 3:20 PM, Bastiaan Veelo wrote:
> 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]`?"
I think this would be a good addition, and definitely possible, since
it's a builtin. For custom types, I'm not sure it would work, but you
probably don't get the same error.
>
> 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).
In general, the fact that the compiler jumps right to trying the alias
this for certain things, and ignores the original type is a problem. It
comes up again and again. I don't think it's simply an indexing problem.
Remove the alias this and you get a MUCH better error:
Error: no [] operator overload for type A
In fact, you could say, for the first issue: "No [,] operator overload
for type int[3][3]"
-Steve
More information about the Digitalmars-d
mailing list