session_user_interface.ml 13.7 KB
Newer Older
1 2

open Format
Sylvain Dailler's avatar
Sylvain Dailler committed
3
open Session_itp
4
open Controller_itp
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

(* TODO: raise exceptions instead of using explicit eprintf/exit *)
let cont_from_files spec usage_str env files provers =
  if Queue.is_empty files then Whyconf.Args.exit_with_usage spec usage_str;
  let fname = Queue.peek files in
  (* extract project directory, and create it if needed *)
  let dir =
    if Filename.check_suffix fname ".why" ||
       Filename.check_suffix fname ".mlw"
    then Filename.chop_extension fname
    else let _ = Queue.pop files in fname
  in
  if Sys.file_exists dir then
    begin
      if not (Sys.is_directory dir) then
        begin
          Format.eprintf
            "[Error] @[When@ more@ than@ one@ file@ is@ given@ on@ the@ \
             command@ line@ the@ first@ one@ must@ be@ the@ directory@ \
             of@ the@ session.@]@.";
          Arg.usage spec usage_str; exit 1
        end
    end
  else
    begin
      eprintf "[GUI] '%s' does not exist. \
               Creating directory of that name for the project@." dir;
      Unix.mkdir dir 0o777
    end;
  (* we load the session *)
Sylvain Dailler's avatar
Sylvain Dailler committed
35
  let ses,use_shapes = load_session dir in
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
  eprintf "using shapes: %a@." pp_print_bool use_shapes;
  (* create the controller *)
  let c = Controller_itp.create_controller env ses in
 (* update the session *)
  Controller_itp.reload_files c env ~use_shapes;
  (* add files to controller *)
  Queue.iter (fun fname -> Controller_itp.add_file c fname) files;
  (* load provers drivers *)
  Whyconf.Mprover.iter
    (fun _ p ->
       try
         let d = Driver.load_driver env p.Whyconf.driver [] in
         Whyconf.Hprover.add c.Controller_itp.controller_provers p.Whyconf.prover (p,d)
       with e ->
         let p = p.Whyconf.prover in
         eprintf "Failed to load driver for %s %s: %a@."
           p.Whyconf.prover_name p.Whyconf.prover_version
           Exn_printer.exn_printer e)
    provers;
  (* return the controller *)
  c

58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
(**********************************)
(* list unproven goal and related *)
(**********************************)

let rec unproven_goals_below_tn cont acc tn =
  if tn_proved cont tn then
    acc                         (* we ignore "dead" goals *)
  else
    let sub_tasks = get_sub_tasks cont.controller_session tn in
    List.fold_left (unproven_goals_below_pn cont) acc sub_tasks

(* note that if goal is not proved and there is no transformation goal
   is returned *)
and unproven_goals_below_pn cont acc goal =
  if pn_proved cont goal then
    acc                         (* we ignore "dead" transformations *)
  else
    match get_transformations cont.controller_session goal with
    | [] -> goal :: acc
    | tns -> List.fold_left (unproven_goals_below_tn cont) acc tns

let unproven_goals_below_th cont acc th =
  if th_proved cont th then
    acc
  else
    let goals = theory_goals th in
    List.fold_left (unproven_goals_below_pn cont) acc goals

let unproven_goals_below_file cont file =
  if file_proved cont file then
    []
  else
    let theories = file.file_theories in
    List.fold_left (unproven_goals_below_th cont) [] theories

let unproven_goals_in_session cont =
  let files = get_files cont.controller_session in
  Stdlib.Hstr.fold (fun _key file acc ->
      let file_goals = unproven_goals_below_file cont file in
      List.rev_append file_goals acc)
    files []

let get_first_unproven_goal_around_pn_in_th cont pn =
  let ses = cont.controller_session in
  let rec look_around pn =
    match get_proof_parent ses pn with
    | Trans tn  ->
      begin match unproven_goals_below_tn cont [] tn with
        | [] -> look_around (get_trans_parent ses tn)
        | l  -> l
      end
    | Theory th -> unproven_goals_below_th cont [] th
  in
  match look_around pn with
  | [] -> None
  | l -> Some (List.hd (List.rev l))

