first commit
This commit is contained in:
commit
c42520b597
6 changed files with 64 additions and 0 deletions
1
.gitignore
vendored
Normal file
1
.gitignore
vendored
Normal file
|
@ -0,0 +1 @@
|
||||||
|
_build
|
4
bin/dune
Normal file
4
bin/dune
Normal file
|
@ -0,0 +1,4 @@
|
||||||
|
(executable
|
||||||
|
(public_name brainfuck_interpreter)
|
||||||
|
(preprocess (pps ppx_deriving.show))
|
||||||
|
(name main))
|
48
bin/main.ml
Normal file
48
bin/main.ml
Normal file
|
@ -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)*)
|
||||||
|
|
0
brainfuck_interpreter.opam
Normal file
0
brainfuck_interpreter.opam
Normal file
8
dune-project
Normal file
8
dune-project
Normal file
|
@ -0,0 +1,8 @@
|
||||||
|
(lang dune 3.16)
|
||||||
|
|
||||||
|
(name brainfuck_interpreter)
|
||||||
|
|
||||||
|
(generate_opam_files true)
|
||||||
|
|
||||||
|
(package
|
||||||
|
(name brainfuck_interpreter))
|
3
test.bf
Normal file
3
test.bf
Normal file
|
@ -0,0 +1,3 @@
|
||||||
|
>++++++++[<+++++++++>-]<.>++++[<+++++++>-]<+.+++++++..+++.>>++++++[<+++++++>-]<+
|
||||||
|
+.------------.>++++++[<+++++++++>-]<+.<.+++.------.--------.>>>++++[<++++++++>-
|
||||||
|
]<+.
|
Loading…
Add table
Reference in a new issue