controller_itp.ml 34.8 KB
Newer Older
1
open Format
Clément Fumex's avatar
Clément Fumex committed
2 3
open Session_itp

Sylvain Dailler's avatar
Sylvain Dailler committed
4 5 6 7 8

let debug_sched = Debug.register_info_flag "scheduler"
  ~desc:"Print@ debugging@ messages@ about@ scheduling@ of@ prover@ calls@ \
         and@ transformation@ applications."

9 10
exception Noprogress

11 12 13
let () = Exn_printer.register
    (fun fmt e ->
      match e with
Sylvain Dailler's avatar
Sylvain Dailler committed
14 15
      | Noprogress ->
          Format.fprintf fmt "The transformation made no progress.\n"
16 17
      | _ -> raise e)

Clément Fumex's avatar
Clément Fumex committed
18 19 20 21 22 23 24 25 26
(** 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 *)
27
    | Uninstalled of Whyconf.prover (** prover is uninstalled *)
Clément Fumex's avatar
Clément Fumex committed
28

MARCHE Claude's avatar
MARCHE Claude committed
29 30
let print_status fmt st =
  match st with
Sylvain Dailler's avatar
Sylvain Dailler committed
31 32 33 34 35 36 37 38 39 40 41
  | 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
42 43

type transformation_status =
44
  | TSscheduled | TSdone of transID | TSfailed of (proofNodeID * exn)
45 46 47 48

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

52 53 54 55
type strategy_status = STSgoto of proofNodeID * int | STShalt

let print_strategy_status fmt st =
  match st with
Sylvain Dailler's avatar
Sylvain Dailler committed
56 57
  | STSgoto(id,n) ->
      fprintf fmt "goto step %d in proofNode %a" n print_proofNodeID id
58 59 60
  | STShalt -> fprintf fmt "halt"


61 62 63
open Ident

type proof_state = {
64
    file_state: bool Stdlib.Hstr.t;
65 66 67 68 69
    th_state: bool Hid.t;
    tn_state: bool Htn.t;
    pn_state : bool Hpn.t;
  }

70 71 72 73 74 75
let init_proof_state () = {
    file_state = Stdlib.Hstr.create 3;
    th_state = Hid.create 7;
    tn_state = Htn.create 42;
    pn_state = Hpn.create 42;
  }
76

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

86
(*
87
let clear_proof_state c =
88
  Stdlib.Hstr.clear c.proof_state.file_state;
89 90 91
  Hid.clear c.proof_state.th_state;
  Htn.clear c.proof_state.tn_state;
  Hpn.clear c.proof_state.pn_state
92
*)
93

94
let create_controller config env ses =
95 96
  let c =
    {
97
      controller_session = ses;
98 99 100 101 102 103 104 105 106 107
      proof_state = init_proof_state ();
      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
108
       let d = Whyconf.load_driver (Whyconf.get_main config) env p.Whyconf.driver [] in
109 110 111 112 113 114 115 116 117
       Whyconf.Hprover.add c.controller_provers p.Whyconf.prover (p,d)
     with e ->
       Format.eprintf
         "[Controller_itp] error while loading driver for prover %a: %a@."
         Whyconf.print_prover p.Whyconf.prover
         Exn_printer.exn_printer e)
    provers;
  c

Clément Fumex's avatar
Clément Fumex committed
118 119
let tn_proved c tid = Htn.find_def c.proof_state.tn_state false tid
let pn_proved c pid = Hpn.find_def c.proof_state.pn_state false pid
120 121 122 123 124
let th_proved c th  =
  if (theory_goals th = []) then
    Hid.find_def c.proof_state.th_state true (theory_name th)
  else
    Hid.find_def c.proof_state.th_state false (theory_name th)
125 126 127 128 129
let file_proved c f =
  if f.file_theories = [] then
    true
  else
    List.for_all (fun th -> th_proved c th) f.file_theories
