Fix memory leak w/ when statements - BIT-1058

Specifically if the condition of a when statement uses an index
expression (e.g. table lookup).
Merge remote-tracking branch 'origin/topic/jsiwek/when-leak'

BIT-1058 #merged

* origin/topic/jsiwek/when-leak:
  Fix memory leak w/ when statements - BIT-1058