util.ml 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. include Ast
  2. let var_counter = ref 0
  3. let fresh_var prefix =
  4. var_counter := !var_counter + 1;
  5. prefix ^ "$" ^ string_of_int !var_counter
  6. (* Default tree transformation
  7. * (node -> node) -> node -> node *)
  8. let rec transform visitor node =
  9. let trav = visitor in
  10. let trav_all nodes = List.map trav nodes in
  11. match node with
  12. | Program (decls) ->
  13. Program (trav_all decls)
  14. | FunDec (ret_type, name, params) ->
  15. FunDec (ret_type, name, trav_all params)
  16. | FunDef (export, ret_type, name, params, body) ->
  17. FunDef (export, ret_type, name, trav_all params, trav_all body)
  18. | GlobalDec (ctype, name) ->
  19. GlobalDec (ctype, name)
  20. | GlobalDef (export, ctype, name, Some init) ->
  21. GlobalDef (export, ctype, name, Some (trav init))
  22. | VarDec (ctype, name, Some init) ->
  23. VarDec (ctype, name, Some (trav init))
  24. | Assign (name, value) ->
  25. Assign (name, trav value)
  26. | Return (value) ->
  27. Return (trav value)
  28. | If (cond, body) ->
  29. If (trav cond, trav_all body)
  30. | IfElse (cond, true_body, false_body) ->
  31. IfElse (trav cond, trav_all true_body, trav_all false_body)
  32. | While (cond, body) ->
  33. While (trav cond, trav_all body)
  34. | DoWhile (cond, body) ->
  35. DoWhile (trav cond, trav_all body)
  36. | For (counter, start, stop, step, body) ->
  37. For (counter, trav start, trav stop, trav step, trav_all body)
  38. | Expr (value) ->
  39. Expr (trav value)
  40. | Monop (op, value) ->
  41. Monop (op, trav value)
  42. | Binop (op, left, right) ->
  43. Binop (op, trav left, trav right)
  44. | Cond (cond, true_expr, false_expr) ->
  45. Cond (trav cond, trav true_expr, trav false_expr)
  46. | TypeCast (ctype, value) ->
  47. TypeCast (ctype, trav value)
  48. | FunCall (name, args) ->
  49. FunCall (name, trav_all args)
  50. | Statements (stats) ->
  51. Statements (trav_all stats)
  52. | Loc (node, loc) ->
  53. Loc (trav node, loc)
  54. | _ -> node