130

131 132 133 134 135 136 137 138 139
let any_proved cont any : bool =
  match any with
  | AFile file -> file_proved cont file
  | ATh th -> th_proved cont th
  | ATn tn -> tn_proved cont tn
  | APn pn -> pn_proved cont pn
  | APa pa ->
      begin
        let pa = get_proof_attempt_node cont.controller_session pa in
Sylvain Dailler's avatar
Sylvain Dailler committed
140
        match pa.Session_itp.proof_state with
141 142 143 144 145 146 147 148 149
        | None -> false
        | Some pa ->
          begin
            match pa.Call_provers.pr_answer with
            | Call_provers.Valid -> true
            | _ -> false
          end
      end

150 151 152 153 154 155 156 157
let remove_any_proof_state cont any : unit =
  match any with
  | AFile _file -> ()
  | ATh th     -> Hid.remove cont.proof_state.th_state (theory_name th)
  | APn pn     -> Hpn.remove cont.proof_state.pn_state pn
  | ATn tn     -> Htn.remove cont.proof_state.tn_state tn
  | APa _pa     -> ()

158 159 160



161

162

163 164 165 166 167 168 169 170 171 172 173
(** TODO make the whole reloading of proof_state more efficient and natural *)

(* Note that f has side effect on the elements of l. We want this effect to
   happen. That's why we cannot use List.for_all (respectively List.exists)
   directly (List.for_all stops on first element that evaluates to false) *)
let for_all_se f l =
  List.for_all (fun b -> b) (List.map f l)

let exists_se f l =
  List.exists (fun b -> b) (List.map f l)

174
(* init proof state after reload *)
175
let rec reload_goal_proof_state c g =
176 177 178
  let ses = c.controller_session in
  let tr_list = get_transformations ses g in
  let pa_list = get_proof_attempts ses g in
179
  let proved = exists_se (reload_trans_proof_state c) tr_list in
180
  let proved = exists_se reload_pa_proof_state pa_list || proved in
181 182 183
  Hpn.replace c.proof_state.pn_state g proved;
  proved

184
and reload_trans_proof_state c tr =
185
  let proof_list = get_sub_tasks c.controller_session tr in
186
  let proved = for_all_se (reload_goal_proof_state c) proof_list in
187 188 189 190 191 192 193 194 195 196 197 198
  Htn.replace c.proof_state.tn_state tr proved;
  proved

and reload_pa_proof_state pa =
  match pa.proof_obsolete, pa.Session_itp.proof_state with
  | false, Some pr when pr.Call_provers.pr_answer = Call_provers.Valid -> true
  | _ -> false

(* to be called after reload *)
let reload_theory_proof_state c th =
  let ps = c.proof_state in
  let goals = theory_goals th in
199
  let proved = for_all_se (reload_goal_proof_state c) goals in
200 201 202 203 204 205 206 207 208 209 210
  Hid.replace ps.th_state (theory_name th) proved

(* to be called after reload *)
let reload_file_proof_state c f =
  List.iter (reload_theory_proof_state c) f.file_theories

(* to be called after reload *)
let reload_session_proof_state c =
  Stdlib.Hstr.iter
    (fun _ f -> reload_file_proof_state c f)
    (get_files c.controller_session)
211

212 213 214 215 216 217 218
(* Get children of any without proofattempts *)
let get_undetached_children_no_pa s any : any list =
  match any with
  | AFile f -> List.map (fun th -> ATh th) f.file_theories
  | 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
219
  | APa _ -> []
220

221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284



(* status update *)

type notifier = any -> unit

let pa_ok pa =
  not pa.proof_obsolete &&
    match pa.Session_itp.proof_state
    with
    | Some { Call_provers.pr_answer = Call_provers.Valid} -> true
    | _ -> false

(* [update_goal_node c id] update the proof status of node id
   update is propagated to parents when required. *)

