controller_itp.ml 28.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
(********************************************************************)
(*                                                                  *)
(*  The Why3 Verification Platform   /   The Why3 Development Team  *)
(*  Copyright 2010-2017   --   INRIA - CNRS - Paris-Sud University  *)
(*                                                                  *)
(*  This software is distributed under the terms of the GNU Lesser  *)
(*  General Public License version 2.1, with the special exception  *)
(*  on linking described in file LICENSE.                           *)
(*                                                                  *)
(********************************************************************)

12
open Format
Clément Fumex's avatar
Clément Fumex committed
13 14
open Session_itp

Sylvain Dailler's avatar
Sylvain Dailler committed
15 16 17 18
let debug_sched = Debug.register_info_flag "scheduler"
  ~desc:"Print@ debugging@ messages@ about@ scheduling@ of@ prover@ calls@ \
         and@ transformation@ applications."

Sylvain Dailler's avatar
Sylvain Dailler committed
19
let debug_call_prover = Debug.lookup_flag "call_prover"
20 21
let default_delay_ms = 100 (* 0.1 seconds *)

Sylvain Dailler's avatar
Sylvain Dailler committed
22

23 24
exception Noprogress

25 26 27
let () = Exn_printer.register
    (fun fmt e ->
      match e with
Sylvain Dailler's avatar
Sylvain Dailler committed
28 29
      | Noprogress ->
          Format.fprintf fmt "The transformation made no progress.\n"
30 31
      | _ -> raise e)

Clément Fumex's avatar
Clément Fumex committed
32 33 34 35 36 37 38 39 40
(** State of a proof *)
type proof_attempt_status =
    | Unedited (** editor not yet run for interactive proof *)
    | JustEdited (** edited but not run yet *)
    | Interrupted (** external proof has never completed *)
    | Scheduled (** external proof attempt is scheduled *)
    | Running (** external proof attempt is in progress *)
    | Done of Call_provers.prover_result (** external proof done *)
    | InternalFailure of exn (** external proof aborted by internal error *)
41
    | Uninstalled of Whyconf.prover (** prover is uninstalled *)
Clément Fumex's avatar
Clément Fumex committed
42

MARCHE Claude's avatar
MARCHE Claude committed
43 44
let print_status fmt st =
  match st with
Sylvain Dailler's avatar
Sylvain Dailler committed
45 46 47 48 49 50 51 52 53 54 55
  | Unedited          -> fprintf fmt "Unedited"
  | JustEdited        -> fprintf fmt "JustEdited"
  | Interrupted       -> fprintf fmt "Interrupted"
  | Scheduled         -> fprintf fmt "Scheduled"
  | Running           -> fprintf fmt "Running"
  | Done r            ->
      fprintf fmt "Done(%a)" Call_provers.print_prover_result r
  | InternalFailure e ->
      fprintf fmt "InternalFailure(%a)" Exn_printer.exn_printer e
  | Uninstalled pr    ->
      fprintf fmt "Prover %a is uninstalled" Whyconf.print_prover pr
MARCHE Claude's avatar
MARCHE Claude committed
56 57

type transformation_status =
58
  | TSscheduled | TSdone of transID | TSfailed of (proofNodeID * exn)
59 60 61 62

let print_trans_status fmt st =
  match st with
  | TSscheduled -> fprintf fmt "TScheduled"
63
  | TSdone _tid -> fprintf fmt "TSdone" (* TODO print tid *)
64
  | TSfailed _e -> fprintf fmt "TSfailed"
Clément Fumex's avatar
Clément Fumex committed
65

66 67 68 69
type strategy_status = STSgoto of proofNodeID * int | STShalt

let print_strategy_status fmt st =
  match st with
Sylvain Dailler's avatar
Sylvain Dailler committed
70 71
  | STSgoto(id,n) ->
      fprintf fmt "goto step %d in proofNode %a" n print_proofNodeID id
72 73 74
  | STShalt -> fprintf fmt "halt"


75
type controller =
Sylvain Dailler's avatar
Sylvain Dailler committed
76
  { mutable controller_session: Session_itp.session;
77
    controller_config : Whyconf.config;
Sylvain Dailler's avatar
Sylvain Dailler committed
78 79 80
    controller_env: Env.env;
    controller_provers:
      (Whyconf.config_prover * Driver.driver) Whyconf.Hprover.t;
81 82
  }

83

