On 7/18/2011 7:43 PM, Jonathan M Davis wrote:
On 2011-07-18 16:02, Johann MacDonagh wrote:
On 7/18/2011 7:00 PM, bearophile wrote:
Jonathan M Davis:
And if pure were inferred for a function and then it became
impure, that could break a _lot_ of code.
OK. The restricted idea then is to infer only the purity of functions
called by templates, to allow more templates to be pure, and such
inferred purity is seen by function templates only.
Example: if a not pure function sqr is called by both a not pure template
bar and by a pure function foo, the compiler raises an error in foo,
because sqr is not pure, but compiles the pure main because sqr called
by bar is seen as pure :-)
int sqr(in int x) {
return x * x;
}
int foo(in int x) pure { // error, sqr is not tagged pure
return sqr(x) + sqr(x);
}
int bar(T)(in T x) {
return sqr(x) * sqr(x);
}
void main() pure {
bar(1); // OK, sqr can be inferred as pure
}
It looks a bit complex :-)
Bye,
bearophile
I thought purity inference only worked one level deep. It would look at
each of the functions it calls. If they are all explicitly marked pure,
then its pure. I don't believe it analyzes the body of sqr to mark it as
pure. You'd still have to mark sqr as pure.
I'm not sure how deep it currnently goes, but it definitely _should_ go as
deep as the templates go. If it calls an templated functions, then those
functions have to be generated before it can use them anyway - let alone know
whether they're pure or not. So, if you have 10 levels of 10 template function
calls with a normal pure function at the bottom (or a template function at the
bottom which doesn't call any other functions and doesn't do anything that a
pure function can't do), then all 10 levels should be pure. Whether that works
at the moment, I don't know. But if it's only one level, then purity inference
doesn't gain us much given how often templated functions call other templated
functions.
- Jonathan M Davis
Right, I'm saying if you have this:
void something(S)(S s)
{
somethingElse!S(s);
callSomething();
}
In this case inference would take a look at everything it calls. When it
hits the somethingElse template it must generate that before moving on.
That generated template will have inferred purity. The template will
then check callSomething and explicitly check its purity. If the
generated somethingElse template and callSomething are both pure, then
the generated something template is pure in this case.