let update_file_node notification c f =
  let ps = c.proof_state in
  let ths = f.file_theories in
  let proved = List.for_all (th_proved c) ths in
  if proved <> file_proved c f then
    begin
      Stdlib.Hstr.replace ps.file_state f.file_name proved;
      notification (AFile f);
    end

let update_theory_node notification c th =
  let ps = c.proof_state in
  let goals = theory_goals th in
  let proved = List.for_all (pn_proved c) goals in
  if proved <> th_proved c th then
    begin
      Hid.replace ps.th_state (theory_name th) proved;
      notification (ATh th);
      update_file_node notification c (theory_parent c.controller_session th)
    end

let rec update_goal_node notification c id =
  let ses = c.controller_session in
  let tr_list = get_transformations ses id in
  let pa_list = get_proof_attempts ses id in
  let proved = List.exists (tn_proved c) tr_list || List.exists pa_ok pa_list in
  if proved <> pn_proved c id then
    begin
      Hpn.replace c.proof_state.pn_state id proved;
      notification (APn id);
      match get_proof_parent ses id with
      | Trans trans_id -> update_trans_node notification c trans_id
      | Theory th -> update_theory_node notification c th
    end

and update_trans_node notification c trid =
  let ses = c.controller_session in
  let proof_list = get_sub_tasks ses trid in
  let proved = List.for_all (pn_proved c) proof_list in
  if proved <> tn_proved c trid then
    begin
      Htn.replace c.proof_state.tn_state trid proved;
      notification (ATn trid);
      update_goal_node notification c (get_trans_parent ses trid)
    end


285 286 287 288 289 290 291 292 293 294 295 296
(* printing *)

module PSession = struct

  open Stdlib

  type any =
    | Session
    | File of file
    | Theory of theory
    | Goal of proofNodeID
    | Transf of transID
297
    | ProofAttempt of proof_attempt_node
298 299 300 301 302 303 304 305 306 307 308

  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 ->
       f.file_name,
Sylvain Dailler's avatar
Sylvain Dailler committed
309 310 311 312
       List.fold_right
          (fun th -> n (Theory th))
          f.file_detached_theories
          (List.fold_right (fun th -> n (Theory th)) f.file_theories [])
313 314 315
    | Theory th ->
       let id = theory_name th in
       let name = id.Ident.id_string in
316
       let name = if th_proved x.tcont th then name^"!" else name^"?" in
317
       name,
Sylvain Dailler's avatar
Sylvain Dailler committed
318 319 320 321
       List.fold_right
         (fun g -> n (Goal g))
         (theory_goals th)
         (List.fold_right (fun g -> n (Goal g)) (theory_detached_goals th) [])
322 323 324
    | Goal id ->
       let gid = get_proof_name s id in
       let name = gid.Ident.id_string in
325
       let name = if pn_proved x.tcont id then name^"!" else name^"?" in
326 327 328 329 330 331 332
       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
333 334 335 336 337
          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 ""), []
338 339
    | Transf id ->
       let name = get_transf_name s id in
340
       let name = if tn_proved x.tcont id then name^"!" else name^"?" in
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
       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 }

(*********)



358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
let read_file env ?format fn =
  let theories = Env.read_file Env.base_language env ?format fn in
  let ltheories =
    Stdlib.Mstr.fold
      (fun name th acc ->
        (* Hack : with WP [name] and [th.Theory.th_name.Ident.id_string] *)
        let th_name =
          Ident.id_register (Ident.id_derive name th.Theory.th_name) in
         match th.Theory.th_name.Ident.id_loc with
           | Some l -> (l,th_name,th)::acc
           | None   -> (Loc.dummy_position,th_name,th)::acc)
      theories []
  in
  let th =  List.sort
      (fun (l1,_,_) (l2,_,_) -> Loc.compare l1 l2)
      ltheories
  in
  List.map (fun (_,_,a) -> a) th


