controller_itp.ml 37.3 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
(** State of a proof *)
type proof_attempt_status =
34 35 36 37 38 39 40 41 42
  | Unedited (** editor not yet run for interactive proof *)
  | JustEdited (** edited but not run yet *)
  | Detached (** parent goal has no task, is detached *)
  | 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 *)
  | Uninstalled of Whyconf.prover (** prover is uninstalled *)
Clément Fumex's avatar
Clément Fumex committed
43

MARCHE Claude's avatar
MARCHE Claude committed
44 45
let print_status fmt st =
  match st with
Sylvain Dailler's avatar
Sylvain Dailler committed
46 47
  | Unedited          -> fprintf fmt "Unedited"
  | JustEdited        -> fprintf fmt "JustEdited"
48
  | Detached          -> fprintf fmt "Detached"
Sylvain Dailler's avatar
Sylvain Dailler committed
49 50 51 52 53 54 55 56 57
  | 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
58 59

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

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

68 69 70 71
type strategy_status = STSgoto of proofNodeID * int | STShalt

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


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

86

87
let create_controller config env ses =
88 89
  let c =
    {
90
      controller_session = ses;
91 92 93
      controller_config = config;
      controller_env = env;
      controller_provers = Whyconf.Hprover.create 7;
94
      controller_strategies = Stdlib.Hstr.create 7;
95 96 97 98 99 100
    }
  in
  let provers = Whyconf.get_provers config in
  Whyconf.Mprover.iter
    (fun _ p ->
     try
101
       let d = Whyconf.load_driver (Whyconf.get_main config) env p.Whyconf.driver [] in
102 103
       Whyconf.Hprover.add c.controller_provers p.Whyconf.prover (p,d)
     with e ->
Sylvain Dailler's avatar
Sylvain Dailler committed
104
       Debug.dprintf debug_call_prover
105 106 107 108 109 110
         "[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
111
let remove_subtree c = Session_itp.remove_subtree c.controller_session
112

113 114 115
(* Get children of any without proofattempts *)
let get_undetached_children_no_pa s any : any list =
  match any with
116
  | AFile f -> List.map (fun th -> ATh th) (file_theories f)
117 118 119
  | 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
120
  | APa _ -> []
121

122 123


124 125 126 127 128 129 130 131 132 133 134 135
(* printing *)

module PSession = struct

  open Stdlib

  type any =
    | Session
    | File of file
    | Theory of theory
    | Goal of proofNodeID
    | Transf of transID
136
    | ProofAttempt of proof_attempt_node
137 138 139 140 141 142 143 144 145 146

  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 ->
147
       (file_name f),
148
       List.fold_right (fun th -> n (Theory th)) (file_theories f) []
149 150 151
    | Theory th ->
       let id = theory_name th in
       let name = id.Ident.id_string in
152
       let name = if th_proved s th then name^"!" else name^"?" in
153
       name,
Sylvain Dailler's avatar
Sylvain Dailler committed
154 155 156 157
       List.fold_right
         (fun g -> n (Goal g))
         (theory_goals th)
         (List.fold_right (fun g -> n (Goal g)) (theory_detached_goals th) [])
158 159 160
    | Goal id ->
       let gid = get_proof_name s id in
       let name = gid.Ident.id_string in
161
       let name = if pn_proved s id then name^"!" else name^"?" in
162 163 164 165 166 167 168
       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
169 170 171 172 173
          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 ""), []
174 175
    | Transf id ->
       let name = get_transf_name s id in
176
       let name = if tn_proved s id then name^"!" else name^"?" in
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
       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 }

(*********)



194 195 196 197 198 199

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

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

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

215 216

module type Scheduler = sig
217
  val multiplier: int
218 219 220 221
  val timeout: ms:int -> (unit -> bool) -> unit
  val idle: prio:int -> (unit -> bool) -> unit
end

222 223
module Make(S : Scheduler) = struct

