LARA

Postfix Translation of Boolean Operators

Eager Boolean Operations

Candidate translation, knowing that booleans are 0 or 1:

[[ e1 & e2 ]] =
   [[ e1 ]]
   [[ e2 ]]
   iand
[[ e1 | e2 ]] =
   [[ e1 ]]
   [[ e2 ]]
   ior

This indeed works for &, |

Java code:

static boolean test(boolean x, boolean y) {
  return (x & y);
}
static boolean test(boolean, boolean);
  Code:
   0:   iload_0
   1:   iload_1
   2:   iand
   3:   ireturn

Effect of Eager Evaluation

Example 1

What does the following Java program do:

class Test {
  static boolean bigFraction(int x, int y) {
    return ((y==0) | (x/y > 100));
  }
  public static void main(String[] args) {
    boolean is = bigFraction(10,0);
  }
}

Answer:

Example 2

What does the following Java program do:

class Test {
    static int iterate() {
	int[] a = new int[10];
	int i = 0;
	int res = 0;
	while ((i < a.length) & (a[i] >= 0)) {
	    i = i + 1;
	    res = res + 1;
	}
	return res;
    }
 
    public static void main(String[] args) {
	System.out.println(iterate());
    }
}

Answer:

Lazy Versions of Logical Operators

To enable code patterns similar to above, instead of bitwise operators

|  &

we use operators

|| && 

The semantics of Java requires: when evaluating

  • (p && q), if p is false, then q is not evaluated
  • (p || q), if p is true, then q is not evaluated