(** 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 *)

383
let merge_file (old_ses : session) (c : controller) ~use_shapes _ file =
384 385 386 387 388 389
  let format = file.file_format in
  let old_theories = file.file_theories in
  let file_name = Filename.concat (get_dir old_ses) file.file_name in
  let new_theories =
    try
      read_file c.controller_env file_name ?format
390 391
    with e -> (* TODO: filter only syntax error and typing errors *)
      raise e
392
  in
393
  merge_file_section
394
    c.controller_session ~use_shapes ~old_ses ~old_theories
395
    ~env:c.controller_env file_name new_theories format
396

397
let reload_files (c : controller) ~use_shapes =
398
  let old_ses = c.controller_session in
Sylvain Dailler's avatar
Sylvain Dailler committed
399 400
  c.controller_session <-
    empty_session ~shape_version:(get_shape_version old_ses) (get_dir old_ses);
401 402 403
  try
    Stdlib.Hstr.iter
      (fun f -> merge_file old_ses c ~use_shapes f)
404 405
      (get_files old_ses);
    reload_session_proof_state c
406 407 408
  with e ->
    c.controller_session <- old_ses;
    raise e
409 410 411

let add_file c ?format fname =
  let theories = read_file c.controller_env ?format fname in
412
  add_file_section c.controller_session fname theories format
413

414 415
(* Update the proof_state according to new false state and then remove
   the subtree *)
416
let remove_subtree c (n: any) ~removed ~notification =
417 418
  let removed = (fun x -> removed x; remove_any_proof_state c x) in
  let parent = get_any_parent c.controller_session n in
419 420 421 422 423 424 425 426 427 428 429 430 431 432
  (* Note that this line can raise RemoveError when called on inappropriate
     node (attached theory / goals) *)
  Session_itp.remove_subtree c.controller_session n ~notification:removed;
  (match parent with
  | Some (APn parent) ->
      (* If proof_state of the parent is actually changed update the branch
         otherwise do nothing *)
      let tr_list = get_transformations c.controller_session parent in
      let pa_list = get_proof_attempts c.controller_session parent in
      let proved = List.exists (tn_proved c) tr_list in
      let proved = List.exists reload_pa_proof_state pa_list || proved in
      if proved then
        ()
      else
433
        update_goal_node notification c parent
434 435 436 437 438 439 440 441
  | Some _ ->
      (* This case corresponds to removal of detached node. We don't need to
         update the proof_state *)
      ()
  | None ->
      (* Cannot remove root. Note that this should already have failed in call
         to Session_itp.remove_subtree *)
      raise RemoveError)
442 443 444 445 446 447

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

448 449
module Make(S : Scheduler) = struct

MARCHE Claude's avatar
MARCHE Claude committed
450 451 452 453 454 455 456 457
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

458 459 460 461 462
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
463
let number_of_running_provers = ref 0
464

465 466 467 468
let observer = ref (fun _ _ _ -> ())

let register_observer = (:=) observer

469
module Hprover = Whyconf.Hprover
MARCHE Claude's avatar
MARCHE Claude committed
470

471
let build_prover_call ?proof_script ~cntexample c id pr limit callback =
472 473
  let (config_pr,driver) = Hprover.find c.controller_provers pr in
  let command =
Sylvain Dailler's avatar
Sylvain Dailler committed
474 475 476
    Whyconf.get_complete_command
      config_pr
      ~with_steps:Call_provers.(limit.limit_steps <> empty_limit.limit_steps) in
477
  let task = Session_itp.get_task c.controller_session id in
478
  let table = Session_itp.get_table c.controller_session id in
479
  let call =
480
    Driver.prove_task ?old:proof_script ~cntexample:cntexample ~inplace:false ~command
481
                      ~limit ?name_table:table driver task
482
  in
483
  let pa = (c.controller_session,id,pr,proof_script,callback,false,call) in