(********************)
(* Terminal history *)
(********************)
118

119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
module type Historic_type = sig
  type historic

  val create_historic: unit -> historic
  val print_next_command: historic -> string option
  val print_prev_command: historic -> string option
  val add_command: historic -> string -> unit

end

module Historic : Historic_type = struct
  type 'a hole_list = 'a list * 'a list

  (* TODO this looks like we can make it more efficient either with imperative
     feature or by being more clever.  With DLlists, we could have added a
     command in O(1). *)
  let add e l =
    match l with
    | ll, lr ->  [], e :: (List.rev ll) @ lr

  let next l =
    match l with
    | ll, [] -> ll, []
    | ll, [hd] -> ll, [hd]
    (* Get acts on the right list so we never empty right list *)
    | ll, cur :: lr -> cur :: ll, lr

  let prev l =
    match l with
    | hd :: ll, lr -> ll, hd :: lr
    | [], lr -> [], lr

  let get l =
    match l with
    | _, hd :: _ -> Some hd
    | _, [] -> None

  type historic = {mutable lc : string hole_list;
                   mutable tr : bool}
(* tr is used to know what was the last query from user because cases for the
   first element of the historic and other elements is not the same *)

  let create_historic () : historic =
    {lc = [], [];
     tr = false}

  let get_current h =
    get h.lc

  let print_next_command h =
    if h.tr then
      begin
        h.lc <- next h.lc;
        get_current h
      end
    else
      begin
        let s = get_current h in
        h.tr <- true;
        s
      end

  let print_prev_command h =
    if h.tr then
      begin
        h.lc <- prev h.lc;
        get_current h
      end
    else
      None

  let add_command h e =
    h.lc <- add e h.lc;
    h.tr <- false

end
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224

(***************** strategies *****************)

let loaded_strategies = ref []

let strategies env config =
  match !loaded_strategies with
    | [] ->
      let strategies = Whyconf.get_strategies config in
      let strategies =
        Stdlib.Mstr.fold_left
          (fun acc _ st ->
            let name = st.Whyconf.strategy_name in
            try
              let code = st.Whyconf.strategy_code in
              let code = Strategy_parser.parse2 env config code in
              let shortcut = st.Whyconf.strategy_shortcut in
              Format.eprintf "[Why3shell] Strategy '%s' loaded.@." name;
              (name, shortcut, st.Whyconf.strategy_desc, code) :: acc
            with Strategy_parser.SyntaxError msg ->
              Format.eprintf
                "[Why3shell warning] Loading strategy '%s' failed: %s@." name msg;
              acc)
          []
          strategies
      in
      let strategies = List.rev strategies in
      loaded_strategies := strategies;
      strategies
    | l -> l
225 226 227 228 229 230


(**** interpretation of command-line *********************)

let sort_pair (x,_) (y,_) = String.compare x y

231
let list_transforms _cont _args =
232
  let l =
233 234 235
    List.rev_append
    (List.rev_append (Trans.list_transforms ()) (Trans.list_transforms_l ()))
    (List.rev_append (Trans.list_transforms_with_args ()) (Trans.list_transforms_with_args_l ()))
236 237 238 239 240 241 242
  in
  let print_trans_desc fmt (x,r) =
    fprintf fmt "@[<hov 2>%s@\n@[<hov>%a@]@]" x Pp.formatted r
  in
  Pp.string_of (Pp.print_list Pp.newline2 print_trans_desc)
               (List.sort sort_pair l)

243 244 245 246 247 248 249 250 251 252 253
let list_provers cont _args =
  let l =
    Whyconf.Hprover.fold
      (fun p _ acc -> (Pp.sprintf "%a" Whyconf.print_prover p)::acc)
      cont.Controller_itp.controller_provers
      []
  in
  let l = List.sort String.compare l in
  Pp.sprintf "%a" (Pp.print_list Pp.newline Pp.string) l