MARCHE Claude's avatar
MARCHE Claude committed
224 225 226 227 228 229 230 231
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

232 233 234 235
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
236
let number_of_running_provers = ref 0
237

238 239 240 241
let observer = ref (fun _ _ _ -> ())

let register_observer = (:=) observer

242
module Hprover = Whyconf.Hprover
MARCHE Claude's avatar
MARCHE Claude committed
243

244 245 246 247 248 249 250 251 252 253 254 255 256
(* calling provers, with limits adaptation

 *)


(* to avoid corner cases when prover results are obtained very closely
   to the time or mem limits, we adapt these limits when we replay a
   proof *)

let adapt_limits ~interactive ~use_steps limits a =
  let t, m, s =
    let timelimit = limits.Call_provers.limit_time in
    let memlimit = limits.Call_provers.limit_mem in
257
    let steplimit = limits.Call_provers.limit_steps in
258 259 260 261 262 263 264 265 266 267 268 269 270 271
    match a.proof_state with
    | Some { Call_provers.pr_answer = r;
             Call_provers.pr_time = t;
             Call_provers.pr_steps = s } ->
       (* increased time limit is 1 + twice the previous running time,
       but enforced to remain inside the interval [l,2l] where l is
       the previous time limit *)
       let t = truncate (1.0 +. 2.0 *. t) in
       let increased_time = if interactive then t
                            else max timelimit (min t (2 * timelimit)) in
       (* increased mem limit is just 1.5 times the previous mem limit *)
       let increased_mem = if interactive then 0 else 3 * memlimit / 2 in
       begin
         match r with
272 273
         | Call_provers.OutOfMemory -> increased_time, memlimit, steplimit
         | Call_provers.Timeout -> timelimit, increased_mem, steplimit
274 275 276 277 278 279 280
         | Call_provers.Valid ->
            let steplimit =
              if use_steps && not a.proof_obsolete then s else 0
            in
            increased_time, increased_mem, steplimit
         | Call_provers.Unknown _
         | Call_provers.StepLimitExceeded
281
         | Call_provers.Invalid -> increased_time, increased_mem, steplimit
282 283 284
         | Call_provers.Failure _
         | Call_provers.HighFailure ->
            (* correct ? failures are supposed to appear quickly anyway... *)
285
            timelimit, memlimit, steplimit
286 287
       end
    | None when interactive -> 0, 0, 0
288
    | None -> timelimit, memlimit, steplimit
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
  in
  { Call_provers.limit_time = t; limit_mem = m; limit_steps = s }

let group_answer a =
  match a with
  | Call_provers.OutOfMemory
  | Call_provers.Unknown _
  | Call_provers.Timeout -> Call_provers.Timeout
  | _ -> a

let fuzzy_proof_time nres ores =
  let ansold = ores.Call_provers.pr_answer in
  let told = ores.Call_provers.pr_time in
  let ansnew = nres.Call_provers.pr_answer in
  let tnew = nres.Call_provers.pr_time in
  if group_answer ansold = group_answer ansnew &&
       tnew >= told *. 0.9 -. 0.1 && tnew <= told *. 1.1 +. 0.1
  then { nres with Call_provers.pr_time = told }
  else nres


let build_prover_call ?proof_script ~cntexample c id pr limit callback ores =
311
  let (config_pr,driver) = Hprover.find c.controller_provers pr in
312
  let with_steps = Call_provers.(limit.limit_steps <> empty_limit.limit_steps) in
313
  let command =
314
    Whyconf.get_complete_command config_pr ~with_steps in
315 316 317 318 319 320 321 322 323 324
  try
    let task = Session_itp.get_raw_task c.controller_session id in
    let call =
      Driver.prove_task ?old:proof_script ~cntexample:cntexample ~inplace:false ~command
                        ~limit (*?name_table:table*) driver task
    in
    let pa = (c.controller_session,id,pr,proof_script,callback,false,call,ores) in
    Queue.push pa prover_tasks_in_progress
  with Not_found (* goal has no task, it is detached *) ->
       callback Detached
