Search code examples
compilationcompiler-constructionvirtual-machineevaluation

Recognizing if further expression execution can be skipped


I have such expression:

(a and b or c) and d

How would I recognize it's further execution doesn't make sense. For example when

a = 0, b = 1, c = 0, d = 1

it doesn't make sense to perform the outer most (...) and d becouse the whole expression will be false after the (a and b or c) return false.

So I'm trying to find a general rule that allows me to analyze expression and based on that, find those parts of expressions which execution is crucial for the whole expression and skip further execution if necessary. Below is hypothetical code of stack based virtual machine with the expression i'm starting from

ld a
ld b
and
ld c
or
ld d
and

with this what I would like to achieve:

ld a
ld b
and
ld c
or
jmpf outOfQuery ;;jump if false
ld d
and
outOfQuer:

Solution

  • The concept of not evaluating the right operand of Boolean operators when the result is already determined by the left operand, is known as short circuiting. It is usually implemented by compiling the and and or operators to the same code as conditional expressions:

    • a and b would be equivalent to a ? b : false (or a ? b : a)
    • a or b would be equivalent to a ? true : b (or a ? a : b)

    So the generated byte- and/or machine code would not contain any and or or instructions, but just a conditional branch.