itp_server.ml 46.1 KB
Newer Older
1
open Format
Sylvain Dailler's avatar
Sylvain Dailler committed
2
open Stdlib
3
4
open Session_itp
open Controller_itp
Sylvain Dailler's avatar
Sylvain Dailler committed
5
open Server_utils
6
open Itp_communication
7

Sylvain Dailler's avatar
Sylvain Dailler committed
8
exception Bad_prover_name of string
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49

(**********************************)
(* list unproven goal and related *)
(**********************************)

(* If the transformation is proved, return acc.
   Else, return the concatenation of the reversed list of unproven
   goals below the transformation and acc *)
let rec unproven_goals_below_tn cont acc tn =
  if tn_proved cont tn then
    acc                         (* we ignore "dead" goals *)
  else
    let sub_tasks = get_sub_tasks cont.controller_session tn in
    List.fold_left (unproven_goals_below_pn cont) acc sub_tasks

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

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

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

50
51
52
53
54
55
56
57
58
59
60
61
62
let unproven_goals_below_id cont id =
  match id  with
  | APn pnid   -> [pnid]
  | APa panid  ->
     let ses = cont.controller_session in
     [get_proof_attempt_parent ses panid]
  | ATn tn     ->
     List.rev (unproven_goals_below_tn cont [] tn)
  | AFile file ->
     List.rev (unproven_goals_below_file cont file)
  | ATh th     ->
     List.rev (unproven_goals_below_th cont [] th)

Sylvain Dailler's avatar
Sylvain Dailler committed
63
64
65
66
(*******************)
(* Strategies list *)
(*******************)
let loaded_strategies = ref []
67
68
69
70

(****** Exception handling *********)

let print_term s id fmt t =
71
  let tables = match (Session_itp.get_table s id) with
72
73
74
75
76
  | None -> Args_wrapper.build_name_tables (Session_itp.get_task s id)
  | Some tables -> tables in
  Why3printer.print_term tables fmt t

let print_type s id fmt t =
77
  let tables = match (Session_itp.get_table s id) with
78
79
80
81
82
  | None -> Args_wrapper.build_name_tables (Session_itp.get_task s id)
  | Some tables -> tables in
  Why3printer.print_ty tables fmt t

let print_ts s id fmt t =
83
  let tables = match (Session_itp.get_table s id) with
84
85
86
87
88
  | None -> Args_wrapper.build_name_tables (Session_itp.get_task s id)
  | Some tables -> tables in
  Why3printer.print_ts tables fmt t

let print_ls s id fmt t =
89
  let tables = match (Session_itp.get_table s id) with
90
91
92
93
94
  | None -> Args_wrapper.build_name_tables (Session_itp.get_task s id)
  | Some tables -> tables in
  Why3printer.print_ls tables fmt t

let print_tv s id fmt t =
95
  let tables = match (Session_itp.get_table s id) with
96
97
98
99
100
  | None -> Args_wrapper.build_name_tables (Session_itp.get_task s id)
  | Some tables -> tables in
  Why3printer.print_tv tables fmt t

let print_vsty s id fmt t =
101
  let tables = match (Session_itp.get_table s id) with
102
103
104
105
106
  | None -> Args_wrapper.build_name_tables (Session_itp.get_task s id)
  | Some tables -> tables in
  Why3printer.print_forget_vsty tables fmt t

let print_pr s id fmt t =
107
  let tables = match (Session_itp.get_table s id) with
108
109
110
111
112
  | None -> Args_wrapper.build_name_tables (Session_itp.get_task s id)
  | Some tables -> tables in
  Why3printer.print_pr tables fmt t

let print_pat s id fmt t =
113
  let tables = match (Session_itp.get_table s id) with
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
  | None -> Args_wrapper.build_name_tables (Session_itp.get_task s id)
  | Some tables -> tables in
  Why3printer.print_pat tables fmt t

(* Exception reporting *)

(* TODO remove references to id.id_string in this function *)
let bypass_pretty s id =
  begin fun fmt exn -> match exn with
  | Ty.TypeMismatch (t1,t2) ->
      fprintf fmt "Type mismatch between %a and %a"
        (print_type s id) t1 (print_type s id) t2
  | Ty.BadTypeArity ({Ty.ts_args = []} as ts, _) ->
      fprintf fmt "Type symbol %a expects no arguments" (print_ts s id) ts
  | Ty.BadTypeArity (ts, app_arg) ->
      let i = List.length ts.Ty.ts_args in
      fprintf fmt "Type symbol %a expects %i argument%s but is applied to %i"
        (print_ts s id) ts i (if i = 1 then "" else "s") app_arg
  | Ty.DuplicateTypeVar tv ->
      fprintf fmt "Type variable %a is used twice" (print_tv s id) tv
  | Ty.UnboundTypeVar tv ->
      fprintf fmt "Unbound type variable: %a" (print_tv s id) tv
  | Ty.UnexpectedProp ->
      fprintf fmt "Unexpected propositional type"
  | Term.BadArity ({Term.ls_args = []} as ls, _) ->
      fprintf fmt "%s %a expects no arguments"
        (if ls.Term.ls_value = None then "Predicate" else "Function") (print_ls s id) ls
  | Term.BadArity (ls, app_arg) ->
      let i = List.length ls.Term.ls_args in
      fprintf fmt "%s %a expects %i argument%s but is applied to %i"
        (if ls.Term.ls_value = None then "Predicate" else "Function")
        (print_ls s id) ls i (if i = 1 then "" else "s") app_arg
  | Term.EmptyCase ->
      fprintf fmt "Empty match expression"
  | Term.DuplicateVar vs ->
      fprintf fmt "Variable %a is used twice" (print_vsty s id) vs
  | Term.UncoveredVar vs ->
      fprintf fmt "Variable %a uncovered in \"or\"-pattern" (print_vsty s id) vs
  | Term.FunctionSymbolExpected ls ->
      fprintf fmt "Not a function symbol: %a" (print_ls s id) ls
  | Term.PredicateSymbolExpected ls ->
      fprintf fmt "Not a predicate symbol: %a" (print_ls s id) ls
  | Term.ConstructorExpected ls ->
      fprintf fmt "%s %a is not a constructor"
        (if ls.Term.ls_value = None then "Predicate" else "Function") (print_ls s id) ls
  | Term.TermExpected t ->
      fprintf fmt "Not a term: %a" (print_term s id) t
  | Term.FmlaExpected t ->
      fprintf fmt "Not a formula: %a" (print_term s id) t
  | Pattern.ConstructorExpected (ls,ty) ->
      fprintf fmt "%s %a is not a constructor of type %a"
        (if ls.Term.ls_value = None then "Predicate" else "Function") (print_ls s id) ls
        (print_type s id) ty
  | Pattern.NonExhaustive pl ->
      fprintf fmt "Pattern not covered by a match:@\n  @[%a@]"
        (print_pat s id) (List.hd pl)
  | Decl.BadConstructor ls ->
      fprintf fmt "Bad constructor: %a" (print_ls s id) ls
  | Decl.BadRecordField ls ->
      fprintf fmt "Not a record field: %a" (print_ls s id) ls
  | Decl.RecordFieldMissing (_cs,ls) ->
      fprintf fmt "Field %a is missing" (print_ls s id) ls
  | Decl.DuplicateRecordField (_cs,ls) ->
      fprintf fmt "Field %a is used twice in the same constructor" (print_ls s id) ls
  | Decl.IllegalTypeAlias ts ->
      fprintf fmt
        "Type symbol %a is a type alias and cannot be declared as algebraic"
        (print_ts s id) ts
  | Decl.NonFoundedTypeDecl ts ->
      fprintf fmt "Cannot construct a value of type %a" (print_ts s id) ts
  | Decl.NonPositiveTypeDecl (_ts, ls, ty) ->
      fprintf fmt "Constructor %a \
          contains a non strictly positive occurrence of type %a"
        (print_ls s id) ls (print_type s id) ty
  | Decl.InvalidIndDecl (_ls, pr) ->
      fprintf fmt "Ill-formed inductive clause %a"
        (print_pr s id) pr
  | Decl.NonPositiveIndDecl (_ls, pr, ls1) ->
      fprintf fmt "Inductive clause %a contains \
          a non strictly positive occurrence of symbol %a"
        (print_pr s id) pr (print_ls s id) ls1
  | Decl.BadLogicDecl (ls1,ls2) ->
      fprintf fmt "Ill-formed definition: symbols %a and %a are different"
        (print_ls s id) ls1 (print_ls s id) ls2
  | Decl.UnboundVar vs ->
      fprintf fmt "Unbound variable: %a" (print_vsty s id) vs
  | Decl.ClashIdent id ->
      fprintf fmt "Ident %s is defined twice" id.Ident.id_string
  | Decl.EmptyDecl ->
      fprintf fmt "Empty declaration"
  | Decl.EmptyAlgDecl ts ->
      fprintf fmt "Algebraic type %a has no constructors" (print_ts s id) ts
  | Decl.EmptyIndDecl ls ->
      fprintf fmt "Inductive predicate %a has no constructors" (print_ls s id) ls
  | Decl.KnownIdent id ->
      fprintf fmt "Ident %s is already declared" id.Ident.id_string
  | Decl.UnknownIdent id ->
      fprintf fmt "Ident %s is not yet declared" id.Ident.id_string
  | Decl.RedeclaredIdent id ->
      fprintf fmt "Ident %s is already declared, with a different declaration"
        id.Ident.id_string
  | Decl.NoTerminationProof ls ->
      fprintf fmt "Cannot prove the termination of %a" (print_ls s id) ls
  | _ -> Format.fprintf fmt "Uncaught: %a" Exn_printer.exn_printer exn
  end