MARCHE Claude's avatar
MARCHE Claude committed
484 485 486 487 488 489
  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
490
    let (ses,id,pr,pr_script,callback,started,call) as c =
Sylvain Dailler's avatar
Sylvain Dailler committed
491
      Queue.pop prover_tasks_in_progress in
492
    match Call_provers.query_call call with
MARCHE Claude's avatar
MARCHE Claude committed
493 494 495 496 497
    | Call_provers.NoUpdates -> Queue.add c q
    | Call_provers.ProverStarted ->
       assert (not started);
       callback Running;
       incr number_of_running_provers;
498 499
       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
500
       if started then decr number_of_running_provers;
501 502 503
       (* update the session *)
       update_proof_attempt ses id pr res;
       (* inform the callback *)
MARCHE Claude's avatar
MARCHE Claude committed
504
       callback (Done res)
505 506 507 508 509 510
    | 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)
511 512 513 514 515 516 517 518
    | 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
519 520
  done;
  Queue.transfer q prover_tasks_in_progress;
521
  (* if the number of prover tasks is less than 3 times the maximum
MARCHE Claude's avatar
MARCHE Claude committed
522 523
     number of running provers, then we heuristically decide to add
     more tasks *)
524 525 526 527
  begin
    try
      for _i = Queue.length prover_tasks_in_progress
          to 3 * !max_number_of_running_provers do
528
        let (c,id,pr,limit,proof_script,callback,cntexample) = Queue.pop scheduled_proof_attempts in
529
        try
530
          build_prover_call ?proof_script ~cntexample c id pr limit callback
531
        with e when not (Debug.test_flag Debug.stack_trace) ->
532
          (*Format.eprintf
533
            "@[Exception raised in Controller_itp.build_prover_call:@ %a@.@]"
534
            Exn_printer.exn_printer e;*)
535 536 537 538 539 540 541 542 543
          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
544

545 546
let interrupt () =
  while not (Queue.is_empty prover_tasks_in_progress) do
547
    let (_ses,_id,_pr,_proof_script,callback,_started,_call) =
548 549 550 551 552 553
      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
554
    let (_c,_id,_pr,_limit,_proof_script,callback,_cntexample) = Queue.pop scheduled_proof_attempts in
555 556 557 558
    callback Interrupted
  done;
  !observer 0 0 0

MARCHE Claude's avatar
MARCHE Claude committed
559 560 561 562 563 564 565
let run_timeout_handler () =
  if not !timeout_handler_running then
    begin
      timeout_handler_running := true;
      S.timeout ~ms:125 timeout_handler;
    end

566
let schedule_proof_attempt_r ?proof_script c id pr ~counterexmp ~limit ~callback =
567
  let panid =
568
    graft_proof_attempt c.controller_session id pr ~limit
569
  in
570
  Queue.add (c,id,pr,limit,proof_script,callback panid,counterexmp) scheduled_proof_attempts;
571
  callback panid Scheduled;
MARCHE Claude's avatar
MARCHE Claude committed
572
  run_timeout_handler ()
Clément Fumex's avatar
Clément Fumex committed
573

574
let schedule_proof_attempt ?proof_script c id pr ~counterexmp ~limit ~callback ~notification =
Sylvain Dailler's avatar
Sylvain Dailler committed
575
  let callback panid s = callback panid s;
Sylvain Dailler's avatar
Sylvain Dailler committed
576
    (match s with
577
    | Scheduled | Running | Done _ -> update_goal_node notification c id
Sylvain Dailler's avatar
Sylvain Dailler committed
578
    | _ -> ())
579
  in
580 581 582 583
  (* proof_script is specific to interactive manual provers *)
  let session_dir = Session_itp.get_dir c.controller_session in
  let proof_script = Opt.map (Sysutil.absolutize_filename session_dir) proof_script in
  schedule_proof_attempt_r ?proof_script c id pr ~counterexmp ~limit ~callback