84
let create_controller config env ses =
85 86
  let c =
    {
87
      controller_session = ses;
88 89 90 91 92 93 94 95 96
      controller_config = config;
      controller_env = env;
      controller_provers = Whyconf.Hprover.create 7;
    }
  in
  let provers = Whyconf.get_provers config in
  Whyconf.Mprover.iter
    (fun _ p ->
     try
97
       let d = Whyconf.load_driver (Whyconf.get_main config) env p.Whyconf.driver [] in
98 99
       Whyconf.Hprover.add c.controller_provers p.Whyconf.prover (p,d)
     with e ->
Sylvain Dailler's avatar
Sylvain Dailler committed
100
       Debug.dprintf debug_call_prover
101 102 103 104 105 106
         "[Controller_itp] error while loading driver for prover %a: %a@."
         Whyconf.print_prover p.Whyconf.prover
         Exn_printer.exn_printer e)
    provers;
  c

Sylvain Dailler's avatar
Sylvain Dailler committed
107
let remove_subtree c = Session_itp.remove_subtree c.controller_session
108

109 110 111
(* Get children of any without proofattempts *)
let get_undetached_children_no_pa s any : any list =
  match any with
112
  | AFile f -> List.map (fun th -> ATh th) (file_theories f)
113 114 115
  | ATh th  -> List.map (fun g -> APn g) (theory_goals th)
  | ATn tn  -> List.map (fun pn -> APn pn) (get_sub_tasks s tn)
  | APn pn  -> List.map (fun tn -> ATn tn) (get_transformations s pn)
Sylvain Dailler's avatar
Sylvain Dailler committed
116
  | APa _ -> []
117

118 119


120 121 122 123 124 125 126 127 128 129 130 131
(* printing *)

module PSession = struct

  open Stdlib

  type any =
    | Session
    | File of file
    | Theory of theory
    | Goal of proofNodeID
    | Transf of transID
132
    | ProofAttempt of proof_attempt_node
133 134 135 136 137 138 139 140 141 142

  type 'a t = { tcont : controller;
                tkind : any }

  let decomp x =
    let s = x.tcont.controller_session in
    let n y acc = { x with tkind = y } :: acc in
    match x.tkind with
    | Session -> "", Hstr.fold (fun _ f -> n (File f)) (get_files s) []
    | File f ->
143
       (file_name f),
Sylvain Dailler's avatar
Sylvain Dailler committed
144 145
       List.fold_right
          (fun th -> n (Theory th))
146 147
          (file_detached_theories f)
          (List.fold_right (fun th -> n (Theory th)) (file_theories f) [])
148 149 150
    | Theory th ->
       let id = theory_name th in
       let name = id.Ident.id_string in
151
       let name = if th_proved s th then name^"!" else name^"?" in
152
       name,
Sylvain Dailler's avatar
Sylvain Dailler committed
153 154 155 156
       List.fold_right
         (fun g -> n (Goal g))
         (theory_goals th)
         (List.fold_right (fun g -> n (Goal g)) (theory_detached_goals th) [])
157 158 159
    | Goal id ->
       let gid = get_proof_name s id in
       let name = gid.Ident.id_string in
160
       let name = if pn_proved s id then name^"!" else name^"?" in
161 162 163 164 165 166 167
       let pas = get_proof_attempts s id in
       let trs = get_transformations s id in
       name,
       List.fold_right (fun g -> n (Transf g)) trs
                       (List.fold_right (fun g -> n (ProofAttempt g)) pas [])
    | ProofAttempt pa ->
       Pp.sprintf_wnl "%a%s%s"
Sylvain Dailler's avatar
Sylvain Dailler committed
168 169 170 171 172
          Whyconf.print_prover pa.prover
          (match pa.Session_itp.proof_state with
          | Some { Call_provers.pr_answer = Call_provers.Valid} -> ""
          | _ -> "?")
          (if pa.proof_obsolete then "O" else ""), []
173 174
    | Transf id ->
       let name = get_transf_name s id in
175
       let name = if tn_proved s id then name^"!" else name^"?" in
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
       let sts = get_sub_tasks s id in
       let dsts = get_detached_sub_tasks s id in
       name,
       List.fold_right (fun g -> n (Goal g)) sts
                       (List.fold_right (fun g -> n (Goal g)) dsts [])

end

module P = Print_tree.PMake(PSession)

let print_session fmt c =
  P.print fmt { PSession.tcont = c; PSession.tkind = PSession.Session }

(*********)



193 194 195 196 197 198

(** reload files, associating old proof attempts and transformations
    to the new goals.  old theories and old goals for which we cannot
    find a corresponding new theory resp. old goal are kept, with
    tasks associated to them *)

199
let reload_files (c : controller) ~use_shapes =
200
  let old_ses = c.controller_session in
Sylvain Dailler's avatar
Sylvain Dailler committed
201 202
  c.controller_session <-
    empty_session ~shape_version:(get_shape_version old_ses) (get_dir old_ses);
203
  try
204
    merge_files ~use_shapes c.controller_env c.controller_session old_ses
205 206 207
  with e ->
    c.controller_session <- old_ses;
    raise e
208 209