let get_exception_message ses id fmt e =
  match e with
222
223
  | Controller_itp.Noprogress ->
      Format.fprintf fmt "Transformation made no progress\n"
224
225
226
227
228
229
230
231
  | Case.Arg_trans_type (s, ty1, ty2) ->
      Format.fprintf fmt "Error in transformation %s during unification of the following terms:\n %a \n %a"
        s (print_type ses id) ty1 (print_type ses id) ty2
  | Case.Arg_trans_term (s, t1, t2) ->
      Format.fprintf fmt "Error in transformation %s during unification of following two terms:\n %a \n %a" s
        (print_term ses id) t1 (print_term ses id) t2
  | Case.Arg_trans (s) ->
      Format.fprintf fmt "Error in transformation function: %s \n" s
Sylvain Dailler's avatar
Sylvain Dailler committed
232
  | Args_wrapper.Arg_hyp_not_found (s) ->
233
234
235
236
237
238
239
240
      Format.fprintf fmt "Following hypothesis was not found: %s \n" s
  | Args_wrapper.Arg_theory_not_found (s) ->
      Format.fprintf fmt "Theory not found: %s" s
  | e ->
      bypass_pretty ses id fmt e



Clément Fumex's avatar
Clément Fumex committed
241
242


Sylvain Dailler's avatar
Sylvain Dailler committed
243
(* Debugging functions *)
244
245
let print_request fmt r =
  match r with
246
247
248
249
  | Command_req (_nid, s)           -> fprintf fmt "command \"%s\"" s
  | Prove_req (_nid, prover, _rl)   -> fprintf fmt "prove with %s" prover
  | Transform_req (_nid, tr, _args) -> fprintf fmt "transformation :%s" tr
  | Strategy_req (_nid, st)         -> fprintf fmt "strategy %s" st
Sylvain Dailler's avatar
Sylvain Dailler committed
250
  | Edit_req (_nid, prover)         -> fprintf fmt "edit with %s" prover
251
(*
252
  | Open_session_req f              -> fprintf fmt "open session file %s" f
253
*)
254
255
  | Add_file_req f                  -> fprintf fmt "open file %s" f
  | Set_max_tasks_req i             -> fprintf fmt "set max tasks %i" i
256
  | Get_file_contents _f            -> fprintf fmt "get file contents"
257
  | Get_first_unproven_node _nid    -> fprintf fmt "get first unproven node"
258
  | Get_task _nid                   -> fprintf fmt "get task"
Sylvain Dailler's avatar
Sylvain Dailler committed
259
260
  | Focus_req _nid                  -> fprintf fmt "focus"
  | Unfocus_req                     -> fprintf fmt "unfocus"
261
  | Remove_subtree _nid             -> fprintf fmt "remove subtree"
Sylvain Dailler's avatar
Sylvain Dailler committed
262
263
  | Copy_paste _                    -> fprintf fmt "copy paste"
  | Copy_detached _                 -> fprintf fmt "copy detached"
264
  | Get_Session_Tree_req            -> fprintf fmt "get session tree"
265
  | Save_file_req _                 -> fprintf fmt "save file"
266
  | Mark_obsolete_req _             -> fprintf fmt "mark obsolete"
267
  | Clean_req                       -> fprintf fmt "clean"
268
269
270
271
  | Save_req                        -> fprintf fmt "save"
  | Reload_req                      -> fprintf fmt "reload"
  | Replay_req                      -> fprintf fmt "replay"
  | Exit_req                        -> fprintf fmt "exit"
272
  | Interrupt_req                   -> fprintf fmt "interrupt"
273

Sylvain Dailler's avatar
Sylvain Dailler committed
274
275
276
277
278
279
280
281
282
283
284
let print_msg fmt m =
  match m with
  | Proof_error (_ids, s)  -> fprintf fmt "proof error %s" s
  | Transf_error (_ids, s) -> fprintf fmt "transf error %s" s
  | Strat_error (_ids, s)  -> fprintf fmt "start error %s" s
  | Replay_Info s          -> fprintf fmt "replay info %s" s
  | Query_Info (_ids, s)   -> fprintf fmt "query info %s" s
  | Query_Error (_ids, s)  -> fprintf fmt "query error %s" s
  | Help _s                -> fprintf fmt "help"
  | Information s          -> fprintf fmt "info %s" s
  | Task_Monitor _         -> fprintf fmt "task montor"
285
  | Parse_Or_Type_Error s  -> fprintf fmt "parse_or_type_error:\n %s" s
286
  | File_Saved s           -> fprintf fmt "file saved %s" s
Sylvain Dailler's avatar
Sylvain Dailler committed
287
  | Error s                -> fprintf fmt "%s" s
