Bug 21756 – Immutable array literals cause runtime GC allocation instead of static readonly section allocation

Status
NEW
Severity
major
Priority
P2
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2021-03-24T08:55:42Z
Last change time
2024-12-13T19:15:24Z
Keywords
pull
Assigned to
No Owner
Creator
Eyal
Moved to GitHub: dmd#19894 →

Comments

Comment #0 by eyal — 2021-03-24T08:55:42Z
auto f() { return "abc"; } // @nogc, cheap auto g() { return ['a', 'b', 'c']; } // allocates via GC, at runtime
Comment #1 by eyal — 2021-03-24T09:10:03Z
I am lacking a way to say the array literal is immutable, so it gets allocated the same way a string literal does. This is especially problematic in a function like: @nogc string f() { enum compileTimeStr = "fmt %x".format(someNum()); return compileTimeStr; // GC allocation here }
Comment #2 by b2.temp — 2021-03-31T18:23:45Z
cast(immutable) could do that. Under the hood a hidden static immutable would be created.
Comment #3 by dlang-bot — 2021-03-31T18:24:48Z
@TungstenHeart created dlang/dmd pull request #12329 "fix 21756 - make `cast(immutable)arrayLiteral` @nogc" fixing this issue: - fix 21756 - make `cast(immutable)arrayLiteral` @nogc adjust array literal semantics so that ```d cast(immutable) <arrayLiteral> ``` gets rewritten to a DeclExp comma VarExp ```d (static immutable __array = <arrayLiteral>, __array) ``` allowing immutable array literals to be `@nogc` https://github.com/dlang/dmd/pull/12329
Comment #4 by pro.mathias.lang — 2021-04-01T00:10:12Z
No, `cast` should not do this magic, it should be requested by the user directly. So: ``` auto g() { static immutable ret = ['a', 'b', 'c']; return ret; } ``` Leaving open for the benefit of the discussion (I found this issue because there's a PR), but IMO this is RESOLVED INVALID territory.
Comment #5 by eyal — 2021-04-01T20:14:38Z
Neither the PR nor this solution seem to resolve the issue. Consider these pieces of code. Will NOT compile: @nogc string f() { static immutable s = "%5d".format(5); enum u = s; return u; // does GC :-( } Will compile fine: @nogc string f() { static immutable s = "%5d".format(5); enum u = s ~ ""; return u; // all is well } Will also compile fine: @nogc string f() { static immutable s = "%5d".format(5) ~ ""; enum u = s; return u; // all is well } Surely this cannot be considered a reasonable state of things?
Comment #6 by robert.schadek — 2024-12-13T19:15:24Z
THIS ISSUE HAS BEEN MOVED TO GITHUB https://github.com/dlang/dmd/issues/19894 DO NOT COMMENT HERE ANYMORE, NOBODY WILL SEE IT, THIS ISSUE HAS BEEN MOVED TO GITHUB