assemble.ml 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. open Types
  2. open Util
  3. let store ctype = function
  4. | 0 -> StoreGlob ()
  5. let assemble program =
  6. let labcounter = ref 0 in
  7. let genlabel suffix =
  8. labcounter := !labcounter + 1;
  9. string_of_int !labcounter ^ "_" ^ suffix
  10. in
  11. let consts = ref [] in
  12. let const_index const =
  13. let rec trav_consts i = function
  14. | [] -> consts := !consts @ [const]; i
  15. | hd :: _ when hd = const -> i
  16. | hd :: tl -> trav_consts (i + 1) tl
  17. in
  18. trav_consts 0 !consts
  19. in
  20. let rec trav node =
  21. let rec trav_all = function
  22. | [] -> []
  23. | hd :: tl -> trav hd @ (trav_all tl)
  24. in
  25. match node with
  26. | Program (decls, _) ->
  27. trav_all decls
  28. | FunDec (ret_type, name, params, _) ->
  29. [Import (name, ret_type, List.map ctypeof params)]
  30. | FunDef (export, ret_type, name, params, body, _) ->
  31. let label = name in
  32. let param_types = List.map ctypeof params in
  33. let export = match export with
  34. | false -> []
  35. | true -> [Export (name, ret_type, param_types, label)]
  36. in
  37. Comment ("function \"" ^ name ^ "\":") ::
  38. (export @ (Label label :: (trav body)))
  39. | VarDec (ctype, name, None, _) ->
  40. []
  41. | VarLet (Assign (name, None, value, _), ctype, depth) ->
  42. [store ctype depth]
  43. (*
  44. | VarLet (Assign (name, Some indices, value, _), ctype, depth) ->
  45. [store deoth]
  46. *)
  47. | BoolConst _ ->
  48. [LoadImm node]
  49. | IntConst _ | FloatConst _ ->
  50. [LoadConst (ctypeof node, const_index node)]
  51. | _ -> []
  52. (*| _ -> raise InvalidNode*)
  53. in
  54. let instrs = trav program in
  55. let const_defs = List.map (fun c -> Const c) !consts in
  56. const_defs @ instrs
  57. let rec phase input =
  58. prerr_endline "- Assembly";
  59. match input with
  60. | Types node -> Assembly (assemble node)
  61. | _ -> raise (InvalidInput "assembly")