288
  | Open_File_Error s      -> fprintf fmt "%s" s
Sylvain Dailler's avatar
Sylvain Dailler committed
289

290
291
292
293
294
295
296
297
298
299
300
(* TODO ad hoc printing. Should reuse print_loc. *)
let print_loc fmt (loc: Loc.position) =
  let (f,l,b,e) = Loc.get loc in
   fprintf fmt "File \"%s\", line %d, characters %d-%d" f l b e

let print_list_loc fmt l =
  Pp.print_list
    (fun _fmt () -> ())
    (fun fmt (loc, _c) -> Format.fprintf fmt "(%a, color)" print_loc loc)
    fmt l

Sylvain Dailler's avatar
Sylvain Dailler committed
301
302
let print_notify fmt n =
  match n with
303
304
305
306
  | Node_change (ni, nf)               ->
      begin
        match nf with
        | Proved b -> fprintf fmt "node change %d Proved %b" ni b
307
308
309
310
        | Obsolete b -> fprintf fmt "node change %d Obsolete %b" ni b
        | Proof_status_change(st,b,_lim) ->
           fprintf fmt "node change %d Proof_status_change res=%a obsolete=%b limits=<TODO>"
                   ni Controller_itp.print_status st b
311
      end
312
313
  | New_node (ni, _pni, _nt,  _nf, _d) -> fprintf fmt "new node %d" ni
  | Remove _ni                         -> fprintf fmt "remove"
314
  | Next_Unproven_Node_Id (_ni, _nj)   -> fprintf fmt "next unproven node_id"
315
316
317
  | Initialized _gi                    -> fprintf fmt "initialized"
  | Saved                              -> fprintf fmt "saved"
  | Message msg                        ->
Sylvain Dailler's avatar
Sylvain Dailler committed
318
      print_msg fmt msg
319
  | Dead s                             -> fprintf fmt "dead :%s" s
320
  | File_contents (_f, _s)             -> fprintf fmt "file contents"
321
322
323
  | Task (ni, _s, list_loc)            ->
      fprintf fmt "task for node_ID %d which contains a list of loc %a"
        ni print_list_loc list_loc
Sylvain Dailler's avatar
Sylvain Dailler committed
324

Clément Fumex's avatar
Clément Fumex committed
325
module type Protocol = sig
Clément Fumex's avatar
Clément Fumex committed
326
327
  val get_requests : unit -> ide_request list
  val notify : notification -> unit
Clément Fumex's avatar
Clément Fumex committed
328
329
end

Sylvain Dailler's avatar
Sylvain Dailler committed
330
module Make (S:Controller_itp.Scheduler) (Pr:Protocol) = struct
331
332

  module C = Controller_itp.Make(S)
Clément Fumex's avatar
Clément Fumex committed
333

334
let debug = Debug.register_flag "itp_server" ~desc:"ITP server"
Clément Fumex's avatar
Clément Fumex committed
335

336
337
338
339
340

(****************)
(* Command list *)
(****************)

341
let interrupt_query _cont _args = C.interrupt (); "interrupted"
342

343
344
345
346
347
348
349
350
351
352
353
354
355
let commands_table = Stdlib.Hstr.create 17

let register_command c d f = Stdlib.Hstr.add commands_table c (d,f)

let () =
  List.iter (fun (c,d,f) -> register_command c d f)
    [
    "interrupt", "interrupt all scheduled or running proof tasks",
    Qnotask interrupt_query;
    "list-transforms", "list available transformations",
    Qnotask list_transforms_query;
    "list-provers", "list available provers",
    Qnotask list_provers;
356
357
358
(*
    "list-strategies", "list available strategies", list_strategies;
*)
359
360
361
362
    "print", "<id> print the declaration where <id> was defined",
    Qtask print_id;
    "search", "<is> print declarations where <id> appears",
    Qtask search_id;
363
364
365
366
367
368
369
370
371
372
373
374
(*
    "r", "reload the session (test only)", test_reload;
    "s", "save the current session", test_save_session;
    "ng", "go to the next goal", then_print (move_to_goal_ret_p next_node);
    "pg", "go to the prev goal", then_print (move_to_goal_ret_p prev_node);
    "gu", "go to the goal up",  then_print (move_to_goal_ret_p zipper_up);
    "gd", "go to the goal down",  then_print (move_to_goal_ret_p zipper_down);
    "gr", "go to the goal right",  then_print (move_to_goal_ret_p zipper_right);
    "gl", "go to the goal left",  then_print (move_to_goal_ret_p zipper_left)
 *)
  ]

375
  type server_data =
376
    { task_driver : Driver.driver;
377
378
      cont : Controller_itp.controller;
    }
Clément Fumex's avatar
Clément Fumex committed
379

380
  let server_data = ref None
Clément Fumex's avatar
Clément Fumex committed
381

382
  let get_server_data () =
383
384
385
386
387
    match !server_data with
    | None ->
       Format.eprintf "[ITP server] not yet initialized@.";
       exit 1
    | Some x -> x
Clément Fumex's avatar
Clément Fumex committed
388

Sylvain Dailler's avatar
Sylvain Dailler committed
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
(* fresh gives new fresh "names" for node_ID using a counter.
   reset resets the counter so that we can regenerate node_IDs as if session
   was fresh *)
  let reset, fresh =
    let count = ref 0 in
    (fun () ->
      count := 0),
    fun () ->
      count := !count + 1;
      !count

  let model_any : any Hint.t = Hint.create 17

  let any_from_node_ID (nid:node_ID) : any = Hint.find model_any nid

  let pan_to_node_ID  : node_ID Hpan.t = Hpan.create 17
  let pn_to_node_ID   : node_ID Hpn.t = Hpn.create 17
  let tn_to_node_ID   : node_ID Htn.t = Htn.create 17
  let th_to_node_ID   : node_ID Ident.Hid.t = Ident.Hid.create 7
  let file_to_node_ID : node_ID Hstr.t = Hstr.create 3

  let node_ID_from_pan  pan  = Hpan.find pan_to_node_ID pan
  let node_ID_from_pn   pn   = Hpn.find pn_to_node_ID pn
  let node_ID_from_tn   tn   = Htn.find tn_to_node_ID tn
  let node_ID_from_th   th   = Ident.Hid.find th_to_node_ID (theory_name th)
  let node_ID_from_file file = Hstr.find file_to_node_ID (file.file_name)

  let node_ID_from_any  any  =
    match any with
    | AFile file -> node_ID_from_file file
    | ATh th     -> node_ID_from_th th
    | ATn tn     -> node_ID_from_tn tn
    | APn pn     -> node_ID_from_pn pn
    | APa pan    -> node_ID_from_pan pan

  let remove_any_node_ID any =
    match any with
    | AFile file ->
        let nid = Hstr.find file_to_node_ID file.file_name in
        Hint.remove model_any nid;
        Hstr.remove file_to_node_ID file.file_name
    | ATh th     ->
        let nid = Ident.Hid.find th_to_node_ID (theory_name th) in
        Hint.remove model_any nid;
        Ident.Hid.remove th_to_node_ID (theory_name th)
    | ATn tn     ->
        let nid = Htn.find tn_to_node_ID tn in
        Hint.remove model_any nid;
        Htn.remove tn_to_node_ID tn
    | APn pn     ->
        let nid = Hpn.find pn_to_node_ID pn in
        Hint.remove model_any nid;
        Hpn.remove pn_to_node_ID pn
    | APa pa     ->
        let nid = Hpan.find pan_to_node_ID pa in
        Hint.remove model_any nid;
        Hpan.remove pan_to_node_ID pa

  let get_prover p =
    let d = get_server_data () in
    match return_prover p d.cont.controller_config with
    | None -> raise (Bad_prover_name p)
    | Some c -> c

  let add_node_to_table node new_id =
    match node with
    | AFile file -> Hstr.add file_to_node_ID file.file_name new_id
    | ATh th     -> Ident.Hid.add th_to_node_ID (theory_name th) new_id
    | ATn tn     -> Htn.add tn_to_node_ID tn new_id
    | APn pn     -> Hpn.add pn_to_node_ID pn new_id
    | APa pan    -> Hpan.add pan_to_node_ID pan new_id


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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
(*******************************)
(* Compute color for locations *)
(*******************************)

