fasterthanlime / shin

:warning: (def shin (dissoc clojurescript :jvm :google_closure)) (deprecated)
MIT License
35 stars 1 forks source link

Statement / Expression awareness #30

Closed fasterthanlime closed 9 years ago

fasterthanlime commented 9 years ago

More poking with mainline cljs revealed something interesting:

If in statement context

(fn []
  (if cond (foo) (bar))
  nil)

Translates to:

function () {
  if (cljs.core.truth_(cond)) {
    foo();
  } else {
    bar();
  }
  return null;
}

If in return placement

(fn []
  (if cond (foo) (bar)))

Translates to

function () {
  if (cljs.core.truth_(cond)) {
    return foo();
  } else {
    return bar();
  }
}

If in expression context

(fn []
  (prn (if cond (foo) (bar))))

Translates to

function () {
  return cljs.core.prn.call(null, cljs.core.truth_(cond) ? foo() : bar());
}

TL;DR cljs mainline generates different code depending on whether we're in a statement context or an expression context, and doesn't consider return a simple expression context.

More fun:

Degenerate if branches

(fn []
  (if cond foo bar)
  nil)

Translates to:

function () {
  if (cljs.core.truth_(cond)) {} else {}
  return null;
}