boolop.ml 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. open Globals
  22. let cast ctype node = TypeCast (ctype, node, [Type ctype])
  23. let boolconst value = Const (BoolVal value, [Type Bool])
  24. let intconst value = Const (IntVal value, [Type Int])
  25. let floatconst value = Const (FloatVal value, [Type Float])
  26. let rec trav_binop = function
  27. | ((Eq | Ne) as op, left, right, ann) ->
  28. bool_op (Binop (op, cast Int left, cast Int right, ann))
  29. | (And, left, right, ann) ->
  30. bool_op (Cond (left, right, boolconst false, ann))
  31. | (Or, left, right, ann) ->
  32. bool_op (Cond (left, boolconst true, right, ann))
  33. | ((Add | Mul) as op, left, right, ann) ->
  34. bool_op (cast Bool (Binop (op, cast Int left, cast Int right, Type Int :: ann)))
  35. | (op, left, right, ann) ->
  36. Binop (op, left, right, ann)
  37. and bool_op = function
  38. | Binop (op, left, right, ann) when typeof left = Bool && typeof right = Bool ->
  39. trav_binop (op, bool_op left, bool_op right, ann)
  40. | TypeCast (Bool, value, ann) when typeof value = Int ->
  41. Binop (Ne, bool_op value, intconst 0, ann)
  42. | TypeCast (Bool, value, ann) when typeof value = Float ->
  43. Binop (Ne, bool_op value, floatconst 0.0, ann)
  44. | TypeCast (Int, value, ann) when typeof value = Bool ->
  45. Cond (bool_op value, intconst 1, intconst 0, ann)
  46. | TypeCast (Float, value, ann) when typeof value = Bool ->
  47. Cond (bool_op value, floatconst 1.0, floatconst 0.0, ann)
  48. | TypeCast (ctype, value, ann) when typeof value = ctype ->
  49. bool_op value
  50. | node -> transform_children bool_op node
  51. let phase = function
  52. | Ast node -> Ast (bool_op node)
  53. | _ -> raise (InvalidInput "bool operations")