Bug 24211 – Const nested function can mutate context

Status
NEW
Severity
normal
Priority
P1
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2023-10-30T13:04:25Z
Last change time
2024-12-13T19:31:21Z
Keywords
safe
Assigned to
No Owner
Creator
Paul Backus
Moved to GitHub: dmd#18193 →

Comments

Comment #0 by snarwin+bugzilla — 2023-10-30T13:04:25Z
As of DMD 2.105.2, the following program compiles: --- void main() { int n; void fun() const { n = 123; } } --- Despite being a const function, `fun` is allowed to mutate its context. If fun is made immutable instead of const, the program does not compile. Possibly a duplicate of issue 16248 or issue 18566.
Comment #1 by b2.temp — 2023-10-30T16:34:45Z
Yes this is like 16248. I dont remember exactly why I had closed that issue, maybe after a NG discussion where I've been explained that in this case `const` is a noop. Anyway, the fact that `immutable` is threated differently is a strong argument indicating that something should be done for `const` too.
Comment #2 by b2.temp — 2023-10-30T23:46:50Z
A bit more of analysis: function attributes apply to the context. The fact that this works is more related to another problem that is "function signatures are wrong" ```d struct S { function f() const {} } ``` is actually more like ```d struct S {} function f(const S* s){} ``` The storage class cannot be put on a parameter that dont exist, so the D solution is to make the hidden `this` const using trailing attributes. That should apply to nested function too, those that captures `this`.
Comment #3 by snarwin+bugzilla — 2023-11-02T00:53:31Z
This bug creates a hole in @safe when combined with "Inferred scope parameters in pure functions" [1]. --- void main() @safe { const(int)* escaped; @safe pure nothrow void fun(const(int)* p) const { escaped = p; } int n; fun(&n); } --- Because fun's context is const, the compiler can assume that "None of the other parameters [aside from p] have mutable indirections," and allow the use of a scope pointer as an argument. If not for this bug, that assumption would be correct. [1] https://dlang.org/spec/function.html#pure-scope-inference
Comment #4 by robert.schadek — 2024-12-13T19:31:21Z
THIS ISSUE HAS BEEN MOVED TO GITHUB https://github.com/dlang/dmd/issues/18193 DO NOT COMMENT HERE ANYMORE, NOBODY WILL SEE IT, THIS ISSUE HAS BEEN MOVED TO GITHUB