MARCHE Claude's avatar
MARCHE Claude committed
325

326 327 328 329 330 331
let update_observer () =
  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

MARCHE Claude's avatar
MARCHE Claude committed
332 333 334 335
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
336
    let (ses,id,pr,pr_script,callback,started,call,ores) as c =
Sylvain Dailler's avatar
Sylvain Dailler committed
337
      Queue.pop prover_tasks_in_progress in
338
    match Call_provers.query_call call with
MARCHE Claude's avatar
MARCHE Claude committed
339 340 341 342 343
    | Call_provers.NoUpdates -> Queue.add c q
    | Call_provers.ProverStarted ->
       assert (not started);
       callback Running;
       incr number_of_running_provers;
344
       Queue.add (ses,id,pr,pr_script,callback,true,call,ores) q
345
    | Call_provers.ProverFinished res ->
MARCHE Claude's avatar
MARCHE Claude committed
346
       if started then decr number_of_running_provers;
347
       let res = Opt.fold fuzzy_proof_time res ores in
348 349 350
       (* update the session *)
       update_proof_attempt ses id pr res;
       (* inform the callback *)
MARCHE Claude's avatar
MARCHE Claude committed
351
       callback (Done res)
352
(*
353 354
    | Call_provers.ProverFinished res (* when pr_script <> None *) ->
       if started then decr number_of_running_provers;
355
       let res = Opt.fold fuzzy_proof_time res ores in
356 357 358 359
       (* update the session *)
       update_proof_attempt ~obsolete:true ses id pr res;
       (* inform the callback *)
       callback (Done res)
360
*)
361 362 363 364 365 366 367 368
    | 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
369 370
  done;
  Queue.transfer q prover_tasks_in_progress;
371
  (* if the number of prover tasks is less than 3 times the maximum
MARCHE Claude's avatar
MARCHE Claude committed
372 373
     number of running provers, then we heuristically decide to add
     more tasks *)
374 375 376
  begin
    try
      for _i = Queue.length prover_tasks_in_progress
377
          to S.multiplier * !max_number_of_running_provers do
378 379
        let (c,id,pr,limit,proof_script,callback,cntexample,ores) =
          Queue.pop scheduled_proof_attempts in
380
        try
381
          build_prover_call ?proof_script ~cntexample c id pr limit callback ores
382
        with e when not (Debug.test_flag Debug.stack_trace) ->
383
          (*Format.eprintf
384
            "@[Exception raised in Controller_itp.build_prover_call:@ %a@.@]"
385
            Exn_printer.exn_printer e;*)
386 387 388 389
          callback (InternalFailure e)
      done
  with Queue.Empty -> ()
  end;
390
  update_observer ();
391
  true
MARCHE Claude's avatar
MARCHE Claude committed
392

393 394
let interrupt () =
  while not (Queue.is_empty prover_tasks_in_progress) do
395
    let (_ses,_id,_pr,_proof_script,callback,_started,_call,_ores) =
396 397 398 399 400 401
      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
402 403
    let (_c,_id,_pr,_limit,_proof_script,callback,_cntexample,_ores) =
      Queue.pop scheduled_proof_attempts in
404 405 406 407
    callback Interrupted
  done;
  !observer 0 0 0

MARCHE Claude's avatar
MARCHE Claude committed
408 409 410 411
let run_timeout_handler () =
  if not !timeout_handler_running then
    begin
      timeout_handler_running := true;
412
      S.timeout ~ms:default_delay_ms timeout_handler;
MARCHE Claude's avatar
MARCHE Claude committed
413 414
    end

415
let schedule_proof_attempt_r ?proof_script c id pr ~counterexmp ~limit ~callback =
416
  let s = c.controller_session in
417
  let adaptlimit,ores =