584

585
(* TODO to be simplified *)
Sylvain Dailler's avatar
Sylvain Dailler committed
586 587 588 589 590 591 592
(* create the path to a file for saving the external proof script *)
let create_file_rel_path c pr pn =
  let config = c.controller_config in
  let c_env = c.controller_env in
  let session = c.controller_session in
  let prover_conf = Whyconf.get_prover_config config pr in
  let driver = prover_conf.Whyconf.driver in
593 594 595
  let driver = Whyconf.load_driver
                 (Whyconf.get_main config)
                 c_env driver prover_conf.Whyconf.extra_drivers in
Sylvain Dailler's avatar
Sylvain Dailler committed
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
  let task = Session_itp.get_task session pn in
  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
  let fn = f.file_name in
  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 config = c.controller_config in
  let c_env = c.controller_env in
  let session = c.controller_session in
  let prover_conf = Whyconf.get_prover_config config pr in
  let driver = prover_conf.Whyconf.driver in
614 615 616
  let driver = Whyconf.load_driver
                 (Whyconf.get_main config)
                 c_env driver prover_conf.Whyconf.extra_drivers in
Sylvain Dailler's avatar
Sylvain Dailler committed
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
  let task = Session_itp.get_task session pn in
  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

exception Editor_not_found

let schedule_edition c id pr ?file ~callback ~notification =
  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
  (* Notification node *)
  let callback panid s = callback panid s;
    match s with
    | Scheduled | Running | Done _ -> update_goal_node notification c id
    | _ -> ()
  in

  let limit = Call_provers.empty_limit in
664
  (* Make sure editor exists. Fails otherwise *)
Sylvain Dailler's avatar
Sylvain Dailler committed
665 666
  let editor =
    match prover_conf.Whyconf.editor with
667
    | "" -> raise Editor_not_found
Sylvain Dailler's avatar
Sylvain Dailler committed
668 669 670
    | s ->
        try
          let ed = Whyconf.editor_by_id config s in
671 672 673
          String.concat " "(ed.Whyconf.editor_command ::
                            ed.Whyconf.editor_options)
        with Not_found -> raise Editor_not_found
Sylvain Dailler's avatar
Sylvain Dailler committed
674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698
  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

  Debug.dprintf debug_sched "[Editing] goal %s with command '%s' on file %s@."
    (Session_itp.get_proof_name session id).Ident.id_string
699 700 701 702 703 704 705 706
    editor file;
  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 ()

Sylvain Dailler's avatar
Sylvain Dailler committed
707

708
let schedule_transformation_r c id name args ~callback =
709 710
  let apply_trans () =
    let task = get_task c.controller_session id in
711 712 713
    let table = match get_table c.controller_session id with
    | None -> raise (Task.Bad_name_table "Controller_itp.schedule_transformation_r")
    | Some table -> table in
714 715
    begin
      try
Sylvain Dailler's avatar
Sylvain Dailler committed
716
        let subtasks =
717
          Trans.apply_transform_args name c.controller_env args table task in
718 719 720 721
        (* if result is same as input task, consider it as a failure *)
        begin
          match subtasks with
          | [t'] when Task.task_equal t' task ->
722
             callback (TSfailed (id, Noprogress))
723 724 725 726 727
          | _ ->
             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) ->
728
        (* Format.eprintf
729
          "@[Exception raised in Trans.apply_transform %s:@ %a@.@]"
730
          name Exn_printer.exn_printer e; TODO *)
731
        callback (TSfailed (id, e))
732 733
    end;
    false
734 735 736
  in
  S.idle ~prio:0 apply_trans;
  callback TSscheduled
Clément Fumex's avatar
Clément Fumex committed
737

738
let schedule_transformation c id name args ~callback ~notification =
739
  let callback s = callback s; (match s with
740
      | TSdone tid -> update_trans_node notification c tid
741
      | TSfailed _e -> ()
742
      | _ -> ()) in
