D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 6274 - 'pure' for a whole struct definition
Summary: 'pure' for a whole struct definition
Status: RESOLVED WONTFIX
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D2
Hardware: All All
: P2 enhancement
Assignee: No Owner
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2011-07-08 18:03 UTC by bearophile_hugs
Modified: 2022-08-15 14:49 UTC (History)
2 users (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-07-08 18:03:32 UTC
Just like "final" applied to a class makes all its methods non-virtual:


final class Foo {
    int x;
    this(int xx) { x = xx; }
    void bar() {}
    static void spam() {}
}
void main() {}



I'd like the attribute "pure" applied to a struct/class (in DMD 2.054beta this doesn't compile):

pure struct Foo {
    int x;
    this(int xx) { x = xx; }
    void bar() {}
    static void spam() {}
}
void main() pure {
    Foo f = Foo(1);
    f.bar();
    Foo.spam();
}


to be equivalent to adding "pure" to all its methods:

struct Foo {
    int x;
    this(int xx) pure { x = xx; }
    void bar() pure {}
    static void spam() pure {}
}
void main() pure {
    Foo f = Foo(1);
    f.bar();
    Foo.spam();
}
Comment 1 bearophile_hugs 2011-08-12 12:44:00 UTC
There is something I don't fully understand. The following code compiles with the improvements in DMD 2.055alpha/head, but it needs a "pure" or before "struct Map" (here#1) or at the front() method of Map (here#2). If both are removed it doesn't compile. So is the pure attribute for struct partially working already?



@property bool empty(T)(in T[] a) pure nothrow {
    return !a.length;
}

@property ref T front(T)(T[] a) pure nothrow {
    assert(a.length);
    return a[0];
}

void popFront(A)(ref A a) pure nothrow {
    assert(a.length);
    a = a[1 .. $];
}

pure struct Map(alias fun, R) { // here#1
    R _input;

    this(R input) nothrow pure {
        _input = input;
    }

    @property bool empty() nothrow const pure {
        return _input.empty;
    }

    @property auto ref front() nothrow const { // here#2
        return fun(_input.front);
    }

    void popFront() nothrow pure {
        _input.popFront();
    }
}

template map(alias fun) {
    auto map(R)(R range) {
        return Map!(fun, R)(range);
    }
}

int sqr(int x) pure nothrow { return x * x; }

pure nothrow int foo(int n) {
    int total;
    foreach (x; map!(sqr)([1, 2, 3, 4]))
        total += x;
    return total;
}

void main() {
    assert(foo(10) == 30);
}
Comment 2 Infiltrator 2014-03-19 19:21:22 UTC
Currently, instead of:

pure struct Foo { ... }

you can do:

struct Foo { pure: ... }


Is this acceptable?
Comment 3 RazvanN 2022-08-15 14:49:28 UTC
Yes, you can use the `pure:` to obtain exactly what is requested. Closing as WONTFIX.