Issue 24353 - Misleading error for foreach when opApply has wrong qualifier
Summary: Misleading error for foreach when opApply has wrong qualifier
Status: REOPENED
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D2
Hardware: All All
: P1 normal
Assignee: No Owner
URL:
Keywords: pull
Depends on:
Blocks:
 
Reported: 2024-01-23 17:21 UTC by Paul Backus
Modified: 2024-11-17 01:28 UTC (History)
0 users

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description Paul Backus 2024-01-23 17:21:47 UTC
As of DMD 2.106.1, attempting to compile the following program produces a misleading error message:

---
struct S
{
    int opApply(int delegate(int) dg)
    {
        return 0;
    }
}

void example()
{
    const S s;
    foreach (e; s) {}
}
---

The message is:

---
bug.d(12): Error: cannot uniquely infer `foreach` argument types
---

However, the real cause of the error is that the program is attempting to call a mutable opApply method on a const object.

Calling opApply directly instead of using foreach produces the correct message:

---
bug.d(12): Error: mutable method `bug.S.opApply` is not callable using a `const` object
bug.d(3):        Consider adding `const` or `inout` here
---
Comment 1 Dlang Bot 2024-11-16 21:51:26 UTC
@royalpinto007 created dlang/dmd pull request #17071 "fix Bugzilla 24353 - add mutability check for foreach with opApply" fixing this issue:

- fix Bugzilla 24353 - add mutability check for foreach with opApply
  
  Signed-off-by: royalpinto007 <royalpinto007@gmail.com>

https://github.com/dlang/dmd/pull/17071
Comment 2 Dlang Bot 2024-11-16 23:44:25 UTC
dlang/dmd pull request #17071 "fix Bugzilla 24353 - add mutability check for foreach with opApply" was merged into master:

- 7ce408a4370a7f308c173b9f233ed7f242b926dc by royalpinto007:
  fix Bugzilla 24353 - add mutability check for foreach with opApply
  
  Signed-off-by: royalpinto007 <royalpinto007@gmail.com>

https://github.com/dlang/dmd/pull/17071
Comment 3 Paul Backus 2024-11-17 01:28:41 UTC
The linked PR is an incomplete fix. The example with `const` now works, but the same problem still exists with other qualifiers, such as `shared` and `immutable`.