743 744 745 746
  schedule_transformation_r c id name args ~callback

open Strategy

Sylvain Dailler's avatar
Sylvain Dailler committed
747
let run_strategy_on_goal
748
    c id strat ~counterexmp ~callback_pa ~callback_tr ~callback ~notification =
749 750 751 752 753 754
  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
755 756
         let callback panid res =
           callback_pa panid res;
757 758 759 760 761
           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
762 763
           | Interrupted | InternalFailure _ ->
              callback STShalt
764 765 766 767 768
           | 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
769
           | Unedited | JustEdited | Uninstalled _ ->
770 771 772 773 774 775
                         (* should not happen *)
                         assert false
         in
         let limit = { Call_provers.empty_limit with
                       Call_provers.limit_time = timelimit;
                       limit_mem  = memlimit} in
776
         schedule_proof_attempt c g p ~counterexmp ~limit ~callback ~notification
777 778
      | Itransform(trname,pcsuccess) ->
         let callback ntr =
MARCHE Claude's avatar
MARCHE Claude committed
779
           callback_tr ntr;
780
           match ntr with
781
           | TSfailed _e -> (* transformation failed *)
782 783 784 785 786 787 788 789 790 791 792 793
              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
794
                (get_sub_tasks c.controller_session tid)
795
         in
796
         schedule_transformation c g trname [] ~callback ~notification
797 798 799 800 801 802
      | Igoto pc ->
         callback (STSgoto (g,pc));
         exec_strategy pc strat g
  in
  exec_strategy 0 strat id

Sylvain Dailler's avatar
Sylvain Dailler committed
803 804
let schedule_pa_with_same_arguments
    c (pa: proof_attempt_node) (pn: proofNodeID) ~callback ~notification =
Sylvain Dailler's avatar
Sylvain Dailler committed
805 806 807 808
  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
809 810
let schedule_tr_with_same_arguments
    c (tr: transID) (pn: proofNodeID) ~callback ~notification =
Sylvain Dailler's avatar
Sylvain Dailler committed
811 812 813 814 815
  let s = c.controller_session in
  let args = get_transf_args s tr in
  let name = get_transf_name s tr in
  schedule_transformation c pn name args ~callback ~notification

816 817


818
let clean_session c ~remove =
819 820
  let s = c.controller_session in
  Session_itp.session_iter_proof_attempt
821 822 823 824 825 826 827 828 829
    (fun id pa ->
      if pn_proved c pa.parent then
        match pa.Session_itp.proof_state with
        | None -> ()
        | Some pr ->
           if pa.Session_itp.proof_obsolete ||
                Call_provers.(pr.pr_answer <> Valid)
           then
             remove_subtree c ~removed:remove ~notification:(fun _ -> ()) (APa id))
830
    s
831

832 833
(* This function folds on any subelements of given node and tries to mark all
   proof attempts it encounters *)
834
let mark_as_obsolete ~notification c any =
835
  (* Case for proof attempt only *)
836
  let mark_as_obsolete_pa c n =
837
    let s = c.controller_session in
838 839
    let parent = get_proof_attempt_parent s n in
    Session_itp.mark_obsolete s n;
840 841
    notification (APa n);
    update_goal_node notification c parent
842 843 844 845
  in
  let s = c.controller_session in
  fold_all_any s
    (fun () any -> match any with
846
    | APa n -> mark_as_obsolete_pa c n
847
    | _ -> ()) () any
848

Sylvain Dailler's avatar
Sylvain Dailler committed
849 850 851 852 853 854 855 856 857 858 859 860 861 862
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
863
      List.iter (fun x -> schedule_pa_with_same_arguments c x to_pn ~counterexmp:false
Sylvain Dailler's avatar
Sylvain Dailler committed
864 865 866 867
          ~callback:callback_pa ~notification) from_pa_list;
      let from_tr_list = get_transformations s from_pn in
      let callback x st = callback_tr st;
        match st with
