Bug Report: The "and" operator can generate buggy code in mBlock 5


#1

This is a report of buggy behaviour of the “and” operator when used in combination with expressions that contain the ?: ternary operator. This has been observed with mBlock 5.0.0 RC on Mac.

Consider this small program for the mBot:

Expected behaviour: If both line sensors detect black the LED should be blue. If either of the line sensors detect white, the LED should be yellow.

Observed behaviour: If both line sensors detect black the LED is blue. If the right sensor detects white the LED is yellow. If the left sensor detects white the LED is blue (wrong). If both sensors detect white the LED is yellow.

Cause: The cause of this behaviour is in the code that is generated from the block program. The interesting part of the code looks like this:

  if(0 ? (2 == 0 ? linefollower_2.readSensors() == 0 :
  (linefollower_2.readSensors() & 2) == 2) :
  (2 == 0 ? linefollower_2.readSensors() == 3 :
  (linefollower_2.readSensors() & 2) == 0) && 0 ? (1 == 0 ? linefollower_2.readSensors() == 0 :
  (linefollower_2.readSensors() & 1) == 1) :
  (1 == 0 ? linefollower_2.readSensors() == 3 :
  (linefollower_2.readSensors() & 1) == 0)){
      rgbled_7.setColor(0, #4c00ff);
      rgbled_7.show();

  }else{
      rgbled_7.setColor(0, #fff600);
      rgbled_7.show();

  }

If one makes sense of that first if-statement, it is made up of a logical and operator (&&) with two ternary ?: operators on each side of the expression. The problem is that && has higher precedence than :? so the evaluation of the expression will not be the correct one.

Suggested solution: When generating the code, add extra parentheses around the values in the && expression. In this case around the ?: ternary operator.

The same problem probably exists for other logical operators as well (“or” and “not”) but I have not verified that.


#2

Thanks for the feedback, we’ll check and try to fix it as soon as possible.