standalone exapunks vm in ocaml
1(* This Source Code Form is subject to the terms of the Mozilla Public
2 License, v. 2.0. If a copy of the MPL was not distributed with this
3 file, You can obtain one at https://mozilla.org/MPL/2.0/. *)
4
5open Utils
6
7let simpleInstruction name = Printf.printf "%s" name
8
9let regInstruction name r = Printf.printf "%s %s" name (Register.show r)
10
11let rnInstruction name rn = Printf.printf "%s %s" name (Register.show_r_n rn)
12
13let labelInstruction name label = Printf.printf "%s %s" name label
14
15let srcDestInstruction name src dest =
16 let left = Register.show_r_n src in
17 let right = Register.show dest in
18 Printf.printf "%s %s %s" name left right
19
20let mathInstruction name src i dest =
21 let left = Register.show_r_n src in
22 let right = Register.show_r_n i in
23 Printf.printf "%s %s %s %s" name left right (Register.show dest)
24
25let testInstruction name left func right =
26 let left = Register.show_r_n left in
27 let right = Register.show_r_n right in
28 Printf.printf "%s %s %s %s" name left func right
29
30let disassembleInstruction (exa : Exa.t) (op : OpCode.t) (offset : int) : unit =
31 let loc = if exa.ip == offset then ">" else " " in
32 Printf.printf "%s%04d %s" loc offset (OpCode.show op);
33 print_newline ()
34
35let disassembleFile ?(pos = -1) (file : File.t) : unit =
36 Printf.printf "__ %s __\n" file.name;
37 print_string "[ ";
38 let len = File.length file in
39 for i = 0 to len - 1 do
40 let s = Value.quote (Dynarray.get file.contents i) in
41 if i = pos then Printf.printf "[%s]; " s else Printf.printf "%s; " s
42 done;
43 if pos = len then print_string "[]";
44 print_string "]";
45 print_newline ()
46
47let disassembleExa (exa : Exa.t) : unit =
48 if not exa.dead then (
49 Printf.printf "== %s (%s) ==\n" exa.name exa.host.name;
50 Printf.printf "X: %s\n" (Value.show exa.x);
51 Printf.printf "T: %s\n" (Value.show exa.t);
52 Printf.printf "F: %s\n"
53 (match exa.f with
54 | None -> "None"
55 | Some f -> f.name);
56 Dynarray.iteri (fun idx op -> disassembleInstruction exa op idx) exa.code;
57 if exa.ip == Dynarray.length exa.code then print_string ">\n";
58 match exa.f with
59 | None -> ()
60 | Some f -> disassembleFile ~pos:exa.f_pos f);
61 ()
62
63let disassembleHost (host : Host.t) : unit =
64 Printf.printf "Host: %s\n" host.name;
65 print_string "Objects: ";
66 host.grid |> StringMap.to_seq
67 |> Seq.map (fun (name, _obj) -> name)
68 |> List.of_seq |> String.concat ", " |> print_string;
69 print_newline ();
70 ()