Sylvain Dailler's avatar
Sylvain Dailler committed
868 869
        | TSdone tid ->
          copy_paste c (ATn x) (ATn tid) ~notification ~callback_pa ~callback_tr
Sylvain Dailler's avatar
Sylvain Dailler committed
870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889
        | _ -> ()
      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
890
      | None -> raise (BadCopyDetached "copy_detached no parent")
Sylvain Dailler's avatar
Sylvain Dailler committed
891 892
      | Some parent ->
          copy ~parent (APn pn_id);
Sylvain Dailler's avatar
Sylvain Dailler committed
893 894
          copy_structure
            ~notification:copy c.controller_session (APn from_pn) (APn pn_id)
Sylvain Dailler's avatar
Sylvain Dailler committed
895
    end
896 897
  (* Only goal can be detached *)
  | _ -> raise (BadCopyDetached "copy_detached. Can only copy goal")
Sylvain Dailler's avatar
Sylvain Dailler committed
898 899


900
let replay_proof_attempt ?proof_script c pr limit (parid: proofNodeID) id ~callback ~notification =
901 902 903
  (* 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
904
    callback id (Uninstalled pr)
905
  else
906
    schedule_proof_attempt ?proof_script c parid pr ~counterexmp:false ~limit ~callback ~notification
907 908 909 910 911

type report =
  | Result of Call_provers.prover_result * Call_provers.prover_result
  (** Result(new_result,old_result) *)
  | CallFailed of exn
912
  | Replay_interrupted
913 914 915 916 917 918 919 920 921 922 923
  | 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
924 925 926 927
  | CallFailed e ->
    Format.fprintf fmt "Callfailed %a@." Exn_printer.exn_printer e
  | Replay_interrupted ->
    Format.fprintf fmt "Interrupted@."
928 929 930 931 932 933 934 935 936
  | 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 *)
937
let replay_print fmt (lr: (proofNodeID * Whyconf.prover * Call_provers.resource_limit * report) list) =
938 939
  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
940 941
      (Obj.magic id) Whyconf.print_prover pr
      rl.Call_provers.limit_time print_report report
942
  in
943
  Format.fprintf fmt "%a@." (Pp.print_list Pp.newline pp_elem) lr
944

945 946
let replay ?(obsolete_only=true) ?(use_steps=false)
           c ~callback ~notification ~final_callback =
947

948
  let craft_report count s r id pr limits pa =
949
    match s with
950 951 952
    | Scheduled | Running -> ()
    | Unedited | JustEdited -> assert false
    | Interrupted ->
953
       decr count;
954
       r := (id, pr, limits, Replay_interrupted ) :: !r
955
    | Done new_r ->
956
       decr count;
957 958 959 960
        (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 ->
961
       decr count;
962
        r := (id, pr, limits, CallFailed (e)) :: !r
963 964 965
    | Uninstalled _ ->
       decr count;
       r := (id, pr, limits, Prover_not_installed) :: !r;
966
  in
967 968 969 970 971 972 973 974 975

  (* === 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
976
    (fun _ pa -> if pa.proof_obsolete || not obsolete_only then incr count) session;
977 978

  (* Replaying function *)
979
  let replay_pa id pa =
980 981 982 983
    if pa.proof_obsolete || not obsolete_only then
      begin
        let parid = pa.parent in
        let pr = pa.prover in
984 985 986 987
        (* 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 *)
988 989 990 991 992 993
        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
994 995
        let proof_script = pa.proof_script in
        replay_proof_attempt ?proof_script c pr limit parid id
996 997 998 999 1000 1001
                             ~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
1002 1003

  (* Calling replay on all the proof_attempts of the session *)
1004
  Session_itp.session_iter_proof_attempt replay_pa session
1005

1006
end