(* This section is used to get colored source as a function of the task *)


(* These functions append stuff to a list which will then be passed to the
   Task notification. *)
let color_loc list ~color ~loc =
  let d = get_server_data () in
  let (f,l,b,e) = Loc.get loc in
  let f = Sysutil.relativize_filename
    (Session_itp.get_dir d.cont.controller_session) f in
  let loc = Loc.user_position f l b e in
  list := (loc, color) :: !list

let rec color_locs list ~color formula =
  let b = ref false in
  Opt.iter (fun loc -> color_loc list ~color ~loc; b := true) formula.Term.t_loc;
  Term.t_fold (fun b subf -> color_locs list ~color subf || b) !b formula

let rec color_t_locs list f =
  let premise_tag = function
    | { Term.t_node = Term.Tnot _; t_loc = None } -> Neg_premise_color
    | _ -> Premise_color
  in
  match f.Term.t_node with
    | Term.Tbinop (Term.Timplies,f1,f2) ->
        let b = color_locs list ~color:(premise_tag f1) f1 in
        color_t_locs list f2 || b
    | Term.Tlet (t,fb) ->
        let _,f1 = Term.t_open_bound fb in
        let b = color_locs list ~color:(premise_tag t) t in
        color_t_locs list f1 || b
    | Term.Tquant (Term.Tforall,fq) ->
        let _,_,f1 = Term.t_open_quant fq in
        color_t_locs list f1
    | _ ->
        color_locs list ~color:Goal_color f

exception No_loc_on_goal

let color_goal list loc =
  match loc with
  | None -> raise No_loc_on_goal
  | Some loc -> color_loc list ~color:Goal_color ~loc

let get_locations list (task: Task.task) =
  let goal_id : Ident.ident = (Task.task_goal task).Decl.pr_name in
  color_goal list goal_id.Ident.id_loc;
  match task with
    | Some
        { Task.task_decl =
            { Theory.td_node =
                Theory.Decl { Decl.d_node = Decl.Dprop (Decl.Pgoal, _, f)}}} ->
        if not (color_t_locs list f) then
          Opt.iter (fun loc -> color_loc list ~color:Goal_color ~loc) goal_id.Ident.id_loc
    | _ ->
        assert false

let get_locations t =
  let l = ref [] in
  get_locations l t;
  !l

Sylvain Dailler's avatar
Sylvain Dailler committed
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
557
558
559
560
561
562
563
564
565
let get_modified_node n =
  match n with
  | New_node (nid, _, _, _, _) -> Some nid
  | Node_change  (nid, _) -> Some nid
  | Remove nid -> Some nid
  | Next_Unproven_Node_Id (_, nid) -> Some nid
  | Initialized _ -> None
  | Saved -> None
  | Message _ -> None
  | Dead _ -> None
  | Task (nid, _, _) -> Some nid
  | File_contents _ -> None

(* Focus on a node *)
let focused_node = ref None

(* TODO *)
module P = struct

  let get_requests = Pr.get_requests

  let notify n =
    let d = get_server_data() in
    let s = d.cont.controller_session in
    match !focused_node with
    | None -> Pr.notify n
    | Some f_node ->
        let updated_node = get_modified_node n in
        match updated_node with
        | None -> Pr.notify n
        | Some nid when
            let any = any_from_node_ID nid in
            Session_itp.is_below s any f_node ->
              Pr.notify n
        | _ -> ()

end

566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
  (*********************)
  (* File input/output *)
  (*********************)

  let read_and_send f =
    try
      let d = get_server_data() in
      let fn = Sysutil.absolutize_filename
          (Session_itp.get_dir d.cont.controller_session) f in
      let s = Sysutil.file_contents fn in
      P.notify (File_contents (f, s))
    with Invalid_argument s ->
      P.notify (Message (Error s))

  let save_file f file_content =
    try
      let d = get_server_data() in
      let fn = Sysutil.absolutize_filename
          (Session_itp.get_dir d.cont.controller_session) f in
      Sysutil.write_file fn file_content;
      P.notify (Message (File_Saved f))
    with Invalid_argument s ->
      P.notify (Message (Error s))

  (* Send source file from the controller to the IDE even if the controller's
     status is not correct *)
  let load_files_session () =
    let d = get_server_data () in
    let s = d.cont.controller_session in
    let files = Session_itp.get_files s in
596
597
598
    Stdlib.Hstr.iter (fun _ f ->
                      Format.eprintf "File : %s@." f.file_name;
                      read_and_send f.file_name) files
599
600
601
602

  (* Reload_files that is used even if the controller is not correct. It can
     be incorrect and end up in a correct state. *)
  let reload_files cont ~use_shapes =
603
    try reload_files cont ~use_shapes; true with
604
605
606
607
608
609
610
611
612
613
614
    | e ->
      let s = Format.asprintf "%a@." Exn_printer.exn_printer e in
      P.notify (Message (Parse_Or_Type_Error s));
      false

  let add_file c ?format fname =
    try add_file c ?format fname; true with
    | e ->
        let s = Format.asprintf "%a@." Exn_printer.exn_printer e in
        P.notify (Message (Parse_Or_Type_Error s)); false

615
  let task_driver config env =
616
617
    try
      let main = Whyconf.get_main config in
MARCHE Claude's avatar
MARCHE Claude committed
618
619
      let d = "why3_itp" in
      let d = Whyconf.load_driver main env d [] in
620
621
622
      Debug.dprintf debug "[ITP server] driver for task printing loaded@.";
      d
    with e ->
623
624
      Format.eprintf "Fatal error while loading itp driver: %a@." Exn_printer.exn_printer e;
      exit 1
Clément Fumex's avatar
Clément Fumex committed
625

626
627
  let get_prover_list (config: Whyconf.config) =
    Mstr.fold (fun x _ acc -> x :: acc) (Whyconf.get_prover_shortcuts config) []
Sylvain Dailler's avatar
Sylvain Dailler committed
628
629

  (* -----------------------------------   ------------------------------------- *)
Clément Fumex's avatar
Clément Fumex committed
630

631
632
633
  let get_node_type (node: any) =
    match node with
    | AFile _ -> NFile
