Proposal: Relax rules for 'pure'

dsimcha dsimcha at yahoo.com
Tue Sep 21 20:47:03 PDT 2010


== Quote from Don (nospam at nospam.com)'s article
> The docs currently state that:
> ---
> Pure functions are functions that produce the same result for the same
> arguments. To that end, a pure function:
>      * has parameters that are all immutable or are implicitly
> convertible to immutable
>      * does not read or write any global mutable state
> ---
> This is extremely restrictive, and not currently enforced.
> Two specific limitations:
> - a 'pure' member function doesn't really make sense (could only be
> called on an immutable class)
> - a pure function cannot have 'out' parameters.
> In a discussion on D.learn, Steven Schveighoffer noted that it's only
> shared variables which make things complicated.
> The limitations exist because 'pure' is used to mean both 'no hidden
> state' AND 'cachable'. But 'cachable' is really only an implementation
> detail.
> PROPOSAL:
> Drop the first requirement. Only one requirement is necessary:
> A pure function does not read or write any global mutable state.
> If a pure function has parameters that are all immutable or are
> implicitly convertible to immutable, then the compiler is permitted to
> cache the results.
> This is possible because the first rule (all immutable parameters) is
> trivial, and can be checked from the function declaration (in fact, you
> can check it just from the mangled function name). The second rule (no
> globals) is viral, and requires inspection of the function body, and the
> function bodies of every function called by that function.
> Actually, a clever compiler could even cache the results of pure
> functions which have parameters which don't implicitly cast to immutable.
> I haven't found anything in TDPL which mentions the "only immutable
> parameters" rule. Relaxing that rule would allow much larger functions
> to be cached. The more important benefit (IMHO) of pure, that it makes
> it easier to reason about code, would be dramatically extended.

Two things:

1.  The documentation that says that the parameters need to be convertible to
immutable is outdated.  This was changed a while ago to only requiring const.

2.  If you mean that the parameters don't have to be const either, i.e. you can
freely mutate state on the heap, i.e. of a ref parameter, or stuff that's
reachable from a pointer or reference, then pure offers almost no useful guarantees.


More information about the Digitalmars-d mailing list