Thread overview
[Issue 24211] Const nested function can mutate context
Oct 30, 2023
Basile-z
Oct 30, 2023
Basile-z
Nov 02, 2023
Paul Backus
October 30, 2023
https://issues.dlang.org/show_bug.cgi?id=24211

Basile-z <b2.temp@gmx.com> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
                 CC|                            |b2.temp@gmx.com

--- Comment #1 from Basile-z <b2.temp@gmx.com> ---
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.

--
October 30, 2023
https://issues.dlang.org/show_bug.cgi?id=24211

--- Comment #2 from Basile-z <b2.temp@gmx.com> ---
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`.

--
November 02, 2023
https://issues.dlang.org/show_bug.cgi?id=24211

Paul Backus <snarwin+bugzilla@gmail.com> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
           Keywords|                            |safe

--- Comment #3 from Paul Backus <snarwin+bugzilla@gmail.com> ---
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

--