Mercerenies / gdlisp

Lisp on the Godot platform
GNU General Public License v3.0
141 stars 1 forks source link

Simple if statement assignment optimization #26

Closed Mercerenies closed 3 years ago

Mercerenies commented 3 years ago

Currently, (if (foo) 1 2) compiles to

var _cond_0 = null
if foo():
    _cond_0 = 1
else:
    _cond_0 = 2
return _cond_0

If we see the pattern:

  1. Variable declaration with assignment to a constant form
  2. If-else statement, or a simple if statement with no else
  3. Every clause of the if-else (or if) is a single statement: a simple assignment to the declared variable

Then we can optimize down to an application of the ternary operator

var _cond_0 = 1 if foo() else 2

Note that the ternary operator does short-circuiting correctly, so the later assignments do not have to be constant expressions (the declaration does, or it at least has to be side-effect-free, since we're planning to elide it).

Possible extension: Support elif as nested ternary applications. This should eliminate a lot of the weirdness with and / or compiling to full statements.

Mercerenies commented 3 years ago

df6246a closes this issue, complete with the elif extension which compiles to nested ternary applications.