Moving variables declarations
I have been working on the question of what to do with variable declarations with the 'variables in queries' optimisation. I have found two solutions available to this problem.
The first one is a 'brute force' solution where the optimisation takes explicitly into account the necessity to move those declarations around. I have started implementing this one.
The other is conceptually rather nicer, but might be less efficient (and has a few other problems). It would be to modify the AST to push all variables declarations always to the earliest possible position (where everything needed to calculate the value is known) in a separate optimisation phase. This would solve the problem of the 'variables in queries' optimisation, and might yield to other optimisations as side-effects (pushing the calculation of variables' values outside of loops, for example). On the other hand, it might be counter-productive in some other cases (a value calculated in only one of a condition's branch pushed before the condition, and calculated every time). Furthermore, if side-effects are allowed in expressions, moving let operators (and their value expression) might completely break the expected behaviour of the side-effects. Of course this is also true with the 'brute-force method'.