Bug 20433 – Don't complain about implicit cast when an explicit cast would also be in error

Status
RESOLVED
Resolution
INVALID
Severity
trivial
Priority
P1
Component
dmd
Product
D
Version
D2
Platform
x86_64
OS
Linux
Creation time
2019-12-05T22:59:19Z
Last change time
2020-07-15T03:47:19Z
Assigned to
No Owner
Creator
mipri

Comments

Comment #0 by mipri — 2019-12-05T22:59:19Z
Consider: struct Thing { int x; } void main() { Thing a = [1]; } // Error: cannot implicitly convert expression [1] of type int[] to Thing The error message suggests that the implicitness of the conversion is the problem. However, this also fails: struct Thing { int x; } void main() { Thing a = cast(Thing) [1]; } // Error: cannot cast expression [1] of type int[] to Thing So I suggest, as a trivial enhancement to dmd's error messages, that 'implicitly' be dropped from the first error when an explicit cast would also fail. The error messages would still not be the same ('convert' vs. 'cast'), which might help the reader find the error in an expression with both implicit conversions and explicit casts.
Comment #1 by razvan.nitu1305 — 2019-12-17T14:12:38Z
I think that the error messages are fine. When someone sees "cannot implicitly convert expression [1] of type int[] to Thing", I would argue that the first think that comes to mind is "Holy Crap, I tried to put an array of ints into a Thing type, the correct thing to do is Thing a = Thing(1);". Let's just assume that my supposition is false and the majority of people think "oh, it wants me to explicitly cast the int array to a Thing" (?!?!?!), then if you explicitly cast it you get an error message that it is impossible. Now you are left with no other option than to try instantiating a Thing with a Thing (which is the correct behavior). As for the situation with both implicit conversions and casts: if you have a situation where both fail, the compiler will highlight one at a time, so your scenario is not possible. Example: struct Thing { int x; } struct A {} void main() { A a = cast(Thing) [1]; } Error: cannot cast expression [1] of type int[] to Thing This behavior is fine and I suggest we close as this INVALID.