418 419 420 421 422 423 424 425 426 427
    try
      let h = get_proof_attempt_ids s id in
      let pa = Hprover.find h pr in
      let a = get_proof_attempt_node s pa in
      let old_res = a.proof_state in
      let config_pr,_ = Hprover.find c.controller_provers pr in
      let interactive = config_pr.Whyconf.interactive in
      let use_steps = Call_provers.(limit.limit_steps <> empty_limit.limit_steps) in
      let limit = adapt_limits ~interactive ~use_steps limit a in
      limit, old_res
428
    with Not_found | Session_itp.BadID -> limit,None
429
  in
430
  let panid = graft_proof_attempt ~limit s id pr in
431
  Queue.add (c,id,pr,adaptlimit,proof_script,callback panid,counterexmp,ores)
432
            scheduled_proof_attempts;
433
  callback panid Scheduled;
MARCHE Claude's avatar
MARCHE Claude committed
434
  run_timeout_handler ()
Clément Fumex's avatar
Clément Fumex committed
435

436 437
let schedule_proof_attempt ?proof_script c id pr
                           ~counterexmp ~limit ~callback ~notification =
438
  let callback panid s =
Sylvain Dailler's avatar
Sylvain Dailler committed
439
    (match s with
440 441 442 443
    | 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
444 445
    | _ -> ());
    callback panid s
446
  in
447 448
  (* proof_script is specific to interactive manual provers *)
  let session_dir = Session_itp.get_dir c.controller_session in
449 450 451
  let proof_script =
    Opt.map (Sysutil.absolutize_filename session_dir) proof_script
  in
452
  schedule_proof_attempt_r ?proof_script c id pr ~counterexmp ~limit ~callback
453

454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496

(* replay *)


let find_prover notification c goal_id pr =
  if Hprover.mem c.controller_provers pr then Some pr else
   match Whyconf.get_prover_upgrade_policy c.controller_config pr with
   | exception Not_found -> None
   | Whyconf.CPU_keep -> None
   | Whyconf.CPU_upgrade new_pr ->
      (* does a proof using new_pr already exists ? *)
      if Hprover.mem (get_proof_attempt_ids c.controller_session goal_id) new_pr
      then (* yes, then we do nothing *)
        None
      else
        begin
          (* we modify the prover in-place *)
          Session_itp.change_prover notification c.controller_session goal_id pr new_pr;
          Some new_pr
        end
   | Whyconf.CPU_duplicate _new_pr ->
      assert false (* TODO *)
(*
      (* does a proof using new_p already exists ? *)
      if Hprover.mem (goal_external_proofs parid) new_pr
      then (* yes, then we do nothing *)
        None
      else
        begin
          (* we duplicate the proof_attempt *)
          let new_a = copy_external_proof
                        ~notify ~keygen:O.create ~prover:new_p ~env_session:eS a
          in
          Some new_pr
        end
*)

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 *)
  match find_prover notification c parid pr with
  | None -> callback id (Uninstalled pr)
  | Some pr ->
497 498 499 500 501
     try
       let _ = get_raw_task c.controller_session parid in
       schedule_proof_attempt ?proof_script c parid pr ~counterexmp:false ~limit ~callback ~notification
     with Not_found ->
       callback id Detached
502 503


