mattbierner / khepri

ECMAScript derived programming language
http://khepri-lang.com/
MIT License
67 stars 3 forks source link

Constant subexpression inlining without temporaries #99

Open mattbierner opened 10 years ago

mattbierner commented 10 years ago
(+, 10) \> (*, 2);

Currently produces

(function(x) {
    var y = (10 + x);
    return (2 * y);
});

Better output would be:

(function(x) {
    return (2 * (10 + x));
});

Because the order of evaluation of 10 + x and 2 * y does not matter and we can directly replace y in 2 * y with 10 * x. In other cases, this order is significant.

\x -> {
var f := \...;

var y = 10 + x;
return f() + y * 2; 
}

Cannot be safely rewritten to

\x -> {
var f := \...;
return f() + (10 + x) * 2; 
}

Because f could be crazy and mutate x. Then the result of 10 + x may differ depending on if it is evaluated before or after the call to f.

mattbierner commented 10 years ago

Actually, this is false.

Because of Javascript craziness, the toString or valueOf methods can do anything, including IO or state mutation. Therefore, it is generally not safe to switch the order in which two subexpressions with arbitrary objects are evaluated in.