D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 6917 - with() at global scope too
Summary: with() at global scope too
Status: NEW
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D2
Hardware: All All
: P4 enhancement
Assignee: No Owner
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2011-11-08 19:24 UTC by bearophile_hugs
Modified: 2024-12-13 17:56 UTC (History)
1 user (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description bearophile_hugs 2011-11-08 19:24:43 UTC
A correct D2 program that defines a global immutable array of enum members:


enum MyEnum { first, second }
immutable MyEnum[] array = [MyEnum.first,MyEnum.second,MyEnum.second,
                            MyEnum.first,MyEnum.second,MyEnum.second];
void main() {}


To reduce the noise I'd like to use with() at global scope too (there is no need to call is "static with"):


enum MyEnum { first, second }
with (MyEnum) {
    immutable MyEnum[] array = [first,second,second,first,second,second];
}
void main() {}


with is useful for global structs too.
Comment 1 bearophile_hugs 2011-11-09 05:12:18 UTC
This is a workaround, but I try to avoid static this where possible to avoid circular reference import troubles:


enum MyEnum { first, second }
immutable MyEnum[] array;
static this() {
    with (MyEnum)
        array = [first,second,second,first,second,second];
}
void main() {}
Comment 2 bearophile_hugs 2013-11-24 08:27:41 UTC
Such "static with" that doesn't create a new scope is also useful to define constant arrays:

void main() {
    enum LongNamedEnum { A, B, C, D }
    const int[LongNamedEnum] foo =
        [LongNamedEnum.A: 10, LongNamedEnum.B: 20,
         LongNamedEnum.C: 30, LongNamedEnum.D: 40];
}


with is usually useful to write such array literals in a shorter space, but you can't also define the assopciative array as const:

void main() {
    enum LongNamedEnum { A, B, C, D }
    /*const*/ int[LongNamedEnum] foo;
    with (LongNamedEnum)
        foo = [A: 10, B: 20, C: 30, D: 40];
}



void main() {
    enum LongNamedEnum { A, B, C, D }
    static with (LongNamedEnum)
        const int[LongNamedEnum] foo = 
            [A: 10, B: 20, C: 30, D: 40];
}
Comment 3 Dennis 2021-09-08 13:43:07 UTC
I like the idea too. The workaround I currently use is this:
```
private alias L = LongNamedEnum;
immutable LongNamedEnum[] array = [L.first, L.second, L.second];
```
Comment 4 dlangBugzillaToGithub 2024-12-13 17:56:53 UTC
THIS ISSUE HAS BEEN MOVED TO GITHUB

https://github.com/dlang/dmd/issues/18379

DO NOT COMMENT HERE ANYMORE, NOBODY WILL SEE IT, THIS ISSUE HAS BEEN MOVED TO GITHUB