Sylvain Dailler's avatar
Sylvain Dailler committed
634
635
636
637
    | ATh _   -> NTheory
    | ATn _   -> NTransformation
    | APn _   -> NGoal
    | APa _   -> NProofAttempt
638
639

  let get_node_name (node: any) =
640
    let d = get_server_data () in
641
642
643
644
645
646
    match node with
    | AFile file ->
      file.file_name
    | ATh th ->
      (theory_name th).Ident.id_string
    | ATn tn ->
647
648
649
650
651
652
       let name = get_transf_name d.cont.controller_session tn in
       let args = get_transf_args d.cont.controller_session tn in
       let full = String.concat " " (name :: args) in
       if String.length full >= 40 then
         String.sub full 0 40 ^ " ..."
       else full
653
    | APn pn ->
654
      (get_proof_name d.cont.controller_session pn).Ident.id_string
655
    | APa pa ->
656
      let pa = get_proof_attempt_node d.cont.controller_session pa in
657
658
      Pp.string_of Whyconf.print_prover pa.prover

659
660
661
662
  let get_node_detached (node: any) =
    let d = get_server_data () in
    is_detached d.cont.controller_session node

663
664
665
  let get_node_proved new_id (node: any) =
    let d = get_server_data () in
    let cont = d.cont in
666
    match node with
667
668
    | AFile file ->
      P.notify (Node_change (new_id, Proved (file_proved cont file)))
669
    | ATh th ->
670
671
672
673
674
675
676
677
678
679
      P.notify (Node_change (new_id, Proved (th_proved cont th)))
    | ATn tn ->
      P.notify (Node_change (new_id, Proved (tn_proved cont tn)))
    | APn pn ->
      P.notify (Node_change (new_id, Proved (pn_proved cont pn)))
    | APa pa ->
      let pa = get_proof_attempt_node cont.controller_session pa in
      let is_obsolete = pa.proof_obsolete in
      let resource_limit = pa.limit in
      begin
680
        match pa.Session_itp.proof_state with
681
682
683
684
685
686
        | Some pa ->
            P.notify (Node_change (
                       new_id, Proof_status_change
                                (Done pa, is_obsolete, resource_limit)))
        | _ -> ()
      end
687

688
(*
Sylvain Dailler's avatar
Sylvain Dailler committed
689
690
691
692
693
  let get_info_and_type ses (node: any) =
    match node with
    | AFile file ->
        let name = file.file_name in
        let proved = file_proved cont file in
694
        NFile, {name; proved}
Sylvain Dailler's avatar
Sylvain Dailler committed
695
696
697
    | ATh th     ->
        let name = (theory_name th).Ident.id_string in
        let proved = th_proved cont th in
698
        NTheory, {name; proved}
Sylvain Dailler's avatar
Sylvain Dailler committed
699
700
701
    | ATn tn     ->
        let name = get_transf_name ses tn in
        let proved = tn_proved cont tn in
702
        NTransformation, {name; proved}
Sylvain Dailler's avatar
Sylvain Dailler committed
703
704
705
    | APn pn     ->
        let name = (get_proof_name ses pn).Ident.id_string in
        let proved = pn_proved cont pn in
706
          NGoal, {name; proved}
Sylvain Dailler's avatar
Sylvain Dailler committed
707
708
709
    | APa pan    ->
        let pa = get_proof_attempt_node ses pan in
        let name = Pp.string_of Whyconf.print_prover pa.prover in
Clément Fumex's avatar
Clément Fumex committed
710
711
712
        let pr, proved = match pa.Session_itp.proof_state with
        | Some pr -> Some pr.pr_answer, pr.pr_answer = Valid
        | None -> None, false
Sylvain Dailler's avatar
Sylvain Dailler committed
713
        in
Clément Fumex's avatar
Clément Fumex committed
714
715
        (NProofAttempt (pr, pa.proof_obsolete)),
        {name; proved}
716
*)
Sylvain Dailler's avatar
Sylvain Dailler committed
717

Sylvain Dailler's avatar
Sylvain Dailler committed
718
  (* Create a new node in the_tree, update the tables and send a
Clément Fumex's avatar
Clément Fumex committed
719
     notification about it *)
Sylvain Dailler's avatar
Sylvain Dailler committed
720
  let new_node ~parent node : node_ID =
721
722
    let new_id = fresh () in
      Hint.add model_any new_id node;
723
724
      let node_type = get_node_type node in
      let node_name = get_node_name node in
725
      let node_detached = get_node_detached node in
Sylvain Dailler's avatar
Sylvain Dailler committed
726
      add_node_to_table node new_id;
727
      P.notify (New_node (new_id, parent, node_type, node_name, node_detached));
728
729
      if node_type = NFile then
        read_and_send node_name;
730
      get_node_proved new_id node;
Clément Fumex's avatar
Clément Fumex committed
731
732
      new_id

Sylvain Dailler's avatar
Sylvain Dailler committed
733
734
735
  (****************************)
  (* Iter on the session tree *)
  (****************************)
Sylvain Dailler's avatar
Sylvain Dailler committed
736

737
738
739
740
  (* Iter on the session tree with a function [f parent current] with type
     node_ID -> any -> unit *)
  let iter_subtree_proof_attempt_from_goal
    (f: parent:node_ID -> any -> unit) parent id =
741
    let d = get_server_data () in
Clément Fumex's avatar
Clément Fumex committed
742
    Whyconf.Hprover.iter
743
      (fun _pa panid -> f ~parent (APa panid))
744
      (get_proof_attempt_ids d.cont.controller_session id)
Clément Fumex's avatar
Clément Fumex committed
745

746
747
  let rec iter_subtree_from_goal
    (f: parent:node_ID -> any -> unit) parent id =
748
749
    let d = get_server_data () in
    let ses = d.cont.controller_session in
750
751
    f ~parent (APn id);
    let nid = node_ID_from_pn id in
Clément Fumex's avatar
Clément Fumex committed
752
    List.iter
753
      (fun trans_id -> iter_subtree_from_trans f nid trans_id)
Clément Fumex's avatar
Clément Fumex committed
754
      (get_transformations ses id);
755
    iter_subtree_proof_attempt_from_goal f nid id
Clément Fumex's avatar
Clément Fumex committed
756

757
758
  and iter_subtree_from_trans
    (f: parent:node_ID -> any -> unit) parent trans_id =
759
760
    let d = get_server_data () in
    let ses = d.cont.controller_session in
761
762
    f ~parent (ATn trans_id);
    let nid = node_ID_from_tn trans_id in
Clément Fumex's avatar
Clément Fumex committed
763
    List.iter
764
      (fun goal_id -> (iter_subtree_from_goal f nid goal_id))
Sylvain Dailler's avatar
Sylvain Dailler committed
765
      (get_sub_tasks ses trans_id)
Clément Fumex's avatar
Clément Fumex committed
766

