D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 4031 - Should be able to access const value-type globals from pure functions
Summary: Should be able to access const value-type globals from pure functions
Status: RESOLVED FIXED
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D2
Hardware: All All
: P2 normal
Assignee: No Owner
URL:
Keywords: pull, rejects-valid
Depends on:
Blocks:
 
Reported: 2010-03-30 03:00 UTC by bearophile_hugs
Modified: 2012-02-01 17:54 UTC (History)
3 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 2010-03-30 03:00:41 UTC
Here I propose two small different changes: to refuse line 2 and accept line 4.

Mutable static variables can't be used in pure functions, so it's better to really disallow them, and produce a compile error at line 2 here (there's no point in allowing their definition and disallowing just their usage).

(On the other hand the static "z" at line 3 is a const and can be allowed, as dmd does now.)

The compiler can also allow the line 4, because z will not change, keeping the function foo pure (there is no point in disallowing something that's semantically correct and safe).


pure int foo(int x) {
    static int y = 10;       // line 2  ERR
    const static int z = 20; // line 3  OK (as now)
    return x + z;            // line 4  OK
}
void main() {}
Comment 1 yebblies 2011-07-02 12:53:47 UTC
https://github.com/D-Programming-Language/dmd/pull/194

This allows static and global value type variables to be used in pure functions.

I'm not sure if disabling mutable static variables inside pure functions is valid, as some actions on them (eg. returning their address) do make sense.  They can also be accessed from any statements inside debug {}.  Please open a new report for that if you would like it.
Comment 3 bearophile_hugs 2011-07-03 17:54:44 UTC
Thank you both for fixing the first thing.

(In reply to comment #1)
> I'm not sure if disabling mutable static variables inside pure functions is
> valid, as some actions on them (eg. returning their address) do make sense.

Returning the address of a static variable defined inside a pure function? I don't see the purpose of this. It smells.
 

> They can also be accessed from any statements inside debug {}.

But this need is probably uncommon, and when this needs arises you are able to move the definition of such variable inside the debug:


pure int foo(int x) {
    debug {
        static int y = 10;
    }
    return x;
}
void main() {}



> Please open a new report for that if you would like it.

Maybe Walter is willing to comment on this, but I think I will open another report for this.
Comment 4 yebblies 2012-02-01 17:54:48 UTC
This was fixed a while ago.