504
(* TODO to be simplified *)
Sylvain Dailler's avatar
Sylvain Dailler committed
505 506 507
(* 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
508
  let driver = snd (Hprover.find c.controller_provers pr) in
509
  let task = Session_itp.get_raw_task session pn in
Sylvain Dailler's avatar
Sylvain Dailler committed
510 511 512 513
  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
514
  let fn = Filename.chop_extension (Filename.basename (file_name f)) in
Sylvain Dailler's avatar
Sylvain Dailler committed
515 516 517 518 519 520 521 522
  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
523
  let driver = snd (Hprover.find c.controller_provers pr) in
524
  let task = Session_itp.get_raw_task session pn in
Sylvain Dailler's avatar
Sylvain Dailler committed
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
  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

Sylvain Dailler's avatar
Sylvain Dailler committed
557
let schedule_edition c id pr ~no_edit ~do_check_proof ?file ~callback ~notification =
Sylvain Dailler's avatar
Sylvain Dailler committed
558 559 560 561 562 563 564
  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
565
  (* Make sure editor exists. Fails otherwise *)
Sylvain Dailler's avatar
Sylvain Dailler committed
566 567
  let editor =
    match prover_conf.Whyconf.editor with
568
    | "" -> raise Editor_not_found
Sylvain Dailler's avatar
Sylvain Dailler committed
569 570 571
    | s ->
        try
          let ed = Whyconf.editor_by_id config s in
572 573
          String.concat " " (ed.Whyconf.editor_command ::
                             ed.Whyconf.editor_options)
574
        with Not_found -> raise Editor_not_found
Sylvain Dailler's avatar
Sylvain Dailler committed
575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
  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

598 599 600 601
  (* 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
602 603 604 605 606 607 608 609 610 611 612 613
    | 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
614 615 616
    | _ -> ()
  in

Sylvain Dailler's avatar
Sylvain Dailler committed
617 618
  Debug.dprintf debug_sched "[Editing] goal %s with command '%s' on file %s@."
    (Session_itp.get_proof_name session id).Ident.id_string
619
    editor file;
Sylvain Dailler's avatar
Sylvain Dailler committed
620 621 622 623 624 625 626 627 628 629
  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
630
      Queue.add (c.controller_session,id,pr,Some file,callback panid,false,call,None)
Sylvain Dailler's avatar
Sylvain Dailler committed
631 632 633
        prover_tasks_in_progress;
      run_timeout_handler ()
    end
634

Sylvain Dailler's avatar
Sylvain Dailler committed
635

636
let schedule_transformation_r c id name args ~callback =
637
  let apply_trans () =
638 639
    begin
      try
640 641 642
        let subtasks =
          apply_trans_to_goal ~allow_no_effect:false
                              c.controller_session c.controller_env name args id
643
        in
644 645 646 647 648 649 650
        let tid = graft_transf c.controller_session id name args subtasks in
        callback (TSdone tid)
      with
      | Exit ->
         (* if result is same as input task, consider it as a failure *)
         callback (TSfailed (id, Noprogress))
      | e when not (Debug.test_flag Debug.stack_trace) ->
651
        (* Format.eprintf
652
          "@[Exception raised in Session_itp.apply_trans_to_goal %s:@ %a@.@]"
653
          name Exn_printer.exn_printer e; TODO *)
654
        callback (TSfailed (id, e))
655 656
    end;
    false
657 658 659
  in
  S.idle ~prio:0 apply_trans;
  callback TSscheduled
Clément Fumex's avatar
Clément Fumex committed
660

661
let schedule_transformation c id name args ~callback ~notification =
662
  let callback s = callback s; (match s with
663
      | TSdone tid -> update_trans_node notification c.controller_session tid
664
      | TSfailed _e -> ()
665
      | _ -> ()) in
666 667 668 669
  schedule_transformation_r c id name args ~callback

open Strategy

Sylvain Dailler's avatar
Sylvain Dailler committed
670
let run_strategy_on_goal
671
    c id strat ~counterexmp ~callback_pa ~callback_tr ~callback ~notification =
672 673 674 675 676 677
  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
678 679
         let callback panid res =
           callback_pa panid res;
680 681 682 683 684
           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
685 686
           | Interrupted | InternalFailure _ ->
              callback STShalt
687 688 689 690 691
           | 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
692
           | Unedited | JustEdited | Detached | Uninstalled _ ->
693 694 695 696 697 698
                         (* should not happen *)
                         assert false
         in
         let limit = { Call_provers.empty_limit with
                       Call_provers.limit_time = timelimit;
                       limit_mem  = memlimit} in
699
         schedule_proof_attempt c g p ~counterexmp ~limit ~callback ~notification
700 701
      | Itransform(trname,pcsuccess) ->
         let callback ntr =
702
           callback_tr trname [] ntr;
703
           match ntr with
704
           | TSfailed _e -> (* transformation failed *)
705 706 707 708 709 710 711 712 713 714 715 716
              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
717
                (get_sub_tasks c.controller_session tid)
718
         in
719
         schedule_transformation c g trname [] ~callback ~notification
720 721 722 723 724 725
      | Igoto pc ->
         callback (STSgoto (g,pc));
         exec_strategy pc strat g
  in
  exec_strategy 0 strat id

Sylvain Dailler's avatar
Sylvain Dailler committed
726 727
let schedule_pa_with_same_arguments
    c (pa: proof_attempt_node) (pn: proofNodeID) ~callback ~notification =
Sylvain Dailler's avatar
Sylvain Dailler committed
728 729 730 731
  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
732 733
let schedule_tr_with_same_arguments
    c (tr: transID) (pn: proofNodeID) ~callback ~notification =
Sylvain Dailler's avatar
Sylvain Dailler committed
734 735 736
  let s = c.controller_session in
  let args = get_transf_args s tr in
  let name = get_transf_name s tr in
737
  let callback = callback name args in
Sylvain Dailler's avatar
Sylvain Dailler committed
738 739
  schedule_transformation c pn name args ~callback ~notification

740 741 742
let clean_session c ~removed =
  (* clean should not change proved status *)
  let notification _ = assert false in
743
  let s = c.controller_session in
744 745 746 747 748
  (* 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 ->
749 750
        let pa = Session_itp.get_proof_attempt_node s pa in
        if pn_proved s pa.parent then
751 752 753
          (match pa.Session_itp.proof_state with
          | None -> ()
          | Some pr ->
754 755 756
           if pa.Session_itp.proof_obsolete ||
                Call_provers.(pr.pr_answer <> Valid)
           then
Sylvain Dailler's avatar
Sylvain Dailler committed
757
             Session_itp.remove_subtree ~notification ~removed s any)
758
      | ATn tn ->
759 760
        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
761
          Session_itp.remove_subtree s ~notification ~removed (ATn tn)
762
      | _ -> ())) ()
763

764 765
(* This function folds on any subelements of given node and tries to mark all
   proof attempts it encounters *)
766
let mark_as_obsolete ~notification c any =
767
  let s = c.controller_session in
768
  (* Case for proof attempt only *)
769
  let mark_as_obsolete_pa n =
770 771
    let parent = get_proof_attempt_parent s n in
    Session_itp.mark_obsolete s n;
772
    notification (APa n);
773
    update_goal_node notification s parent
774 775 776
  in
  fold_all_any s
    (fun () any -> match any with
777
    | APa n -> mark_as_obsolete_pa n
778
    | _ -> ()) () any
779

Sylvain Dailler's avatar
Sylvain Dailler committed
780 781 782 783 784 785 786 787 788 789 790 791 792 793
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
794
      List.iter (fun x -> schedule_pa_with_same_arguments c x to_pn ~counterexmp:false
Sylvain Dailler's avatar
Sylvain Dailler committed
795 796
          ~callback:callback_pa ~notification) from_pa_list;
      let from_tr_list = get_transformations s from_pn in
797
      let callback x tr args st = callback_tr tr args st;
Sylvain Dailler's avatar
Sylvain Dailler committed
798
        match st with
Sylvain Dailler's avatar
Sylvain Dailler committed
799 800
        | TSdone tid ->
          copy_paste c (ATn x) (ATn tid) ~notification ~callback_pa ~callback_tr
Sylvain Dailler's avatar
Sylvain Dailler committed
801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820
        | _ -> ()
      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
821
      | None -> raise (BadCopyDetached "copy_detached no parent")
Sylvain Dailler's avatar
Sylvain Dailler committed
822 823
      | Some parent ->
          copy ~parent (APn pn_id);
Sylvain Dailler's avatar
Sylvain Dailler committed
824 825
          copy_structure
            ~notification:copy c.controller_session (APn from_pn) (APn pn_id)
Sylvain Dailler's avatar
Sylvain Dailler committed
826
    end
827 828
  (* Only goal can be detached *)
  | _ -> raise (BadCopyDetached "copy_detached. Can only copy goal")
Sylvain Dailler's avatar
Sylvain Dailler committed
829

MARCHE Claude's avatar
MARCHE Claude committed
830 831 832 833 834 835 836 837 838 839 840







(***************** {2 replay} ****************)



841 842 843 844
type report =
  | Result of Call_provers.prover_result * Call_provers.prover_result
  (** Result(new_result,old_result) *)
  | CallFailed of exn
845
  | Replay_interrupted
846 847 848 849 850 851 852 853 854 855 856
  | 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
857 858 859 860
  | CallFailed e ->
    Format.fprintf fmt "Callfailed %a@." Exn_printer.exn_printer e
  | Replay_interrupted ->
    Format.fprintf fmt "Interrupted@."
861 862 863 864 865 866 867 868 869
  | 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 *)
