2024-08-02 00:10:48 +02:00
|
|
|
let ( let* ) = Result.bind
|
|
|
|
|
|
|
|
|
|
module Error = Error
|
2024-08-12 16:31:28 +02:00
|
|
|
module Expr = Expr
|
2024-08-17 13:32:59 +02:00
|
|
|
module Interpreter = Interpreter
|
2024-08-12 16:31:28 +02:00
|
|
|
module Lexer = Lexer
|
|
|
|
|
module Parser = Parser
|
2024-08-25 02:12:51 +02:00
|
|
|
module Stmt = Stmt
|
2024-08-02 00:10:48 +02:00
|
|
|
|
|
|
|
|
type lox_error = Error.lox_error
|
|
|
|
|
|
2024-08-26 01:58:03 +02:00
|
|
|
let run ?(env : Environment.environment option) ?(debug = false) (source : string) :
|
|
|
|
|
(unit, lox_error) result =
|
|
|
|
|
let env = Option.value env ~default:(Environment.Env.make ()) in
|
2024-08-02 00:10:48 +02:00
|
|
|
let* tokens = Error.of_lexer_error (Lexer.tokenize source) in
|
2024-08-26 01:58:03 +02:00
|
|
|
let () =
|
|
|
|
|
if debug then
|
|
|
|
|
let print_tokens () =
|
|
|
|
|
print_endline "--- Tokens ---";
|
|
|
|
|
let f token = Printf.printf "%s " (Lexer.show_token token) in
|
|
|
|
|
Printf.printf "Got %d tokens\n" (List.length tokens);
|
|
|
|
|
List.iter f tokens;
|
|
|
|
|
print_newline ();
|
|
|
|
|
print_endline "--------------";
|
|
|
|
|
print_newline ()
|
|
|
|
|
in
|
|
|
|
|
print_tokens ()
|
|
|
|
|
else ()
|
|
|
|
|
in
|
2024-08-27 01:57:47 +02:00
|
|
|
let* stmts = Parser.parse tokens |> Error.of_parser_error in
|
2024-08-26 01:58:03 +02:00
|
|
|
let () =
|
|
|
|
|
if debug then
|
|
|
|
|
let print_statements () =
|
|
|
|
|
print_endline "--- Statements ---";
|
|
|
|
|
let f (stmt : Stmt.stmt_node) = print_endline (Stmt.show_stmt stmt.stmt) in
|
|
|
|
|
List.iter f stmts;
|
|
|
|
|
print_endline "------------------";
|
|
|
|
|
print_newline ()
|
|
|
|
|
in
|
|
|
|
|
print_statements ()
|
|
|
|
|
else ()
|
|
|
|
|
in
|
2024-08-25 02:12:51 +02:00
|
|
|
let rec interpret_stmts (stmts : Stmt.stmt_node list) =
|
|
|
|
|
match stmts with
|
|
|
|
|
| [] -> Ok ()
|
|
|
|
|
| stmt :: tail ->
|
2024-08-26 01:58:03 +02:00
|
|
|
let* _ = Interpreter.interpret_stmt env stmt in
|
2024-08-25 02:12:51 +02:00
|
|
|
interpret_stmts tail
|
|
|
|
|
in
|
2024-08-26 01:58:03 +02:00
|
|
|
interpret_stmts stmts |> Error.of_runtimer_error
|
2024-08-02 00:10:48 +02:00
|
|
|
|
2024-08-26 01:58:03 +02:00
|
|
|
let runRepl ?(debug = false) () : unit =
|
|
|
|
|
let env = Environment.Env.make () in
|
2024-08-02 00:10:48 +02:00
|
|
|
try
|
|
|
|
|
while true do
|
|
|
|
|
print_string "> ";
|
|
|
|
|
let line = read_line () in
|
2024-08-26 01:58:03 +02:00
|
|
|
let result = run ~env ~debug line in
|
2024-08-02 00:10:48 +02:00
|
|
|
Result.iter_error Error.print_error result
|
|
|
|
|
done
|
|
|
|
|
with End_of_file -> ()
|