package minicaml

  1. Overview
  2. Docs

Source file file.ml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
open Interface
open Types

(** Parse the contents from a file, using a given [parser]. *)
let read_file parser fn =
  try
    if not (Sys.file_exists fn) then raise (FileNotFoundError fn) else
      let fh = open_in fn in
      let lex = Lexing.from_channel fh in
      lex.Lexing.lex_curr_p <- {lex.Lexing.lex_curr_p with Lexing.pos_fname = fn};
      try
        let terms = wrap_syntax_errors parser lex in
        close_in fh;
        terms
      with
      (* Close the file in case of any parsing errors. *)
        Error err -> close_in fh ; raise (Error err)
  with
  (* Any errors when opening or closing a file are fatal. *)
    Sys_error msg -> fatal_error "%s" msg

let parser = Parser.file Lexer.token

let rec run_file_list cmdlst state = match cmdlst with
  | x::xs ->
    let result, newstate = Repl.run_one x state in
    [result]::run_file_list xs newstate
  | [] -> []

let run_file fn state =
  try
  run_file_list (read_file parser fn) state
  with
  | Error err -> print_error err; []
  | Sys.Break -> prerr_endline "Interrupted."; []
  | e -> print_error (Nowhere, "Error", (Printexc.to_string e)); []

let compile_file fn =
  (Jscompiler.compile_program (read_file parser fn)) ^ "\n"