let add_file c ?format fname =
210 211 212
  let theories = Session_itp.read_file c.controller_env ?format fname in
  let (_ : file) = add_file_section c.controller_session fname theories format in
  ()
213

214 215 216 217 218 219

module type Scheduler = sig
  val timeout: ms:int -> (unit -> bool) -> unit
  val idle: prio:int -> (unit -> bool) -> unit
end

220 221
module Make(S : Scheduler) = struct

MARCHE Claude's avatar
MARCHE Claude committed
222 223 224 225 226 227 228 229
let scheduled_proof_attempts = Queue.create ()

let prover_tasks_in_progress = Queue.create ()

let timeout_handler_running = ref false

let max_number_of_running_provers = ref 1

230 231 232 233
let set_max_tasks n =
  max_number_of_running_provers := n;
  Prove_client.set_max_running_provers n

MARCHE Claude's avatar
MARCHE Claude committed
234
let number_of_running_provers = ref 0
235

236 237 238 239
let observer = ref (fun _ _ _ -> ())

let register_observer = (:=) observer

240
module Hprover = Whyconf.Hprover
MARCHE Claude's avatar
MARCHE Claude committed
241

242
let build_prover_call ?proof_script ~cntexample c id pr limit callback =
243 244
  let (config_pr,driver) = Hprover.find c.controller_provers pr in
  let command =
Sylvain Dailler's avatar
Sylvain Dailler committed
245 246 247
    Whyconf.get_complete_command
      config_pr
      ~with_steps:Call_provers.(limit.limit_steps <> empty_limit.limit_steps) in
248
  let task = Session_itp.get_raw_task c.controller_session id in
249
  let call =
250
    Driver.prove_task ?old:proof_script ~cntexample:cntexample ~inplace:false ~command
251
                      ~limit (*?name_table:table*) driver task
252
  in
253
  let pa = (c.controller_session,id,pr,proof_script,callback,false,call) in
MARCHE Claude's avatar
MARCHE Claude committed
254 255 256 257 258 259
  Queue.push pa prover_tasks_in_progress

let timeout_handler () =
  (* examine all the prover tasks in progress *)
  let q = Queue.create () in
  while not (Queue.is_empty prover_tasks_in_progress) do
260
    let (ses,id,pr,pr_script,callback,started,call) as c =
Sylvain Dailler's avatar
Sylvain Dailler committed
261
      Queue.pop prover_tasks_in_progress in
262
    match Call_provers.query_call call with
MARCHE Claude's avatar
MARCHE Claude committed
263 264 265 266 267
    | Call_provers.NoUpdates -> Queue.add c q
    | Call_provers.ProverStarted ->
       assert (not started);
       callback Running;
       incr number_of_running_provers;
268 269
       Queue.add (ses,id,pr,pr_script,callback,true,call) q
    | Call_provers.ProverFinished res when pr_script = None ->
MARCHE Claude's avatar
MARCHE Claude committed
270
       if started then decr number_of_running_provers;
271 272 273
       (* update the session *)
       update_proof_attempt ses id pr res;
       (* inform the callback *)
MARCHE Claude's avatar
MARCHE Claude committed
274
       callback (Done res)
275 276 277 278 279 280
    | Call_provers.ProverFinished res (* when pr_script <> None *) ->
       if started then decr number_of_running_provers;
       (* update the session *)
       update_proof_attempt ~obsolete:true ses id pr res;
       (* inform the callback *)
       callback (Done res)
281 282 283 284 285 286 287 288
    | Call_provers.ProverInterrupted ->
       if started then decr number_of_running_provers;
       (* inform the callback *)
       callback (Interrupted)
    | Call_provers.InternalFailure exn ->
       if started then decr number_of_running_provers;
       (* inform the callback *)
       callback (InternalFailure (exn))
MARCHE Claude's avatar
MARCHE Claude committed
289 290
  done;
  Queue.transfer q prover_tasks_in_progress;
291
  (* if the number of prover tasks is less than 3 times the maximum
MARCHE Claude's avatar
MARCHE Claude committed
292 293
     number of running provers, then we heuristically decide to add
     more tasks *)
294 295 296 297
  begin
    try
      for _i = Queue.length prover_tasks_in_progress
          to 3 * !max_number_of_running_provers do
298
        let (c,id,pr,limit,proof_script,callback,cntexample) = Queue.pop scheduled_proof_attempts in
299
        try
300
          build_prover_call ?proof_script ~cntexample c id pr limit callback
301
        with e when not (Debug.test_flag Debug.stack_trace) ->
302
          (*Format.eprintf
303
            "@[Exception raised in Controller_itp.build_prover_call:@ %a@.@]"
304
            Exn_printer.exn_printer e;*)
