brainfuck_interpreter/bin/main.ml
2025-03-09 17:53:05 +13:00

48 lines
1.5 KiB
OCaml

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)*)