767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
  let iter_subtree_from_theory
    (f: parent:node_ID -> any -> unit) parent theory_id =
    f ~parent (ATh theory_id);
    let nid = node_ID_from_th theory_id in
    List.iter (iter_subtree_from_goal f nid)
               (theory_goals theory_id)

  let iter_subtree_from_file
    (f: parent:node_ID -> any -> unit) parent file =
    f ~parent (AFile file);
    let nid = node_ID_from_file file in
    List.iter (iter_subtree_from_theory f nid)
      file.file_theories

  let iter_the_files (f: parent:node_ID -> any -> unit) parent : unit =
782
783
    let d = get_server_data () in
    let ses = d.cont.controller_session in
Clément Fumex's avatar
Clément Fumex committed
784
785
786
    let files = get_files ses in
    Stdlib.Hstr.iter
      (fun _ file ->
787
        iter_subtree_from_file f parent file)
Sylvain Dailler's avatar
Sylvain Dailler committed
788
      files
Clément Fumex's avatar
Clément Fumex committed
789

Sylvain Dailler's avatar
Sylvain Dailler committed
790
791
792
793
  (**********************************)
  (* Initialization of session tree *)
  (**********************************)

794
795
  let _init_the_tree (): unit =
    let f ~parent node_id = ignore (new_node ~parent node_id) in
Sylvain Dailler's avatar
Sylvain Dailler committed
796
    iter_the_files f root_node
797
798

  let init_and_send_subtree_from_trans parent trans_id : unit =
Clément Fumex's avatar
Clément Fumex committed
799
800
    iter_subtree_from_trans
      (fun ~parent id -> ignore (new_node ~parent id)) parent trans_id
801

Sylvain Dailler's avatar
Sylvain Dailler committed
802
803
  let init_and_send_file f =
    iter_subtree_from_file (fun ~parent id -> ignore (new_node ~parent id))
Sylvain Dailler's avatar
Sylvain Dailler committed
804
      root_node f
Sylvain Dailler's avatar
Sylvain Dailler committed
805

806
  let init_and_send_the_tree (): unit =
Sylvain Dailler's avatar
Sylvain Dailler committed
807
    iter_the_files (fun ~parent id -> ignore (new_node ~parent id)) root_node
808
809
810
811

  let resend_the_tree (): unit =
    let send_node ~parent any =
      let node_id = node_ID_from_any any in
812
813
      let node_name = get_node_name any in
      let node_type = get_node_type any in
814
      let node_detached = get_node_detached any in
815
816
      P.notify (New_node (node_id, parent, node_type, node_name, node_detached));
      get_node_proved node_id any in
Sylvain Dailler's avatar
Sylvain Dailler committed
817
    iter_the_files send_node root_node
818

819

Clément Fumex's avatar
Clément Fumex committed
820
  (* -- send the task -- *)
821
822
  let task_of_id d id =
    let task = get_task d.cont.controller_session id in
823
    let tables = get_table d.cont.controller_session id in
824
825
    (* This function also send source locations associated to the task *)
    let loc_color_list = get_locations task in
826
827
    Pp.string_of
      (Driver.print_task ~cntexample:false ?name_table:tables d.task_driver)
828
      task, loc_color_list
829

Clément Fumex's avatar
Clément Fumex committed
830
  let send_task nid =
831
    let d = get_server_data () in
Clément Fumex's avatar
Clément Fumex committed
832
833
    match any_from_node_ID nid with
    | APn id ->
834
835
       let s, list_loc = task_of_id d id in
       P.notify (Task (nid, s, list_loc))
836
    | ATh t ->
837
       P.notify (Task (nid, "Theory " ^ (theory_name t).Ident.id_string, []))
838
    | APa pid ->
839
840
841
       let pa = get_proof_attempt_node  d.cont.controller_session pid in
       let parid = pa.parent in
       let name = Pp.string_of Whyconf.print_prover pa.prover in
842
843
       let s, list_loc = task_of_id d parid in
       P.notify (Task (nid,s ^ "\n====================> Prover: " ^ name ^ "\n", list_loc))
844
    | AFile f ->
845
       P.notify (Task (nid, "File " ^ f.file_name, []))
846
847
848
    | ATn tid ->
       let name = get_transf_name d.cont.controller_session tid in
       let args = get_transf_args d.cont.controller_session tid in
849
       let parid = get_trans_parent d.cont.controller_session tid in
850
851
       let s, list_loc = task_of_id d parid in
       P.notify (Task (nid, s ^ "\n====================> Transformation: " ^ String.concat " " (name :: args) ^ "\n", list_loc))
852

Sylvain Dailler's avatar
Sylvain Dailler committed
853
854
855
856
857
858
859
860
861
862
863
864
  (* -------------------- *)

  (* Add a file into the session when (Add_file_req f) is sent *)
  (* Note that f is the path from execution directory to the file and fn is the
     path from the session directory to the file. *)
  let add_file_to_session cont f =
    let fn = Sysutil.relativize_filename
      (Session_itp.get_dir cont.controller_session) f in
    let files = get_files cont.controller_session in
    if (not (Stdlib.Hstr.mem files fn)) then
      if (Sys.file_exists f) then
      begin
865
866
867
868
        let b = add_file cont f in
        if b then
          let file = Stdlib.Hstr.find files fn in
          init_and_send_file file
Sylvain Dailler's avatar
Sylvain Dailler committed
869
870
      end
      else
MARCHE Claude's avatar
MARCHE Claude committed
871
        P.notify (Message (Open_File_Error ("File not found: " ^ f)))
872
    else
Sylvain Dailler's avatar
Sylvain Dailler committed
873
      P.notify (Message (Open_File_Error ("File already in session: " ^ fn)))
874
875


876
  (* ------------ init server ------------ *)
877

878
879
880
881
882
883
884
885
886
  let init_server config env f =
    Debug.dprintf debug "[ITP server] loading session %s@." f;
    let ses,use_shapes = Session_itp.load_session f in
    Debug.dprintf debug "[ITP server] creating controller@.";
    let c = create_controller config env ses in
    let task_driver = task_driver config env in
    server_data := Some
                     { task_driver = task_driver;
                       cont = c };
887
    let d = get_server_data () in
888
    let prover_list = get_prover_list config in
889
890
    let transformation_list = List.map fst (list_transforms ()) in
    let strategies_list =
891
      let l = strategies d.cont.controller_env config loaded_strategies in
892
893
894
895
896
897
898
899
      List.map (fun (a,_,_,_) -> a) l
    in
    let infos =
      {
        provers = prover_list;
        transformations = transformation_list;
        strategies = strategies_list;
        commands =
900
          Hstr.fold (fun c _ acc -> c :: acc) commands_table []
901
902
      }
    in
903
904
905
906
907
908
909
910
911
    Debug.dprintf debug "[ITP server] sending initialization infos@.";
    P.notify (Initialized infos);
    Debug.dprintf debug "[ITP server] reloading source files@.";
    let b = reload_files d.cont ~use_shapes in
    if b then
      init_and_send_the_tree ()
    else
      load_files_session ()

912

Clément Fumex's avatar
Clément Fumex committed
913
914
915
916
917
  (* ----------------- Schedule proof attempt -------------------- *)

  (* Callback of a proof_attempt *)
  let callback_update_tree_proof cont panid pa_status =
    let ses = cont.controller_session in
Clément Fumex's avatar
Clément Fumex committed
918
    begin match pa_status with