305 306 307 308 309 310 311 312 313
          callback (InternalFailure e)
      done
  with Queue.Empty -> ()
  end;
  let scheduled = Queue.length scheduled_proof_attempts in
  let waiting_or_running = Queue.length prover_tasks_in_progress in
  let running = !number_of_running_provers in
  !observer scheduled (waiting_or_running - running) running;
  true
MARCHE Claude's avatar
MARCHE Claude committed
314

315 316
let interrupt () =
  while not (Queue.is_empty prover_tasks_in_progress) do
317
    let (_ses,_id,_pr,_proof_script,callback,_started,_call) =
318 319 320 321 322 323
      Queue.pop prover_tasks_in_progress in
    (* TODO: apply some Call_provers.interrupt_call call *)
    callback Interrupted
  done;
  number_of_running_provers := 0;
  while not (Queue.is_empty scheduled_proof_attempts) do
324
    let (_c,_id,_pr,_limit,_proof_script,callback,_cntexample) = Queue.pop scheduled_proof_attempts in
325 326 327 328
    callback Interrupted
  done;
  !observer 0 0 0

MARCHE Claude's avatar
MARCHE Claude committed
329 330 331 332
let run_timeout_handler () =
  if not !timeout_handler_running then
    begin
      timeout_handler_running := true;
333
      S.timeout ~ms:default_delay_ms timeout_handler;
MARCHE Claude's avatar
MARCHE Claude committed
334 335
    end

336
let schedule_proof_attempt_r ?proof_script c id pr ~counterexmp ~limit ~callback =
337
  let panid =
338
    graft_proof_attempt c.controller_session id pr ~limit
339
  in
340 341
  Queue.add (c,id,pr,limit,proof_script,callback panid,counterexmp)
            scheduled_proof_attempts;
342
  callback panid Scheduled;
MARCHE Claude's avatar
MARCHE Claude committed
343
  run_timeout_handler ()
Clément Fumex's avatar
Clément Fumex committed
344

345 346
let schedule_proof_attempt ?proof_script c id pr
                           ~counterexmp ~limit ~callback ~notification =
Sylvain Dailler's avatar
Sylvain Dailler committed
347
  let callback panid s = callback panid s;
Sylvain Dailler's avatar
Sylvain Dailler committed
348
    (match s with
349 350 351 352
    | Scheduled | Running -> update_goal_node notification c.controller_session id
    | Done res ->
        update_proof_attempt ~obsolete:false c.controller_session id pr res;
        update_goal_node notification c.controller_session id
Sylvain Dailler's avatar
Sylvain Dailler committed
353
    | _ -> ())
354
  in
355 356
  (* proof_script is specific to interactive manual provers *)
  let session_dir = Session_itp.get_dir c.controller_session in
357 358 359
  let proof_script =
    Opt.map (Sysutil.absolutize_filename session_dir) proof_script
  in
360
  schedule_proof_attempt_r ?proof_script c id pr ~counterexmp ~limit ~callback
361

362
(* TODO to be simplified *)
Sylvain Dailler's avatar
Sylvain Dailler committed
363 364 365
(* create the path to a file for saving the external proof script *)
let create_file_rel_path c pr pn =
  let session = c.controller_session in
366
  let driver = snd (Hprover.find c.controller_provers pr) in
367
  let task = Session_itp.get_raw_task session pn in
Sylvain Dailler's avatar
Sylvain Dailler committed
368 369 370 371
  let session_dir = Session_itp.get_dir session in
  let th = get_encapsulating_theory session (APn pn) in
  let th_name = (Session_itp.theory_name th).Ident.id_string in
  let f = get_encapsulating_file session (ATh th) in
372
  let fn = Filename.chop_extension (Filename.basename (file_name f)) in
Sylvain Dailler's avatar
Sylvain Dailler committed
373 374 375 376 377 378 379 380
  let file = Driver.file_of_task driver fn th_name task in
  let file = Filename.concat session_dir file in
  let file = Sysutil.uniquify file in
  let file = Sysutil.relativize_filename session_dir file in
  file

let update_edit_external_proof c pn ?panid pr =
  let session = c.controller_session in
381
  let driver = snd (Hprover.find c.controller_provers pr) in
382
  let task = Session_itp.get_raw_task session pn in
Sylvain Dailler's avatar
Sylvain Dailler committed
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
  let session_dir = Session_itp.get_dir session in
  let file =
    match panid with
    | None ->
        create_file_rel_path c pr pn
    | Some panid ->
        let pa = get_proof_attempt_node session panid in
        Opt.get pa.proof_script
  in
  let file = Filename.concat session_dir file in
  let old =
    if Sys.file_exists file
    then
      begin
        let backup = file ^ ".bak" in
        if Sys.file_exists backup
        then Sys.remove backup;
        Sys.rename file backup;
        Some(open_in backup)
      end
    else None
  in
  let ch = open_out file in
  let fmt = formatter_of_out_channel ch in
  (* Name table is only used in ITP printing *)
  Driver.print_task ~cntexample:false ?old driver fmt task;
  Opt.iter close_in old;
  close_out ch;
  file