Sylvain Dailler's avatar
Sylvain Dailler committed
254 255 256 257 258 259
let find_any_id nt s =
  try (Stdlib.Mstr.find s nt.Theory.ns_pr).Decl.pr_name with
  | Not_found -> try (Stdlib.Mstr.find s nt.Theory.ns_ls).Term.ls_name with
    | Not_found -> (Stdlib.Mstr.find s nt.Theory.ns_ts).Ty.ts_name

(* The id you are trying to use is undefined *)
260
exception Undefined_id of string
Sylvain Dailler's avatar
Sylvain Dailler committed
261 262 263 264 265 266 267
(* Bad number of arguments *)
exception Number_of_arguments

let print_id s task =
  let tables = Args_wrapper.build_name_tables task in
  let km = tables.Args_wrapper.known_map in
  let id = try find_any_id tables.Args_wrapper.namespace s with
268
  | Not_found -> raise (Undefined_id s) in
Sylvain Dailler's avatar
Sylvain Dailler committed
269 270 271 272 273 274
  let d =
    try Ident.Mid.find id km with
    | Not_found -> raise Not_found (* Should not happen *)
  in
  Pp.string_of (Why3printer.print_decl tables) d

275
let print_id _cont task args =
Sylvain Dailler's avatar
Sylvain Dailler committed
276 277 278 279 280 281 282 283
  match args with
  | [s] -> print_id s task
  | _ -> raise Number_of_arguments

let search s task =
  let tables = Args_wrapper.build_name_tables task in
  let id_decl = tables.Args_wrapper.id_decl in
  let id = try find_any_id tables.Args_wrapper.namespace s with
284
  | Not_found -> raise (Undefined_id s) in
Sylvain Dailler's avatar
Sylvain Dailler committed
285 286 287 288 289 290
  let l =
    try Ident.Mid.find id id_decl with
    | Not_found -> raise Not_found (* Should not happen *)
  in
  Pp.string_of (Pp.print_list Pp.newline2 (Why3printer.print_decl tables)) l

291
let search_id _cont task args =
Sylvain Dailler's avatar
Sylvain Dailler committed
292 293 294
  match args with
  | [s] -> search s task
  | _ -> raise Number_of_arguments
295

296 297 298 299
type query =
  | Qnotask of (Controller_itp.controller -> string list -> string)
  | Qtask of (Controller_itp.controller -> Task.task -> string list -> string)

300 301
let commands =
  [
302 303
    "list-transforms", "list available transformations", Qnotask list_transforms;
    "list-provers", "list available provers", Qnotask list_provers;
304 305
(*
    "list-strategies", "list available strategies", list_strategies;
Sylvain Dailler's avatar
Sylvain Dailler committed
306
*)
307 308
    "print", "<s> print the declaration where s was defined", Qtask print_id;
    "search", "<s> print some declarations where s appear", Qtask search_id;
Sylvain Dailler's avatar
Sylvain Dailler committed
309
(*
310 311 312 313 314 315 316 317 318 319 320 321
    "r", "reload the session (test only)", test_reload;
    "rp", "replay", test_replay;
    "s", "save the current session", test_save_session;
    "ng", "go to the next goal", then_print (move_to_goal_ret_p next_node);
    "pg", "go to the prev goal", then_print (move_to_goal_ret_p prev_node);
    "gu", "go to the goal up",  then_print (move_to_goal_ret_p zipper_up);
    "gd", "go to the goal down",  then_print (move_to_goal_ret_p zipper_down);
    "gr", "go to the goal right",  then_print (move_to_goal_ret_p zipper_right);
    "gl", "go to the goal left",  then_print (move_to_goal_ret_p zipper_left)
 *)
  ]

MARCHE Claude's avatar
MARCHE Claude committed
322 323 324 325 326 327
let help_on_queries fmt () =
  let l = List.rev_map (fun (c,h,_) -> (c,h)) commands in
  let l = List.sort sort_pair l in
  let p fmt (c,help) = fprintf fmt "%20s : %s" c help in
  Format.fprintf fmt "%a" (Pp.print_list Pp.newline p) l

328 329 330 331 332 333
let commands_table = Stdlib.Hstr.create 17
let () =
  List.iter
    (fun (c,_,f) -> Stdlib.Hstr.add commands_table c f)
    commands