Clément Fumex's avatar
Clément Fumex committed
919
920
921
922
923
924
925
926
927
928
    | Scheduled ->
      begin
        try
          ignore (node_ID_from_pan panid)
        (* TODO: do we notify here ? *)
        with Not_found ->
          let parent_id = get_proof_attempt_parent ses panid in
          let parent = node_ID_from_pn parent_id in
          ignore (new_node ~parent (APa panid))
      end
929
    | _  -> () (* TODO ? status like Uninstalled should not generate a Notification *)
Clément Fumex's avatar
Clément Fumex committed
930
    end;
931
932
933
    let limit = (get_proof_attempt_node cont.controller_session panid).limit in
    let new_status = Proof_status_change (pa_status, false, limit) in
    P.notify (Node_change (node_ID_from_pan panid, new_status))
Clément Fumex's avatar
Clément Fumex committed
934

935
936
  let notify_change_proved c x =
    try
937
      let node_ID = node_ID_from_any x in
938
939
940
941
942
943
944
      let b = any_proved c x in
      P.notify (Node_change (node_ID, Proved b));
      match x with
      | APa pa ->
         let obs = (get_proof_attempt_node c.controller_session pa).proof_obsolete in
         P.notify (Node_change (node_ID, Obsolete obs))
      | _ -> ()
945
946
    with Not_found -> ()

947
  let schedule_proof_attempt ~counterexmp nid (p: Whyconf.config_prover) limit =
948
    let d = get_server_data () in
Clément Fumex's avatar
Clément Fumex committed
949
    let prover = p.Whyconf.prover in
950
    let callback = callback_update_tree_proof d.cont in
951
    let unproven_goals = unproven_goals_below_id d.cont (any_from_node_ID nid) in
952
    List.iter (fun id -> C.schedule_proof_attempt d.cont id prover ~counterexmp
953
                ~limit ~callback ~notification:(notify_change_proved d.cont))
954
      unproven_goals
Clément Fumex's avatar
Clément Fumex committed
955

Sylvain Dailler's avatar
Sylvain Dailler committed
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
  let callback_edition cont panid pa_status =
    let ses = cont.controller_session in
    begin match pa_status with
    | Running ->
      begin
        try
          ignore (node_ID_from_pan panid)
        with Not_found ->
          let parent_id = get_proof_attempt_parent ses panid in
          let parent = node_ID_from_pn parent_id in
          ignore (new_node ~parent (APa panid))
      end
    | _  -> ()
    end;
    let limit = (get_proof_attempt_node cont.controller_session panid).limit in
    let new_status = Proof_status_change (pa_status, false, limit) in
    P.notify (Node_change (node_ID_from_pan panid, new_status))

  let schedule_edition (nid: node_ID) (p: Whyconf.config_prover) =
    let d = get_server_data () in
    let prover = p.Whyconf.prover in
    let callback = callback_edition d.cont in
    match any_from_node_ID nid with
    | APn id ->
        C.schedule_edition d.cont id prover ?file:None
          ~callback ~notification:(notify_change_proved d.cont)
    | _ -> ()

Clément Fumex's avatar
Clément Fumex committed
984
985
986
987
  (* ----------------- Schedule transformation -------------------- *)

  (* Callback of a transformation *)
  let callback_update_tree_transform status =
988
    let d = get_server_data () in
Clément Fumex's avatar
Clément Fumex committed
989
990
    match status with
    | TSdone trans_id ->
991
      let ses = d.cont.controller_session in
Clément Fumex's avatar
Clément Fumex committed
992
993
      let id = get_trans_parent ses trans_id in
      let nid = node_ID_from_pn id in
994
      init_and_send_subtree_from_trans nid trans_id
Clément Fumex's avatar
Clément Fumex committed
995
996
    | TSfailed (id, e) ->
      let msg =
997
        Pp.sprintf "%a" (get_exception_message d.cont.controller_session id) e
Clément Fumex's avatar
Clément Fumex committed
998
      in
Sylvain Dailler's avatar
Sylvain Dailler committed
999
      P.notify (Message (Transf_error (node_ID_from_pn id, msg)))
Clément Fumex's avatar
Clément Fumex committed
1000
1001
1002
    | _ -> ()

  let rec apply_transform nid t args =
1003
    let d = get_server_data () in
Clément Fumex's avatar
Clément Fumex committed
1004
1005
1006
    match any_from_node_ID nid with
    | APn id ->
      let callback = callback_update_tree_transform in
1007
      C.schedule_transformation d.cont id t args ~callback ~notification:(notify_change_proved d.cont)
Clément Fumex's avatar
Clément Fumex committed
1008
    | APa panid ->
1009
      let parent_id = get_proof_attempt_parent d.cont.controller_session panid in
Clément Fumex's avatar
Clément Fumex committed
1010
1011
1012
1013
1014
1015
1016
1017
      let parent = node_ID_from_pn parent_id in
      apply_transform parent t args
    | ATn _ | AFile _ | ATh _ ->
      (* TODO: propagate trans to all subgoals, just the first one, do nothing ... ?  *)
      ()

  (* ----------------- run strategy -------------------- *)

MARCHE Claude's avatar
MARCHE Claude committed
1018
1019
  let debug_strat = Debug.register_flag "strategy_exec" ~desc:"Trace strategies execution"

1020
  let run_strategy_on_task ~counterexmp nid s =
1021
    let d = get_server_data () in
1022
    let unproven_goals = unproven_goals_below_id d.cont (any_from_node_ID nid) in
1023
    let l = strategies d.cont.controller_env d.cont.controller_config loaded_strategies in
1024
1025
1026
    let st = List.filter (fun (_,c,_,_) -> c=s) l in
    match st with
    | [(n,_,_,st)] ->
MARCHE Claude's avatar
MARCHE Claude committed
1027
        Debug.dprintf debug_strat "[strategy_exec] running strategy '%s'@." n;
1028
       let callback sts =
MARCHE Claude's avatar
MARCHE Claude committed
1029
         Debug.dprintf debug_strat "[strategy_exec] strategy status: %a@." print_strategy_status sts
1030
1031
1032
1033
       in
       let callback_pa = callback_update_tree_proof d.cont in
       let callback_tr st = callback_update_tree_transform st in
       List.iter (fun id ->
1034
1035
                  C.run_strategy_on_goal d.cont id st ~counterexmp
                    ~callback_pa ~callback_tr ~callback ~notification:(notify_change_proved d.cont))
1036
                 unproven_goals
MARCHE Claude's avatar
MARCHE Claude committed
1037
    | _ ->  Debug.dprintf debug_strat "[strategy_exec] strategy '%s' not found@." s
Clément Fumex's avatar
Clément Fumex committed
1038

1039
1040
1041
1042
1043
1044
1045
1046

  (* ----------------- Clean session -------------------- *)
  let clean_session () =
    let d = get_server_data () in
    let remove x =
      let nid = node_ID_from_any x in
      remove_any_node_ID x;
      P.notify (Remove nid) in
MARCHE Claude's avatar
MARCHE Claude committed
1047
    C.clean_session d.cont ~remove
1048
1049


Sylvain Dailler's avatar
Sylvain Dailler committed
1050
1051
  (* ----------------- Save session --------------------- *)
  let save_session () =