870
let replay_print fmt (lr: (proofNodeID * Whyconf.prover * Call_provers.resource_limit * report) list) =
871 872
  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
873 874
      (Obj.magic id) Whyconf.print_prover pr
      rl.Call_provers.limit_time print_report report
875
  in
876
  Format.fprintf fmt "%a@." (Pp.print_list Pp.newline pp_elem) lr
877

878 879
let replay ?(obsolete_only=true) ?(use_steps=false)
           c ~callback ~notification ~final_callback =
880

881
  let craft_report count s r id pr limits pa =
882
    match s with
883 884 885
    | Scheduled | Running -> ()
    | Unedited | JustEdited -> assert false
    | Interrupted ->
886
       decr count;
887
       r := (id, pr, limits, Replay_interrupted ) :: !r
888
    | Done new_r ->
889
       decr count;
890 891 892 893
        (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 ->
894
       decr count;
895
        r := (id, pr, limits, CallFailed (e)) :: !r
896 897 898
    | Uninstalled _ ->
       decr count;
       r := (id, pr, limits, Prover_not_installed) :: !r;
899
    | Detached -> decr count
900
  in
901 902 903 904 905 906 907 908

  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
909
    (fun _ pa -> if pa.proof_obsolete || not obsolete_only then incr count) session;
910 911

  (* Replaying function *)
912
  let replay_pa id pa =
913 914 915 916
    if pa.proof_obsolete || not obsolete_only then
      begin
        let parid = pa.parent in
        let pr = pa.prover in
917 918 919 920
        (* 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 *)
921 922 923 924 925 926
        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
927 928
        let proof_script = pa.proof_script in
        replay_proof_attempt ?proof_script c pr limit parid id
929 930 931 932 933 934
                             ~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
935

936
  if !count = 0 then final_callback !report else
937
  (* Calling replay on all the proof_attempts of the session *)
938
  Session_itp.session_iter_proof_attempt replay_pa session
939

MARCHE Claude's avatar
MARCHE Claude committed
940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965



(*************** bisect **********)



let debug = Debug.register_flag ~desc:"Task bisection" "bisect"

let bisect_proof_attempt ~notification c pa_id =
  let ses = c.controller_session in
  let pa = get_proof_attempt_node ses pa_id in
  let goal_id = pa.parent in
  let prover = pa.prover in
  let limit = { pa.limit with
                Call_provers.limit_steps =
                  Call_provers.empty_limit.Call_provers.limit_steps }
  in
  let timelimit = ref (-1) in
  let set_timelimit res =
    timelimit := 1 + (int_of_float (floor res.Call_provers.pr_time)) in
  let rec callback kont _pa_id = function
    | Running | Scheduled -> ()
    | Interrupted ->
      Debug.dprintf debug "Bisecting interrupted.@."
    | Unedited | JustEdited -> assert false
966
    | Detached | Uninstalled _ -> assert false
MARCHE Claude's avatar
MARCHE Claude committed
967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004
    | InternalFailure exn ->
      (* Perhaps the test can be considered false in this case? *)
      Debug.dprintf debug "Bisecting interrupted by an error %a.@."
        Exn_printer.exn_printer exn
    | Done res ->
      let b = res.Call_provers.pr_answer = Call_provers.Valid in
      Debug.dprintf debug "Bisecting: %a.@."
        Call_provers.print_prover_result res;
      if b then set_timelimit res;
      match kont b with
      | Eliminate_definition.BSdone rem ->
         if Decl.Spr.is_empty rem.Eliminate_definition.rem_pr &&
              Term.Sls.is_empty rem.Eliminate_definition.rem_ls &&
                Ty.Sts.is_empty rem.Eliminate_definition.rem_ts
         then
           Debug.dprintf debug "Bisecting doesn't reduced the task.@."
         else
           begin
             Debug.dprintf debug "Bisecting done.@.";
             ()
(*
        begin try
        let keygen = MA.keygen in
        let notify = MA.notify in
        let reml = List.map (fun (m,l) -> m.Theory.meta_name,l) reml in
        let metas = S.add_registered_metas ~keygen ses reml pa.S.proof_parent in
        let trans = S.add_registered_transformation ~keygen
          ses "eliminate_builtin" metas.S.metas_goal in
        let goal = List.hd trans.S.transf_goals in (* only one *)
        let npa = S.copy_external_proof ~notify ~keygen ~obsolete:true
          ~goal ~env_session:ses pa in
        MA.init_any (S.Metas metas);
        M.run_external_proof ses sched ~cntexample npa
        with e ->
          dprintf debug "Bisecting error:@\n%a@."
            Exn_printer.exn_printer e end
 *)
           end
1005
      | Eliminate_definition.BSstep (_rem,kont) ->
MARCHE Claude's avatar
MARCHE Claude committed
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015

         schedule_proof_attempt
           c goal_id prover
	  ~counterexmp:false
          ~limit:{ limit with Call_provers.limit_time = !timelimit; }
          ~callback:(callback kont)
          ~notification
  in
  (* Run once the complete goal in order to verify its validity and
     update the proof attempt *)
1016
  let first_callback _pa_id = function
MARCHE Claude's avatar
MARCHE Claude committed
1017 1018 1019 1020
    (* this pa_id can be different from the first pa_id *)
    | Running | Scheduled -> ()
    | Interrupted ->
      Debug.dprintf debug "Bisecting interrupted.@."
1021
    | Unedited | JustEdited | Detached | Uninstalled _ -> assert false
MARCHE Claude's avatar
MARCHE Claude committed
1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
    | InternalFailure exn ->
        Debug.dprintf debug "proof of the initial task interrupted by an error %a.@."
          Exn_printer.exn_printer exn
    | Done res ->
      if res.Call_provers.pr_answer <> Call_provers.Valid
      then Debug.dprintf debug "Initial task can't be proved.@."
      else
        let t = get_raw_task ses goal_id in
        let r = Eliminate_definition.bisect_step t in
        match r with
1032
        | Eliminate_definition.BSdone _res ->
MARCHE Claude's avatar
MARCHE Claude committed
1033
          Debug.dprintf debug "Task can't be reduced.@."
1034
        | Eliminate_definition.BSstep (_rem,kont) ->
MARCHE Claude's avatar
MARCHE Claude committed
1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
          set_timelimit res;
          schedule_proof_attempt
            c goal_id prover
	    ~counterexmp:false
            ~limit:{ limit with Call_provers.limit_time = !timelimit}
            ~callback:(callback kont)
            ~notification
  in
  Debug.dprintf debug "Bisecting with %a started.@."
    Whyconf.print_prover prover;
  schedule_proof_attempt
    c goal_id prover ~counterexmp:false ~limit ~callback:first_callback ~notification

1048
end