334 335 336 337 338 339
(* splits input string [s] into substrings separated by space
   spaces inside quotes or parentheses are not separator.
   implemented as a hardcoded automaton:

*)

340 341
let split_args s =
  let args = ref [] in
342
  let par_depth = ref 0 in
343
  let b = Buffer.create 17 in
344 345 346 347 348
  let push_arg () =
    let x = Buffer.contents b in
    if String.length x > 0 then (args := x :: !args; Buffer.clear b)
  in
  let push_char c = Buffer.add_char b c in
349 350 351 352
  let state = ref 0 in
  for i = 0 to String.length s - 1 do
    let c = s.[i] in
    match !state, c with
353 354 355 356 357 358 359
    | 0,' ' -> if !par_depth > 0 then push_char c else push_arg ()
    | 0,'(' -> incr par_depth; push_char c
    | 0,')' -> decr par_depth; push_char c
    | 0,'"' -> state := 1; if !par_depth > 0 then push_char c
    | 0,_ -> push_char c
    | 1,'"' -> state := 0; if !par_depth > 0 then push_char c
    | 1,_ -> push_char c
360 361
    | _ -> assert false
  done;
362
  push_arg ();
363 364 365 366 367 368 369 370 371
  match List.rev !args with
    | a::b -> a,b
    | [] -> "",[]

type command =
  | Transform of string * Trans.gentrans * string list
  | Query of string
  | Other of string * string list

372
let interp cont id s =
373 374 375
  let cmd,args = split_args s in
  try
    let f = Stdlib.Hstr.find commands_table cmd in
376 377 378 379 380
    match f,id with
    | Qnotask f, _ -> Query (f cont args)
    | Qtask _, None -> Query "please select a goal first"
    | Qtask f, Some id ->
       let task = Session_itp.get_task cont.Controller_itp.controller_session id in
381 382 383 384
       let s = try Query (f cont task args) with
       | Undefined_id s -> Query ("No existing id corresponding to " ^ s)
       | Number_of_arguments -> Query "Bad number of arguments"
       in s
385
  with Not_found ->
MARCHE Claude's avatar
MARCHE Claude committed
386
    try
387
      let t = Trans.lookup_trans cont.Controller_itp.controller_env cmd in
MARCHE Claude's avatar
MARCHE Claude committed
388 389 390
      Transform (cmd,t,args)
    with Trans.UnknownTrans _ ->
      Other(cmd,args)
391 392 393 394 395 396 397 398 399 400 401 402 403 404


(********* Callbacks tools *******)

(* Return the prover corresponding to given name. name is of the form
  | name
  | name, version
  | name, altern
  | name, version, altern *)
let return_prover name config =
  let fp = Whyconf.parse_filter_prover name in
  (** all provers that have the name/version/altern name *)
  let provers = Whyconf.filter_provers config fp in
  if Whyconf.Mprover.is_empty provers then begin
405
    (*Format.eprintf "Prover corresponding to %s has not been found@." name;*)
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
    None
  end else
    Some (snd (Whyconf.Mprover.choose provers))

(* Parses the Other command. If it fails to parse it, it answers None otherwise
   it returns the config of the prover together with the ressource_limit *)
let parse_prover_name config name args :
  (Whyconf.config_prover * Call_provers.resource_limit) option =
  let main = Whyconf.get_main config in
  match (return_prover name config) with
  | None -> None
  | Some prover_config ->
    begin
      if (List.length args > 2) then None else
      match args with
      | [] ->
        let default_limit = Call_provers.{limit_time = Whyconf.timelimit main;
                                          limit_mem = Whyconf.memlimit main;
                                          limit_steps = 0} in
          Some (prover_config, default_limit)
      | [timeout] -> Some (prover_config,
                           Call_provers.{empty_limit with
                                         limit_time = int_of_string timeout})
      | [timeout; oom ] ->
        Some (prover_config, Call_provers.{limit_time = int_of_string timeout;
                                           limit_mem = int_of_string oom;
                                           limit_steps = 0})
433
      | _ -> (*Format.eprintf "Parse_prover_name. Should not happen. Please report@."; *) None
434
    end