commit c42520b5976032a4dcb6253b95a3bbbc0f14981c Author: sam Date: Sun Mar 9 17:53:05 2025 +1300 first commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e35d885 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +_build diff --git a/bin/dune b/bin/dune new file mode 100644 index 0000000..dd67faa --- /dev/null +++ b/bin/dune @@ -0,0 +1,4 @@ +(executable + (public_name brainfuck_interpreter) + (preprocess (pps ppx_deriving.show)) + (name main)) diff --git a/bin/main.ml b/bin/main.ml new file mode 100644 index 0000000..3c7c302 --- /dev/null +++ b/bin/main.ml @@ -0,0 +1,48 @@ +exception Unrecognized_character of string + +type memory = int array [@@deriving show] + +let rec interpret code pc ptr stack memory = + if pc < String.length code then ( + let ch = code.[pc] in + let next_pc = pc + 1 in + let ret_val = match ch with + | '+' -> memory.(ptr) <- memory.(ptr) + 1 + | '-' -> memory.(ptr) <- memory.(ptr) - 1 + | '>' -> interpret code next_pc (ptr + 1) stack memory + | '<' -> interpret code next_pc (ptr - 1) stack memory + | '.' -> Printf.printf "%c" (char_of_int memory.(ptr)) + | '[' -> ( + Stack.push next_pc stack; + interpret code next_pc ptr stack memory + ) + | ']' -> ( + if memory.(ptr) == 0 then ( + let _ = Stack.pop_opt stack in + () + ) else ( + interpret code (Stack.top stack) ptr stack memory + ) + ) + | '\n' | ' ' -> () + | _ -> raise (Unrecognized_character (Char.escaped ch)) in + + interpret code next_pc ptr stack memory; + ret_val + ) +;; + +let () = + let file = open_in Sys.argv.(1) in + let code = really_input_string file (in_channel_length file) in + let stack = Stack.create () in + + let memory = Array.make 100 0 in + try + interpret code 0 0 stack memory; + with + | Unrecognized_character(ch) -> Printf.printf "ERROR: Unrecognized character \"%s\"\n" ch + | Stack.Empty -> (); + + (*Printf.printf "%s\n" (show_memory memory)*) + diff --git a/brainfuck_interpreter.opam b/brainfuck_interpreter.opam new file mode 100644 index 0000000..e69de29 diff --git a/dune-project b/dune-project new file mode 100644 index 0000000..bd38170 --- /dev/null +++ b/dune-project @@ -0,0 +1,8 @@ +(lang dune 3.16) + +(name brainfuck_interpreter) + +(generate_opam_files true) + +(package + (name brainfuck_interpreter)) diff --git a/test.bf b/test.bf new file mode 100644 index 0000000..2570b01 --- /dev/null +++ b/test.bf @@ -0,0 +1,3 @@ +>++++++++[<+++++++++>-]<.>++++[<+++++++>-]<+.+++++++..+++.>>++++++[<+++++++>-]<+ ++.------------.>++++++[<+++++++++>-]<+.<.+++.------.--------.>>>++++[<++++++++>- +]<+.