Issue 24870 - cast() ignore when the dot operator is used
Summary: cast() ignore when the dot operator is used
Status: NEW
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D2
Hardware: All All
: P1 normal
Assignee: No Owner
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2024-11-21 02:14 UTC by Jonathan M Davis
Modified: 2024-11-21 02:26 UTC (History)
1 user (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description Jonathan M Davis 2024-11-21 02:14:30 UTC
This code

---
void main()
{
    const s = S(42);
    T* ptr = cast() s.t;
}

struct S
{
    T* t;

    this(int i)
    {
        t = new T(42);
    }
}

struct T
{
    int i;
}
---

fails to compile:

---
q.d(4): Error: cannot implicitly convert expression `s.t` of type `const(T)*` to `T*`
---

It's exactly what would happen if the cast() were not there. If I change the offending line to

---
    T* ptr = (cast() s).t;
---

to force the cast to be on s, then the code compiles. So, it would appear that without parens, the cast() applies to t (which is what I would expect), and putting the parens around the entire expression has the same result as having none:

---
    T* ptr = (cast() s.t);
---

which is also what I would expect. However, in this case, I wouldn't expect it to matter one whit whether the cast applied to s or to t. If s becomes mutable, then its t member will be mutable, and if s is left const and the cast applies to its t member, then t should still be mutable, and then the resulting pointer value should be mutable. In either case, the result should be a mutable T* which should be able to be used to initialize the variable.

Maybe there's some language detail here that I'm missing, and this isn't actually a bug, but I don't see any reason why using cast() wouldn't work on s.t, so something about using the . operator seems to be mucking things up.

Note that

---
    T* t = cast(T*) s.t;
---

does work, so the issue is specifically with cast().
Comment 1 elpenguino+D 2024-11-21 02:26:18 UTC
This is behaving as expected. The dot operator has a higher precedence, and `cast()(const(T*))` == `const(T)*`.