1052
1053
    let d = get_server_data () in
    Session_itp.save_session d.cont.controller_session;
Sylvain Dailler's avatar
Sylvain Dailler committed
1054
1055
1056
1057
    P.notify Saved

  (* ----------------- Reload session ------------------- *)
  let clear_tables () : unit =
1058
1059
    reset ();
    Hint.clear model_any;
Sylvain Dailler's avatar
Sylvain Dailler committed
1060
1061
1062
1063
1064
1065
1066
    Hpan.clear pan_to_node_ID;
    Hpn.clear pn_to_node_ID;
    Htn.clear tn_to_node_ID;
    Ident.Hid.clear th_to_node_ID;
    Hstr.clear file_to_node_ID

  let reload_session () : unit =
1067
    let d = get_server_data () in
Sylvain Dailler's avatar
Sylvain Dailler committed
1068
    clear_tables ();
1069
    (* Calling reload_files breaks the controller if it fails *)
1070
    let b = reload_files d.cont ~use_shapes:true in
1071
1072
    if b then init_and_send_the_tree ()

Sylvain Dailler's avatar
Sylvain Dailler committed
1073
1074

  let replay_session () : unit =
1075
    let d = get_server_data () in
1076
1077
    let callback = callback_update_tree_proof d.cont in
    let final_callback lr =
1078
      P.notify (Message (Replay_Info (Pp.string_of C.replay_print lr))) in
Sylvain Dailler's avatar
Sylvain Dailler committed
1079
    (* TODO make replay print *)
1080
    C.replay ~use_steps:false ~obsolete_only:true d.cont
1081
             ~callback ~notification:(notify_change_proved d.cont) ~final_callback
Sylvain Dailler's avatar
Sylvain Dailler committed
1082

1083
1084
1085
  let () = register_command "replay" "replay obsolete proofs"
    (Qnotask (fun _cont _args ->  replay_session (); "replay in progress, be patient"))

1086
1087
1088
1089
  (* ---------------- Mark obsolete ------------------ *)
  let mark_obsolete n =
    let d = get_server_data () in
    let any = any_from_node_ID n in
1090
(*
1091
1092
1093
    let node_obsolete x b =
      let nid = node_ID_from_any x in
      P.notify (Node_change (nid, Obsolete b)) in
1094
1095
 *)
    C.mark_as_obsolete (* ~node_obsolete *) ~notification:(notify_change_proved d.cont) d.cont any
1096

1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
  (* ----------------- locate next unproven node -------------------- *)

  let notify_first_unproven_node d ni =
    let any = any_from_node_ID ni in
      let unproven_any =
        get_first_unproven_goal_around
          ~proved:(Controller_itp.any_proved d.cont)
          ~children:(get_undetached_children_no_pa d.cont.controller_session)
          ~get_parent:(get_any_parent d.cont.controller_session)
          ~is_goal:(fun any -> match any with | APn _ -> true | _ -> false)
          ~is_pa:(fun any -> match any with | APa _ -> true | _ -> false)
          any in
      begin
        match unproven_any with
        | None -> () (* If no node is found we don't tell IDE to move *)
        | Some any ->
            P.notify (Next_Unproven_Node_Id (ni, node_ID_from_any any))
      end


Clément Fumex's avatar
Clément Fumex committed
1117
  (* ----------------- treat_request -------------------- *)
Clément Fumex's avatar
Clément Fumex committed
1118

Sylvain Dailler's avatar
Sylvain Dailler committed
1119
1120
1121
1122
1123
1124
1125
1126
  let get_proof_node_id nid =
    try
      match any_from_node_ID nid with
      | APn pn_id -> Some pn_id
      | _ -> None
    with
      Not_found -> None

1127
  let rec treat_request r =
1128
    let d = get_server_data () in
1129
    let config = d.cont.controller_config in
1130
1131
    try (
    match r with
1132
    | Prove_req (nid,p,limit)      ->
Sylvain Dailler's avatar
Sylvain Dailler committed
1133
1134
1135
1136
1137
      let p = try Some (get_prover p) with
      | Bad_prover_name p -> P.notify (Message (Proof_error (nid, "Bad prover name" ^ p))); None
      in
      begin match p with
      | None -> ()
1138
      | Some p ->
1139
          let counterexmp = Whyconf.cntexample (Whyconf.get_main config) in
1140
          schedule_proof_attempt ~counterexmp nid p limit
Sylvain Dailler's avatar
Sylvain Dailler committed
1141
      end
1142
    | Transform_req (nid, t, args) -> apply_transform nid t args
1143
    | Strategy_req (nid, st)       ->
1144
        let counterexmp = Whyconf.cntexample (Whyconf.get_main config) in
1145
        run_strategy_on_task ~counterexmp nid st
Sylvain Dailler's avatar
Sylvain Dailler committed
1146
1147
1148
1149
1150
1151
1152
1153
1154
    | Edit_req (nid, p)            ->
      let p = try Some (get_prover p) with
      | Bad_prover_name p -> P.notify (Message (Proof_error (nid, "Bad prover name" ^ p))); None
      in
      begin match p with
      | None -> ()
      | Some p ->
          schedule_edition nid p
      end
1155
    | Clean_req                    -> clean_session ()
1156
    | Save_req                     -> save_session ()
Sylvain Dailler's avatar
Sylvain Dailler committed
1157
    | Reload_req                   -> reload_session ()
1158
    | Get_Session_Tree_req         -> resend_the_tree ()
1159
1160
    | Get_first_unproven_node ni   ->
      notify_first_unproven_node d ni
Sylvain Dailler's avatar
Sylvain Dailler committed
1161
1162
1163
1164
1165
    | Focus_req nid ->
        let any = any_from_node_ID nid in
        focused_node := Some any
    | Unfocus_req ->
        focused_node := None
1166
1167
1168
1169
    | Remove_subtree nid           ->
        let n = any_from_node_ID nid in
        begin
        try
1170
          Controller_itp.remove_subtree d.cont n
1171
            ~notification:(notify_change_proved d.cont)
1172
1173
1174
1175
            ~removed:(fun x ->
                        let nid = node_ID_from_any x in
                        remove_any_node_ID x;
                        P.notify (Remove nid))
1176
        with RemoveError -> (* TODO send an error instead of information *)
1177
          P.notify (Message (Information "Cannot remove attached proof nodes or theories, and proof_attempt that did not yet return"))
1178
        end
Sylvain Dailler's avatar
Sylvain Dailler committed
1179
1180
1181
    | Copy_paste (from_id, to_id)    ->
        let from_any = any_from_node_ID from_id in
        let to_any = any_from_node_ID to_id in
1182
        C.copy_paste ~notification:(notify_change_proved d.cont)
Sylvain Dailler's avatar
Sylvain Dailler committed
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
          ~callback_pa:(callback_update_tree_proof d.cont)
          ~callback_tr:(callback_update_tree_transform)
          d.cont from_any to_any

    | Copy_detached from_id        ->
        let from_any = any_from_node_ID from_id in
        let copy ~parent p =
          let parent = node_ID_from_any parent in
          ignore (new_node ~parent p)
        in
        C.copy_detached ~copy d.cont from_any
1194
    | Get_file_contents f          ->