413 414 415 416 417 418 419 420
let replay_proof_attempt ?proof_script c pr limit (parid: proofNodeID) id ~callback ~notification =
  (* The replay can be done on a different machine so we need
     to check more things before giving the attempt to the scheduler *)
  if not (Hprover.mem c.controller_provers pr) then
    callback id (Uninstalled pr)
  else
    schedule_proof_attempt ?proof_script c parid pr ~counterexmp:false ~limit ~callback ~notification

Sylvain Dailler's avatar
Sylvain Dailler committed
421 422
exception Editor_not_found

Sylvain Dailler's avatar
Sylvain Dailler committed
423
let schedule_edition c id pr ~no_edit ~do_check_proof ?file ~callback ~notification =
Sylvain Dailler's avatar
Sylvain Dailler committed
424 425 426 427 428 429 430
  Debug.dprintf debug_sched "[Sched] Scheduling an edition@.";
  let config = c.controller_config in
  let session = c.controller_session in
  let prover_conf = Whyconf.get_prover_config config pr in
  let session_dir = Session_itp.get_dir session in

  let limit = Call_provers.empty_limit in
431
  (* Make sure editor exists. Fails otherwise *)
Sylvain Dailler's avatar
Sylvain Dailler committed
432 433
  let editor =
    match prover_conf.Whyconf.editor with
434
    | "" -> raise Editor_not_found
Sylvain Dailler's avatar
Sylvain Dailler committed
435 436 437
    | s ->
        try
          let ed = Whyconf.editor_by_id config s in
438 439
          String.concat " " (ed.Whyconf.editor_command ::
                             ed.Whyconf.editor_options)
440
        with Not_found -> raise Editor_not_found
Sylvain Dailler's avatar
Sylvain Dailler committed
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
  in
  let proof_attempts_id = get_proof_attempt_ids session id in
  let panid =
    try Some (Hprover.find proof_attempts_id pr) with
    | _ -> None
  in
  (* make sure to actually create the file and the proof attempt *)
  let panid, file =
    match panid, file with
    | None, None ->
        let file = update_edit_external_proof c id pr in
        let filename = Sysutil.relativize_filename session_dir file in
        let panid = graft_proof_attempt c.controller_session id pr ~file:filename ~limit in
        panid, file
    | None, Some file ->
        let panid = graft_proof_attempt c.controller_session id pr ~file ~limit in
        let file = update_edit_external_proof c id ~panid pr in
        panid, file
    | Some panid, _ ->
        let file = update_edit_external_proof c id ~panid pr in
        panid, file
  in

464 465 466 467
  (* Notification node *)
  let callback panid s = callback panid s;
    match s with
    | Scheduled | Running -> update_goal_node notification c.controller_session id
Sylvain Dailler's avatar
Sylvain Dailler committed
468 469 470 471 472 473 474 475 476 477 478 479
    | Done _ ->
        (* TODO *)
        if do_check_proof then
          let file = Sysutil.relativize_filename session_dir file in
          replay_proof_attempt ~proof_script:file c pr Call_provers.empty_limit id
            panid ~callback ~notification
    | Interrupted | InternalFailure _ ->
        (* TODO *)
        if do_check_proof then
          let file = Sysutil.relativize_filename session_dir file in
          replay_proof_attempt ~proof_script:file c pr Call_provers.empty_limit id
            panid ~callback ~notification
480 481 482
    | _ -> ()
  in

Sylvain Dailler's avatar
Sylvain Dailler committed
483 484
  Debug.dprintf debug_sched "[Editing] goal %s with command '%s' on file %s@."
    (Session_itp.get_proof_name session id).Ident.id_string
485
    editor file;
Sylvain Dailler's avatar
Sylvain Dailler committed
486 487 488 489 490 491 492 493 494 495 496 497 498 499
  if no_edit then
    begin
      callback panid Running;
      callback panid Interrupted
    end
  else
    begin
      let call = Call_provers.call_editor ~command:editor file in
      callback panid Running;
      let file = Sysutil.relativize_filename session_dir file in
      Queue.add (c.controller_session,id,pr,Some file,callback panid,false,call)
        prover_tasks_in_progress;
      run_timeout_handler ()
    end
500

Sylvain Dailler's avatar
Sylvain Dailler committed
501

502
let schedule_transformation_r c id name args ~callback =
503
  let apply_trans () =
504 505
    (* TODO: use get_raw_task instead, and make only the needed intros
       or alternatively, use 'revert' *)
