D needs a type expression syntax
Quirin Schroll
qs.il.paperinik at gmail.com
Wed May 10 14:12:33 UTC 2023
On Tuesday, 9 May 2023 at 18:13:09 UTC, Tim wrote:
> On Tuesday, 9 May 2023 at 17:15:41 UTC, Quirin Schroll wrote:
>> I have found one issue, but it falls under the category of
>> Nobody Writes Such Code:
>> If a type `T` has a `static` indexing operator (`opIndex` or
>> similar), then the token sequence `T[]` can denote a
>> [`Type`](https://dlang.org/spec/type.html#Type) or an
>> [`Expression`](https://dlang.org/spec/expression.html#Expression). If that token sequence is itself in parentheses and not prefixed by a [`TypeCtor`](https://dlang.org/spec/type.html#TypeCtor), then it currently cannot parse as a [`Type`](https://dlang.org/spec/type.html#Type), but with the proposed changes, it could, and in some circumstances, that would make valid working code change meaning.
>
> There are some other examples with similar problems:
>
> The code `X*[1]` could be both an expression and a type. As an
> expression `X` would need to implement `opBinary` for
> multiplication. As a type it would be an array to a pointer to
> `X`.
To parse as a type, `X` *must* be a type. Therefore, to a type or
expression depending on what to parse, `X` *must* be a type.
To parse as an expression `X` it *must* be an aggregate type has
a `static` member function template `opBinary` that can be
instantiated as `opBinary!"*"` and called with `[1]`. It must be
`static` because `X` must parse as a type if `X` is unambiguously
a type or an expression. (Phrased in reverse, if `X` parses as an
expression, but never as a type, then `X*[1]` cannot parse as a
type.) If `X` is ambiguous itself, you just shift the problem
down one layer.
> The code `X*[0][0]` could also be both. As an expression it
> would multiply `X` with `[0][0]`, which is `0`. As a type it
> would be an array of an array of a pointer to X. This example
> does not need operator overloading.
>
> A more complex example also uses `*` as a pointer dereference:
> `X**[Y][0]`
> This could be a type, if `X` is a type and `Y` is also a type
> or evaluates to an integer.
> If `X` is an integer and `Y` is a pointer to an integer, then
> it would be a valid expression.
To change meaning silently, `X` would have to be an aggregate
type that implements `opBinary` as a `static` function. This is
really important because Nobody Writes Such Code.
I haven’t been able to come up with an example that necessitates
a `static` operator function.
More information about the Digitalmars-d
mailing list