global and local variables with scope

also reworked arg parsing, now has --debug flag
This commit is contained in:
Moritz Gmeiner 2024-08-26 01:58:03 +02:00
commit 77e57cd8c2
8 changed files with 341 additions and 95 deletions

View file

@ -1,19 +1,27 @@
let printUsage () =
print_endline "Usage: jlox [script]";
exit 64
type args = { debug : bool; file_name : string option }
let parse_args () : args =
let usage_msg = "mlox [--debug] [<file>]" in
let debug = ref false in
let anon = ref [] in
let anon_fun s = anon := s :: !anon in
let spec = [ ("--debug", Arg.Set debug, "Debug mode") ] in
let () = Arg.parse spec anon_fun usage_msg in
let debug = !debug in
let file_and_args = List.rev !anon in
let file_name = List.nth_opt file_and_args 0 in
{ debug; file_name }
let () =
let argc = Array.length Sys.argv in
match argc - 1 with
| 0 -> Lox.runRepl ()
| 1 -> (
let path = Sys.argv.(1) in
let { debug; file_name } = parse_args () in
match file_name with
| None -> Lox.runRepl ~debug ()
| Some file_name -> (
(* Printf.printf "Running script %s\n" path; *)
let ic = open_in path in
let ic = open_in file_name in
let source = In_channel.input_all ic in
match Lox.run source with
match Lox.run ~debug source with
| Error e ->
Lox.Error.print_error e;
exit 1
| Ok () -> exit 0)
| _ -> printUsage ()