506
(*
507
    let task,table = get_task c.controller_session id in
508 509 510 511 512
 *)
 (*
   let task = get_raw_task c.controller_session id in
    let table = Args_wrapper.build_naming_tables task in
  *)
513 514
    begin
      try
515 516 517 518
        let task, subtasks =
          apply_trans_to_goal c.controller_session c.controller_env name args id
        in
(*
519
          Trans.apply_transform_args name c.controller_env args table task in
520
 *)
521 522 523 524
        (* if result is same as input task, consider it as a failure *)
        begin
          match subtasks with
          | [t'] when Task.task_equal t' task ->
525
             callback (TSfailed (id, Noprogress))
526 527 528 529 530
          | _ ->
             let tid = graft_transf c.controller_session id name args subtasks in
             callback (TSdone tid)
        end
      with e when not (Debug.test_flag Debug.stack_trace) ->
531
        (* Format.eprintf
532
          "@[Exception raised in Trans.apply_transform %s:@ %a@.@]"
533
          name Exn_printer.exn_printer e; TODO *)
534
        callback (TSfailed (id, e))
535 536
    end;
    false
537 538 539
  in
  S.idle ~prio:0 apply_trans;
  callback TSscheduled
Clément Fumex's avatar
Clément Fumex committed
540

541
let schedule_transformation c id name args ~callback ~notification =
542
  let callback s = callback s; (match s with
543
      | TSdone tid -> update_trans_node notification c.controller_session tid
544
      | TSfailed _e -> ()
545
      | _ -> ()) in
546 547 548 549
  schedule_transformation_r c id name args ~callback

open Strategy

Sylvain Dailler's avatar
Sylvain Dailler committed
550
let run_strategy_on_goal
551
    c id strat ~counterexmp ~callback_pa ~callback_tr ~callback ~notification =
552 553 554 555 556 557
  let rec exec_strategy pc strat g =
    if pc < 0 || pc >= Array.length strat then
      callback STShalt
    else
      match Array.get strat pc with
      | Icall_prover(p,timelimit,memlimit) ->
MARCHE Claude's avatar
MARCHE Claude committed
558 559
         let callback panid res =
           callback_pa panid res;
560 561 562 563 564
           match res with
           | Scheduled | Running -> (* nothing to do yet *) ()
           | Done { Call_provers.pr_answer = Call_provers.Valid } ->
              (* proof succeeded, nothing more to do *)
              callback STShalt
565 566
           | Interrupted | InternalFailure _ ->
              callback STShalt
567 568 569 570 571
           | Done _ ->
              (* proof did not succeed, goto to next step *)
              callback (STSgoto (g,pc+1));
              let run_next () = exec_strategy (pc+1) strat g; false in
              S.idle ~prio:0 run_next
572
           | Unedited | JustEdited | Uninstalled _ ->
573 574 575 576 577 578
                         (* should not happen *)
                         assert false
         in
         let limit = { Call_provers.empty_limit with
                       Call_provers.limit_time = timelimit;
                       limit_mem  = memlimit} in
579
         schedule_proof_attempt c g p ~counterexmp ~limit ~callback ~notification
580 581
      | Itransform(trname,pcsuccess) ->
         let callback ntr =
582
           callback_tr trname [] ntr;
583
           match ntr with
584
           | TSfailed _e -> (* transformation failed *)
585 586 587 588 589 590 591 592 593 594 595 596
              callback (STSgoto (g,pc+1));
              let run_next () = exec_strategy (pc+1) strat g; false in
              S.idle ~prio:0 run_next
           | TSscheduled -> ()
           | TSdone tid ->
              List.iter
                (fun g ->
                 callback (STSgoto (g,pcsuccess));
                 let run_next () =
                   exec_strategy pcsuccess strat g; false
                 in
                 S.idle ~prio:0 run_next)
MARCHE Claude's avatar
MARCHE Claude committed
597
                (get_sub_tasks c.controller_session tid)
598
         in
599
         schedule_transformation c g trname [] ~callback ~notification
600 601 602 603 604 605
      | Igoto pc ->
         callback (STSgoto (g,pc));
         exec_strategy pc strat g
  in
  exec_strategy 0 strat id

Sylvain Dailler's avatar
Sylvain Dailler committed
606 607
let schedule_pa_with_same_arguments
    c (pa: proof_attempt_node) (pn: proofNodeID) ~callback ~notification =
Sylvain Dailler's avatar
Sylvain Dailler committed
608 609 610 611
  let prover = pa.prover in
  let limit = pa.limit in
  schedule_proof_attempt c pn prover ~limit ~callback ~notification

Sylvain Dailler's avatar
Sylvain Dailler committed
612 613
let schedule_tr_with_same_arguments
    c (tr: transID) (pn: proofNodeID) ~callback ~notification =
Sylvain Dailler's avatar
Sylvain Dailler committed
614 615 616
  let s = c.controller_session in
  let args = get_transf_args s tr in
  let name = get_transf_name s tr in
617
  let callback = callback name args in
Sylvain Dailler's avatar
Sylvain Dailler committed
618 619
  schedule_transformation c pn name args ~callback ~notification

620 621 622
let clean_session c ~removed =
  (* clean should not change proved status *)
  let notification _ = assert false in
623
  let s = c.controller_session in
624 625 626 627 628
  (* This function is applied on leafs first for the case of removes *)
  Session_itp.fold_all_session s
    (fun () any ->
      (match any with
      | APa pa ->
629 630
        let pa = Session_itp.get_proof_attempt_node s pa in
        if pn_proved s pa.parent then
631 632 633
          (match pa.Session_itp.proof_state with
          | None -> ()
          | Some pr ->
634 635 636
           if pa.Session_itp.proof_obsolete ||
                Call_provers.(pr.pr_answer <> Valid)
           then
Sylvain Dailler's avatar
Sylvain Dailler committed
637
             Session_itp.remove_subtree ~notification ~removed s any)
638
      | ATn tn ->
639 640
        let pn = get_trans_parent s tn in
        if pn_proved s pn && not (tn_proved s tn) then
Sylvain Dailler's avatar
Sylvain Dailler committed
641
          Session_itp.remove_subtree s ~notification ~removed (ATn tn)
642
      | _ -> ())) ()
643

644 645
(* This function folds on any subelements of given node and tries to mark all
   proof attempts it encounters *)
646
let mark_as_obsolete ~notification c any =
647
  let s = c.controller_session in
648
  (* Case for proof attempt only *)
649
  let mark_as_obsolete_pa n =
650 651
    let parent = get_proof_attempt_parent s n in
    Session_itp.mark_obsolete s n;
652
    notification (APa n);
653
    update_goal_node notification s parent
654 655 656
  in
  fold_all_any s
    (fun () any -> match any with
657
    | APa n -> mark_as_obsolete_pa n
658
    | _ -> ()) () any
659

Sylvain Dailler's avatar
Sylvain Dailler committed
660 661 662 663 664 665 666 667 668 669 670 671 672 673
exception BadCopyPaste

(* Reproduce the transformation made on node on an other one *)
let rec copy_paste ~notification ~callback_pa ~callback_tr c from_any to_any =
  let s = c.controller_session in
  if (not (is_below s from_any to_any) &&
      not (is_below s to_any from_any)) then
    match from_any, to_any with
    | AFile _, AFile _ ->
        raise BadCopyPaste
    | ATh _from_th, ATh _to_th ->
        raise BadCopyPaste
    | APn from_pn, APn to_pn ->
      let from_pa_list = get_proof_attempts s from_pn in
674
      List.iter (fun x -> schedule_pa_with_same_arguments c x to_pn ~counterexmp:false
Sylvain Dailler's avatar
Sylvain Dailler committed
675 676
          ~callback:callback_pa ~notification) from_pa_list;
      let from_tr_list = get_transformations s from_pn in
677
      let callback x tr args st = callback_tr tr args st;
Sylvain Dailler's avatar
Sylvain Dailler committed
678
        match st with
Sylvain Dailler's avatar
Sylvain Dailler committed
679 680
        | TSdone tid ->
          copy_paste c (ATn x) (ATn tid) ~notification ~callback_pa ~callback_tr
Sylvain Dailler's avatar
Sylvain Dailler committed
681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700
        | _ -> ()
      in
      List.iter (fun x -> schedule_tr_with_same_arguments c x to_pn
          ~callback:(callback x) ~notification) from_tr_list
    | ATn from_tn, ATn to_tn ->
        let from_tn_list = get_sub_tasks s from_tn in
        let to_tn_list = get_sub_tasks s to_tn in
        if (List.length from_tn_list = List.length to_tn_list) then
          List.iter2 (fun x y -> copy_paste c (APn x) (APn y)
              ~notification ~callback_pa ~callback_tr) from_tn_list to_tn_list
    | _ -> raise BadCopyPaste


let copy_detached ~copy c from_any =
  match from_any with
  | APn from_pn ->
    begin
      let pn_id = copy_proof_node_as_detached c.controller_session from_pn in
      let parent = get_any_parent c.controller_session from_any in
      match parent with
701
      | None -> raise (BadCopyDetached "copy_detached no parent")
Sylvain Dailler's avatar
Sylvain Dailler committed
702 703
      | Some parent ->
          copy ~parent (APn pn_id);
Sylvain Dailler's avatar
Sylvain Dailler committed
704 705
          copy_structure
            ~notification:copy c.controller_session (APn from_pn) (APn pn_id)
Sylvain Dailler's avatar
Sylvain Dailler committed
706
    end
707 708
  (* Only goal can be detached *)
  | _ -> raise (BadCopyDetached "copy_detached. Can only copy goal")
Sylvain Dailler's avatar
Sylvain Dailler committed
709

710 711 712 713
type report =
  | Result of Call_provers.prover_result * Call_provers.prover_result
  (** Result(new_result,old_result) *)
  | CallFailed of exn
714
  | Replay_interrupted
715 716 717 718 719 720 721 722 723 724 725
  | Prover_not_installed
  | Edited_file_absent of string
  | No_former_result of Call_provers.prover_result

(* TODO find a better way to print it *)
let print_report fmt (r: report) =
  match r with
  | Result (new_r, old_r) ->
    Format.fprintf fmt "new_result = %a, old_result = %a@."
      Call_provers.print_prover_result new_r
      Call_provers.print_prover_result old_r
726 727 728 729
  | CallFailed e ->
    Format.fprintf fmt "Callfailed %a@." Exn_printer.exn_printer e
  | Replay_interrupted ->
    Format.fprintf fmt "Interrupted@."
730 731 732 733 734 735 736 737 738
  | Prover_not_installed ->
    Format.fprintf fmt "Prover not installed@."
  | Edited_file_absent _ ->
    Format.fprintf fmt "No edited file@."
  | No_former_result new_r ->
    Format.fprintf fmt "new_result = %a, no former result@."
      Call_provers.print_prover_result new_r

(* TODO to be removed when we have a better way to print *)
739
let replay_print fmt (lr: (proofNodeID * Whyconf.prover * Call_provers.resource_limit * report) list) =
740 741
  let pp_elem fmt (id, pr, rl, report) =
    fprintf fmt "ProofNodeID: %d, Prover: %a, Timelimit?: %d, Result: %a@."
Sylvain Dailler's avatar
Sylvain Dailler committed
742 743
      (Obj.magic id) Whyconf.print_prover pr
      rl.Call_provers.limit_time print_report report
744
  in
745
  Format.fprintf fmt "%a@." (Pp.print_list Pp.newline pp_elem) lr
746

747 748
let replay ?(obsolete_only=true) ?(use_steps=false)
           c ~callback ~notification ~final_callback =
749

750
  let craft_report count s r id pr limits pa =
751
    match s with
752 753 754
    | Scheduled | Running -> ()
    | Unedited | JustEdited -> assert false
    | Interrupted ->
755
       decr count;
756
       r := (id, pr, limits, Replay_interrupted ) :: !r
757
    | Done new_r ->
758
       decr count;
759 760 761 762
        (match pa.Session_itp.proof_state with
        | None -> (r := (id, pr, limits, No_former_result new_r) :: !r)
        | Some old_r -> r := (id, pr, limits, Result (new_r, old_r)) :: !r)
    | InternalFailure e ->
763
       decr count;
764
        r := (id, pr, limits, CallFailed (e)) :: !r
765 766 767
    | Uninstalled _ ->
       decr count;
       r := (id, pr, limits, Prover_not_installed) :: !r;
768
  in
769 770 771 772 773 774 775 776 777

  (* === replay === *)
  let session = c.controller_session in
  let count = ref 0 in
  let report = ref [] in

  (* TODO count the number of node in a more efficient way *)
  (* Counting the number of proof_attempt to print report only once *)
  Session_itp.session_iter_proof_attempt
778
    (fun _ pa -> if pa.proof_obsolete || not obsolete_only then incr count) session;
779 780

  (* Replaying function *)
781
  let replay_pa id pa =
782 783 784 785
    if pa.proof_obsolete || not obsolete_only then
      begin
        let parid = pa.parent in
        let pr = pa.prover in
786 787 788 789
        (* TODO: if pr is not installed, lookup for a replacement policy
         OR: delegate this work to the replay_proof_attempt function *)
        (* If use_steps, we give only steps as a limit
         TODO: steps should not be used if prover was replaced above *)
790 791 792 793 794 795
        let limit =
          if use_steps then
            Call_provers.{empty_limit with limit_steps = pa.limit.limit_steps}
          else
            Call_provers.{ pa.limit with limit_steps = empty_limit.limit_steps }
        in
796 797
        let proof_script = pa.proof_script in
        replay_proof_attempt ?proof_script c pr limit parid id
798 799 800 801 802 803
                             ~callback:(fun id s ->
                                        craft_report count s report parid pr limit pa;
                                        callback id s;
                                        if !count = 0 then final_callback !report)
                             ~notification
      end in
804

805
  if !count = 0 then final_callback !report else
806
  (* Calling replay on all the proof_attempts of the session *)
807
  Session_itp.session_iter_proof_attempt replay_pa session
808

809
end