boolop.ml 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. (**
  2. * The phase applies the transformations shown below. These transformations are
  3. * required because the CiviC VM does not offer instructions that perform these
  4. * operations. Another reason is that conjunction and disjunction require
  5. * short-circuit evaluation. In the examples below, `b1` and `b2` are
  6. * expressions of type boolean, `i` is of type int and `f` is of type float.
  7. *
  8. * > b1 == b2 ==> (int)b1 == (int)b2
  9. * > b1 != b2 ==> (int)b1 != (int)b2
  10. * > b1 && b2 ==> b1 ? b2 : false
  11. * > b1 || b2 ==> b1 ? true : b2
  12. * > b1 + b2 ==> (bool)((int)b1 + (int)b2)
  13. * > b1 * b2 ==> (bool)((int)b1 * (int)b2)
  14. * > (bool)i ==> i != 0
  15. * > (bool)f ==> f != 0.0
  16. * > (int)b1 ==> b1 ? 1 : 0
  17. * > (float)b1 ==> b1 ? 1.0 : 0.0
  18. *)
  19. open Types
  20. open Util
  21. let cast ctype node = TypeCast (ctype, node, [Type ctype])
  22. let boolconst value = Const (BoolVal value, [Type Bool])
  23. let intconst value = Const (IntVal value, [Type Int])
  24. let floatconst value = Const (FloatVal value, [Type Float])
  25. let rec trav_binop = function
  26. | ((Eq | Ne) as op, left, right, ann) ->
  27. bool_op (Binop (op, cast Int left, cast Int right, ann))
  28. | (And, left, right, ann) ->
  29. bool_op (Cond (left, right, boolconst false, ann))
  30. | (Or, left, right, ann) ->
  31. bool_op (Cond (left, boolconst true, right, ann))
  32. | ((Add | Mul) as op, left, right, ann) ->
  33. bool_op (cast Bool (Binop (op, cast Int left, cast Int right, Type Int :: ann)))
  34. | (op, left, right, ann) ->
  35. Binop (op, left, right, ann)
  36. and bool_op = function
  37. | Binop (op, left, right, ann) when typeof left = Bool && typeof right = Bool ->
  38. trav_binop (op, bool_op left, bool_op right, ann)
  39. | TypeCast (Bool, value, ann) when typeof value = Int ->
  40. Binop (Ne, bool_op value, intconst 0, ann)
  41. | TypeCast (Bool, value, ann) when typeof value = Float ->
  42. Binop (Ne, bool_op value, floatconst 0.0, ann)
  43. | TypeCast (Int, value, ann) when typeof value = Bool ->
  44. Cond (bool_op value, intconst 1, intconst 0, ann)
  45. | TypeCast (Float, value, ann) when typeof value = Bool ->
  46. Cond (bool_op value, floatconst 1.0, floatconst 0.0, ann)
  47. | TypeCast (ctype, value, ann) when typeof value = ctype ->
  48. bool_op value
  49. | node -> traverse_unit bool_op node
  50. let phase = function
  51. | Ast node -> Ast (bool_op node)
  52. | _ -> raise InvalidInput