Bug 24499 – foreach over a ref parameter to an rvalue should be an error

Status
NEW
Severity
normal
Priority
P1
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2024-04-13T18:30:02Z
Last change time
2025-08-08T10:35:02Z
Keywords
pull
Assigned to
No Owner
Creator
Walter Bright
Moved to GitHub: dmd#18231 →

Comments

Comment #0 by bugzilla — 2024-04-13T18:30:02Z
This should fail to compile: @safe void test() { foreach(ref el; 0 .. 5) el = 42; } It doesn't make any sense, and generates bad code: 0000: 55 push RBP 0001: 48 8B EC mov RBP,RSP 0004: 48 83 EC 10 sub RSP,010h 0008: C7 45 F8 00 00 00 00 mov dword ptr -8[RBP],0 000f: C7 45 FC 05 00 00 00 mov dword ptr -4[RBP],5 0016: 8B 45 F8 mov EAX,-8[RBP] 0019: 3B 45 FC cmp EAX,-4[RBP] 001c: 7D 0C jge L2a 001e: C7 45 F8 2A 00 00 00 mov dword ptr -8[RBP],02Ah !!!!! 0025: FF 45 F8 inc dword ptr -8[RBP] 0028: EB EC jmp short L16 002a: C9 leave 002b: C3 ret
Comment #1 by elpenguino+D — 2024-04-13T18:58:39Z
I fully agree. I've been bitten by this same problem many times in the past with incompletely-implemented ranges, and it can be fairly annoying to track down the cause with dbi + a few layers of range interfaces. If I recall correctly, there were many attempts to solve this in the past (https://github.com/dlang/DIPs/blob/master/DIPs/other/DIP1022.md being one of them), and there are many related issues, both open and closed. - https://issues.dlang.org/show_bug.cgi?id=11934 ("fixed", but the provided test case still fails) - https://issues.dlang.org/show_bug.cgi?id=24232 - https://issues.dlang.org/show_bug.cgi?id=5306 (and the subsequent https://issues.dlang.org/show_bug.cgi?id=6214 )
Comment #2 by dlang-bot — 2024-04-14T13:13:02Z
@ntrel created dlang/dmd pull request #16381 "[foreach] Deprecate `ref` for array index or range parameter" fixing this issue: - Deprecate `ref` for array index or range foreach parameter Fix Bugzilla 24499 - foreach over a ref parameter to an rvalue should be an error Fix Bugzilla 24232 - ref for index of foreach for arrays is not allowed by spec but accepted by compiler https://github.com/dlang/dmd/pull/16381
Comment #3 by robert.schadek — 2024-12-13T19:34:39Z
THIS ISSUE HAS BEEN MOVED TO GITHUB https://github.com/dlang/dmd/issues/18231 DO NOT COMMENT HERE ANYMORE, NOBODY WILL SEE IT, THIS ISSUE HAS BEEN MOVED TO GITHUB
Comment #4 by dlang-bot — 2025-08-08T10:35:02Z
@ntrel created dlang/dmd pull request #21674 "Deprecate `ref` for range foreach parameter" fixing this issue: - Deprecate `ref` for range foreach parameter Fix Bugzilla 24499 - foreach over a ref parameter to an rvalue should be an error Allow struct variable to be `ref` to avoid destructor call on each iteration. https://github.com/dlang/dmd/pull/21674