(**************************************************************************)
(*  The CDuce compiler                                                    *)
(*  Alain Frisch <Alain.Frisch@inria.fr> and the CDuce team               *)
(*  Copyright CNRS,INRIA, 2003,2004 (see LICENSE for details)             *)
(**************************************************************************)

open Ident

let () = State.close ();;

let load_dump = ref None
let save_dump = ref None

let out_dir  = ref [] (* directory of the output file *)
let src  = ref []
let args = ref []

let compile = ref false
let run = ref false
let script = ref false

let version () =
  Printf.eprintf "CDuce, version %s\n" <:symbol<cduce_version>>;
  Printf.eprintf "built on %s\n" <:symbol<build_date>>;
  Printf.eprintf "using OCaml %s compiler\n" <:symbol<ocaml_compiler>>;
  Printf.eprintf "Supported features: \n";
  List.iter (fun (n,d) -> Printf.eprintf "- %s: %s\n" n d) (Config.descrs ());
  exit 0

let license () =
  Printf.eprintf "\n\
The CDuce interpreter is distributed under the terms of the Q Public \n\
License version 1.0 (included in the sources). The Choice of Law section\n\
been modified from the original Q Public.\n\n
"; 
  exit 0

let specs =
  [ "--compile", Arg.Set compile,
             "compile the given CDuce file";
    "--run", Arg.Set run,
         "    execute the given .cdo files";
    "--verbose", Arg.Set Cduce.verbose,
             "(for --compile) show types of exported values";
    "--obj-dir",  Arg.String (fun s -> out_dir := s :: !out_dir),
             "(for --compile) directory for the compiled .cdo file";
    "-I", Arg.String (fun s -> Librarian.obj_path := s::!Librarian.obj_path),
      "       add one directory to the lookup path for .cdo and .cmi files";
    "--stdin", Arg.Unit (fun () -> src := "" :: !src),
           "  read CDuce script on standard input";
    "--arg", Arg.Rest (fun s -> args := s :: !args),
         "    following arguments are passed to the CDuce program";
    "--script", Arg.Rest (fun s -> 
			    if not !script then (script := true;
						src := s :: !src)
			    else args := s :: !args),
            " the first argument after is the source, then the arguments";
    "--no", Arg.String Config.inhibit,
        "     disable a feature (cduce -v to get a list of features)";
    "--debug", Arg.Unit (fun () -> Stats.set_verbosity Stats.Summary),
           "  print profiling/debugging information";
    "-v", Arg.Unit version,
      "       print CDuce version, and list built-in optional features";
    "--version", Arg.Unit version,
             "print CDuce version, and list built-in optional features";
    "--license", Arg.Unit license,
             "print CDuce license";

    "--dump", Arg.String (fun s -> save_dump := Some s; load_dump := Some s), 
          "   (deprecated) specify persistency file for loading and saving";
    "--load", Arg.String (fun s -> load_dump := Some s), 
          "   (deprecated) load persistency file before running CDuce program";
    "--save", Arg.String (fun s -> save_dump := Some s), 
          "   (deprecated) save persistency file after running CDuce program";


 ]

let ppf = Format.std_formatter
let ppf_err = Format.err_formatter

let err s =
  prerr_endline s;
  exit 1

let mode () =
  Arg.parse (specs @ !Cduce.extra_specs) (fun s -> src := s :: !src) 
    "Usage:\ncduce [OPTIONS ...] [FILE ...] [--arg argument ...]\n\nOptions:";
  match (!compile,!out_dir,!run,!src,!args) with
    | false, _::_, _,  _, _   -> 
	err "--obj-dir option can be used only with --compile"
    | false, [], false, [],  args   -> `Toplevel args
    | false, [], false, [x], args   -> `Script (x,args)
    | false, [], false, _, _        ->
	err "Only one CDuce program can be executed at a time"
    | true,  [o], false, [x], []     -> `Compile (x,Some o) 
    | true,  [], false, [x], []     -> `Compile (x,None) 
    | true,  [], false, [], []      ->
	err "Please specify the CDuce program to be compiled"
    | true,  [], false, _, []       ->
	err "Only one CDuce program can be compiled at a time"
    | true,  _, false, _, []        ->
	err "Please specify only one output directory"
    | true,  _, false, _, _        ->
	err "No argument can be passed to programs at compile time"
    | false, _, true,  [x], args   -> `Run (x,args)
    | false, _, true,  [], _       ->
	err "Please specifiy the CDuce program to be executed"
    | false, _, true,   _, _       ->
	err "Only one CDuce program can be executed at a time"
    | true, _, true,   _,  _       ->
	err "The options --compile and --run are incompatible"
	


let bol = ref true

let outflush s =
  output_string stdout s;
  flush stdout

let toploop () =
  let restore = 
    try 
      let tcio = Unix.tcgetattr Unix.stdin in
      Unix.tcsetattr 
	Unix.stdin Unix.TCSADRAIN { tcio with Unix.c_vquit = '\004' };
      fun () -> Unix.tcsetattr Unix.stdin Unix.TCSADRAIN tcio
    with Unix.Unix_error (_,_,_) -> 
      fun () -> ()
  in
  let quit () = 
    outflush "\n";
    restore ();
    exit 0
  in
  Format.fprintf ppf "        CDuce version %s\n@." <:symbol<cduce_version>>;
  Sys.set_signal Sys.sigquit (Sys.Signal_handle (fun _ -> quit ()));
  Sys.catch_break true;
  Cduce.toplevel := true;
  Location.push_source `Stream;
  let read i =
    if !bol then 
      if !Ulexer.in_comment then outflush "* " else outflush "> ";
    try 
      let c = input_char stdin in
      bol := c = '\n';
      Some c
    with Sys.Break -> quit () 
  in
  let input = Stream.from read in
  let rec loop () =
    outflush "# ";
    bol := false;
    ignore (Cduce.topinput ppf ppf_err input);
    while (input_char stdin != '\n') do () done;
    loop () in
  (try loop () with End_of_file -> ());
  restore ()

let argv args = 
  Value.sequence (List.rev_map Value.string_latin1 args)

let restore () =
  match !load_dump with
    | Some f ->
	(try 
	   Format.fprintf ppf "Restoring state: ";
	   let chan = open_in_bin f in
	   let s = Marshal.from_channel chan in
	   close_in chan;
	   State.set s; 
	   Format.fprintf ppf "done ...@."
	 with Sys_error _ ->  
	   Format.fprintf ppf "failed ...@.")
    | None -> 
	()

let save () =
  match !save_dump with
    | Some f ->
	Format.fprintf ppf "Saving state ...@\n";
	let s = State.get () in
	let chan = open_out_bin f in
	Marshal.to_channel chan s [ Marshal.Closures ];
	close_out chan
    | None -> ()

let main () = 
  at_exit (fun () -> Stats.dump Format.std_formatter);
  Location.set_viewport (Html.create false);
  match mode () with
    | `Toplevel args ->
(*	Config.inhibit "ocaml"; *)
	Config.init_all ();
	Builtin.argv := argv args;
	restore ();
	toploop ();
	save ()
    | `Script (f,args) ->
	Config.init_all ();
	Builtin.argv := argv args;
	Cduce.compile_run f
    | `Compile (f,o) ->
	Config.init_all ();
	Cduce.compile f o
    | `Run (f,args) ->
	Config.init_all ();
	Builtin.argv := argv args;
	Cduce.run f
	 

