Debian Codegraph @

stm/stm.ml

raw symbols SCIP
1 (************************************************************************)
2 (* * The Rocq Prover / The Rocq Development Team *)
3 (* v * Copyright INRIA, CNRS and contributors *)
4 (* <O___,, * (see version control and CREDITS file for authors & dates) *)
5 (* \VV/ **************************************************************)
6 (* // * This file is distributed under the terms of the *)
7 (* * GNU Lesser General Public License Version 2.1 *)
8 (* * (see LICENSE file for the text of the license) *)
9 (************************************************************************)
10
11 (* enable in case of stm problems *)
12 (* let stm_debug () = CDebug.(get_flag misc) *)
13 let stm_debug = ref false
14
15 let stm_pr_err s = Format.eprintf "%s] %s\n%!" (Spawned.process_id ()) s
16 let stm_pp_err pp = Format.eprintf "%s] @[%a@]\n%!" (Spawned.process_id ()) Pp.pp_with pp
17
18 let stm_prerr_endline s = if !stm_debug then begin stm_pr_err (s ()) end else ()
19 let stm_pperr_endline s = if !stm_debug then begin stm_pp_err (s ()) end else ()
20
21 let stm_prerr_debug s = if CDebug.(get_flag misc) then begin stm_pr_err (s ()) end else ()
22
23 open Pp
24 open CErrors
25 open Names
26 open Feedback
27 open Vernacexpr
28 open Vernacextend
29
30 module PG_compat = Vernacstate.Declare [@@ocaml.warning "-3"]
31
32 let is_vtkeep = function VtKeep _ -> true | _ -> false
33 let get_vtkeep = function VtKeep x -> x | _ -> assert false
34
35 module AsyncOpts = struct
36
37 type cache = Force
38 type async_proofs = APoff | APonLazy | APon
39 type tac_error_filter = FNone | FOnly of string list | FAll
40
41 type stm_opt = {
42 spawn_args : string list;
43
44 async_proofs_n_workers : int;
45 async_proofs_n_tacworkers : int;
46
47 async_proofs_cache : cache option;
48 async_proofs_mode : async_proofs;
49
50 async_proofs_private_flags : string option;
51 async_proofs_never_reopen_branch : bool;
52
53 async_proofs_tac_error_resilience : tac_error_filter;
54 async_proofs_cmd_error_resilience : bool;
55 async_proofs_delegation_threshold : float;
56
57 async_proofs_worker_priority : CoqworkmgrApi.priority;
58 }
59
60 let default_opts ~spawn_args = {
61 spawn_args;
62
63 async_proofs_n_workers = 1;
64 async_proofs_n_tacworkers = 2;
65
66 async_proofs_cache = None;
67
68 async_proofs_mode = APoff;
69
70 async_proofs_private_flags = None;
71 async_proofs_never_reopen_branch = false;
72
73 async_proofs_tac_error_resilience = FOnly [ "curly" ];
74 async_proofs_cmd_error_resilience = true;
75 async_proofs_delegation_threshold = 0.03;
76
77 async_proofs_worker_priority = CoqworkmgrApi.Low;
78 }
79
80 let cur_opt : stm_opt option ref = ref None
81 let set_cur_opt o = assert (Option.is_empty !cur_opt); cur_opt := Some o
82 let cur_opt () = match !cur_opt with
83 | Some o -> o
84 | None ->
85 anomaly Pp.(str "Incorrect stm init: accessing options before they are set.")
86 end
87
88 open AsyncOpts
89
90 let async_proofs_is_master opt =
91 opt.async_proofs_mode = APon &&
92 !Flags.async_proofs_worker_id = "master"
93
94 let execution_error ?loc state_id msg =
95 feedback ~id:state_id (Message (Error, loc, [], msg))
96
97 module Hooks = struct
98
99 let state_computed = ref (fun ~doc:_ state_id ~in_cache ->
100 feedback ~id:state_id Processed)
101
102 let state_ready = ref (fun ~doc:_ state_id -> ())
103
104 let forward_feedback =
105 let m = Mutex.create () in
106 ref (function
107 | { doc_id = did; span_id = id; route; contents } ->
108 CThread.with_lock m ~scope:(fun () -> feedback ~did ~id ~route contents))
109
110 let unreachable_state = ref (fun ~doc:_ _ _ -> ())
111
112 let document_add = ref (fun _ _ -> ())
113
114 let document_edit = ref (fun _ -> ())
115
116 let sentence_exec = ref (fun _ -> ())
117
118 end
119
120 let async_proofs_workers_extra_env = ref [||]
121
122 type aast = {
123 verbose : bool;
124 indentation : int;
125 strlen : int;
126 mutable expr : vernac_control; (* mutable: Proof using hinted by aux file *)
127 }
128 let pr_ast { expr; indentation } = Pp.(int indentation ++ str " " ++ Ppvernac.pr_vernac expr)
129
130 (* Commands piercing opaque (probably should be using the vernactypes system instead) *)
131 let may_pierce_opaque = function
132 | VernacSynPure (VernacPrint _) -> true
133 | VernacSynterp (VernacExtend ({ ext_plugin = "rocq-runtime.plugins.extraction" }, _)) -> true
134 | _ -> false
135
136 type depth = int
137 type 'branch branch_type_gen =
138 | Master
139 | Proof of depth
140 | Edit of
141 Stateid.t * Stateid.t * Vernacextend.vernac_qed_type * 'branch
142
143 module Kind =
144 struct
145 type 'a t = 'a branch_type_gen
146 let master = Master
147 end
148
149 module Vcs_ = Vcs.Make(Stateid.Self)(Kind)
150 type future_proof = Declare.Proof.closed_proof_output option Future.computation
151
152 type branch_type = Vcs_.Branch.t Kind.t
153 (* TODO 8.7 : split commands and tactics, since this type is too messy now *)
154 type cqueue = MainQueue | SkipQueue
155 type cmd_t = {
156 ctac : bool; (* is a tactic *)
157 ceff : bool; (* is a side-effecting command in the middle of a proof *)
158 cast : aast;
159 cids : Names.Id.t list;
160 cblock : proof_block_name option;
161 cqueue : cqueue;
162 cancel_switch : AsyncTaskQueue.cancel_switch; }
163 type fork_t = aast * Vcs_.Branch.t * opacity_guarantee * Names.Id.t list
164 type qed_t = {
165 qast : aast;
166 keep : vernac_qed_type;
167 mutable fproof : (future_proof option * AsyncTaskQueue.cancel_switch) option;
168 brname : Vcs_.Branch.t;
169 brinfo : Vcs_.branch_info
170 }
171 type seff_t = ReplayCommand of aast | CherryPickEnv
172 type alias_t = Stateid.t * aast
173
174 type transaction =
175 | Cmd of cmd_t
176 | Fork of fork_t
177 | Qed of qed_t
178 | Sideff of seff_t
179 | Alias of alias_t
180 | Noop
181 type step =
182 | SCmd of cmd_t
183 | SFork of fork_t * Stateid.t option
184 | SQed of qed_t * Stateid.t
185 | SSideff of seff_t * Stateid.t
186 | SAlias of alias_t
187
188 type visit = { step : step; next : Stateid.t }
189
190 let mkTransTac cast cblock cqueue =
191 Cmd { ctac = true; cast; cblock; cqueue; cids = []; ceff = false; cancel_switch = ref false }
192
193 let mkTransCmd cast cids ceff cqueue =
194 Cmd { ctac = false; cast; cblock = None; cqueue; cids; ceff; cancel_switch = ref false }
195
196 type cached_state =
197 | EmptyState
198 | ParsingState of Procq.frozen_t
199 | FullState of Vernacstate.t
200 | ErrorState of Procq.frozen_t option * Exninfo.iexn
201 type branch = Vcs_.Branch.t * Vcs_.branch_info
202 type backup = { mine : branch; others : branch list }
203
204 module DynBlockData : Dyn.S = Dyn.Make ()
205
206 (* Clusters of nodes implemented as Dag properties. While Dag and Vcs impose
207 * no constraint on properties, here we impose boxes to be non overlapping.
208 * Such invariant makes sense for the current kinds of boxes (proof blocks and
209 * entire proofs) but may make no sense and dropped/refined in the future.
210 * Such invariant is useful to detect broken proof block detection code *)
211 type box =
212 | ProofTask of pt
213 | ProofBlock of static_block_declaration * proof_block_name
214 and pt = { (* TODO: inline records in OCaml 4.03 *)
215 lemma : Stateid.t;
216 qed : Stateid.t;
217 }
218 and static_block_declaration = {
219 block_start : Stateid.t;
220 block_stop : Stateid.t;
221 dynamic_switch : Stateid.t;
222 carry_on_data : DynBlockData.t;
223 }
224
225 (* Functions that work on a Vcs with a specific branch type *)
226 module Vcs_aux : sig
227
228 val proof_nesting : ('t,'i,'c) Vcs_.t -> int
229 val find_proof_at_depth :
230 ('t, 'i,'c) Vcs_.t -> int ->
231 Vcs_.Branch.t * Vcs_.branch_info
232 exception Expired
233 val visit : (transaction,'i,'c) Vcs_.t -> Vcs_.Dag.node -> visit
234
235 end = struct (* {{{ *)
236
237 let proof_nesting vcs =
238 List.fold_left max 0
239 (CList.map_filter
240 (function
241 | { Vcs_.kind = Proof n } -> Some n
242 | { Vcs_.kind = Edit _ } -> Some 1
243 | _ -> None)
244 (List.map (Vcs_.get_branch vcs) (Vcs_.branches vcs)))
245
246 let find_proof_at_depth vcs pl =
247 try List.find (function
248 | _, { Vcs_.kind = Proof n } -> Int.equal n pl
249 | _, { Vcs_.kind = Edit _ } -> anomaly(Pp.str "find_proof_at_depth")
250 | _ -> false)
251 (List.map (fun h -> h, Vcs_.get_branch vcs h) (Vcs_.branches vcs))
252 with Not_found -> failwith "find_proof_at_depth"
253
254 exception Expired
255 let visit vcs id =
256 if Stateid.equal id Stateid.initial then
257 anomaly(Pp.str "Visiting the initial state id.")
258 else if Stateid.equal id Stateid.dummy then
259 anomaly(Pp.str "Visiting the dummy state id.")
260 else
261 try
262 match Vcs_.Dag.from_node (Vcs_.dag vcs) id with
263 | [n, Cmd x] -> { step = SCmd x; next = n }
264 | [n, Alias x] -> { step = SAlias x; next = n }
265 | [n, Fork x] -> { step = SFork (x,None); next = n }
266 | [n, Fork x; p, Noop] -> { step = SFork (x,Some p); next = n }
267 | [p, Noop; n, Fork x] -> { step = SFork (x,Some p); next = n }
268 | [n, Qed x; p, Noop]
269 | [p, Noop; n, Qed x] -> { step = SQed (x,p); next = n }
270 | [n, Sideff CherryPickEnv; p, Noop]
271 | [p, Noop; n, Sideff CherryPickEnv]-> { step = SSideff (CherryPickEnv, p); next = n }
272 | [n, Sideff (ReplayCommand x); p, Noop]
273 | [p, Noop; n, Sideff (ReplayCommand x)]-> { step = SSideff(ReplayCommand x,p); next = n }
274 | [n, Sideff (ReplayCommand x)]-> {step = SSideff(ReplayCommand x, Stateid.dummy); next=n}
275 | _ -> anomaly (Pp.str ("Malformed VCS at node "^Stateid.to_string id^"."))
276 with Not_found -> raise Expired
277
278 end (* }}} *)
279
280 (*************************** THE DOCUMENT *************************************)
281 (******************************************************************************)
282
283 (* The main document type associated to a VCS *)
284 type stm_doc_type =
285 | VoDoc of string
286 | VosDoc of string
287 | Interactive of Coqargs.top
288
289 (* Dummy until we land the functional interp patch + fixed start_library *)
290 type doc = int
291 let dummy_doc : doc = 0
292
293 (* Imperative wrap around VCS to obtain _the_ VCS that is the
294 * representation of the document Rocq is currently processing *)
295 module VCS : sig
296
297 exception Expired
298
299 module Branch : (module type of Vcs_.Branch with type t = Vcs_.Branch.t)
300 type id = Stateid.t
301 type branch_info = Vcs_.branch_info = {
302 kind : branch_type;
303 root : id;
304 pos : id;
305 }
306
307 type vcs = (transaction, state_info, box) Vcs_.t
308 and state_info = { (* TODO: Make this record private to VCS *)
309 mutable n_reached : int; (* debug cache: how many times was computed *)
310 mutable n_goals : int; (* open goals: indentation *)
311 mutable state : cached_state; (* state value *)
312 mutable proof_mode : Pvernac.proof_mode option;
313 mutable vcs_backup : vcs option * backup option;
314 }
315
316 val init : stm_doc_type -> id -> Procq.frozen_t -> doc
317 (* val get_type : unit -> stm_doc_type *)
318 val set_ldir : Names.DirPath.t -> unit
319 val get_ldir : unit -> Names.DirPath.t
320
321 val is_interactive : unit -> bool
322 val is_vos_doc : unit -> bool
323
324 val current_branch : unit -> Branch.t
325 val checkout : Branch.t -> unit
326 val branches : unit -> Branch.t list
327 val get_branch : Branch.t -> branch_info
328 val get_branch_pos : Branch.t -> id
329 val new_node : ?id:Stateid.t -> Pvernac.proof_mode option -> unit -> id
330 val merge : id -> ours:transaction -> ?into:Branch.t -> Branch.t -> unit
331 val rewrite_merge : id -> ours:transaction -> at:id -> Branch.t -> unit
332 val delete_branch : Branch.t -> unit
333 val commit : id -> transaction -> unit
334 val mk_branch_name : aast -> Branch.t
335 val edit_branch : Branch.t
336 val branch : ?root:id -> ?pos:id -> Branch.t -> branch_type -> unit
337 val reset_branch : Branch.t -> id -> unit
338 val reachable : id -> Stateid.Set.t
339 val cur_tip : unit -> id
340
341 val get_info : id -> state_info
342 val reached : id -> unit
343 val goals : id -> int -> unit
344 val set_state : id -> cached_state -> unit
345 val get_state : id -> cached_state
346 val set_parsing_state : id -> Procq.frozen_t -> unit
347 val get_parsing_state : id -> Procq.frozen_t option
348 val get_proof_mode : id -> Pvernac.proof_mode option
349
350 (* cuts from start -> stop, raising Expired if some nodes are not there *)
351 val slice : block_start:id -> block_stop:id -> vcs
352 val nodes_in_slice : block_start:id -> block_stop:id -> Stateid.t list
353
354 val create_proof_task_box : id list -> qed:id -> block_start:id -> unit
355 val create_proof_block : static_block_declaration -> string -> unit
356 val box_of : id -> box list
357 val delete_boxes_of : id -> unit
358 val proof_task_box_of : id -> pt option
359
360 val proof_nesting : unit -> int
361 val checkout_shallowest_proof_branch : unit -> unit
362 val propagate_sideff : action:seff_t -> Stateid.t list
363 val propagate_qed : unit -> unit
364
365 val gc : unit -> unit
366
367 val visit : id -> visit
368
369 val print : ?now:bool -> unit -> unit
370
371 val backup : unit -> vcs
372 val restore : vcs -> unit
373
374 end = struct (* {{{ *)
375
376 include Vcs_
377 exception Expired = Vcs_aux.Expired
378
379 open Printf
380
381 type vcs = (transaction, state_info, box) t
382 and state_info = { (* TODO: Make this record private to VCS *)
383 mutable n_reached : int; (* debug cache: how many times was computed *)
384 mutable n_goals : int; (* open goals: indentation *)
385 mutable state : cached_state; (* state value *)
386 mutable proof_mode : Pvernac.proof_mode option;
387 mutable vcs_backup : vcs option * backup option;
388 }
389 let default_info proof_mode =
390 {
391 n_reached = 0; n_goals = 0;
392 state = EmptyState;
393 proof_mode;
394 vcs_backup = (None,None);
395 }
396
397 let print_dag vcs () =
398
399 (* Due to threading, be wary that this will be called from the
400 toplevel with we_are_parsing set to true, as indeed, the
401 toplevel is waiting for input . What a race! XD
402
403 In case you are hitting the race enable stm_debug.
404 *)
405 Flags.in_synterp_phase := Some false;
406
407 let fname =
408 "stm_" ^ Str.global_replace (Str.regexp " ") "_" (Spawned.process_id ()) in
409 let string_of_transaction = function
410 | Cmd { cast = t } | Fork (t, _,_,_) ->
411 (try Pp.string_of_ppcmds (pr_ast t) with e when CErrors.noncritical e -> "ERR")
412 | Sideff (ReplayCommand t) ->
413 sprintf "Sideff(%s)"
414 (try Pp.string_of_ppcmds (pr_ast t) with e when CErrors.noncritical e -> "ERR")
415 | Sideff CherryPickEnv -> "EnvChange"
416 | Noop -> " "
417 | Alias (id,_) -> sprintf "Alias(%s)" (Stateid.to_string id)
418 | Qed { qast } -> Pp.string_of_ppcmds (pr_ast qast) in
419 let is_green id =
420 match get_info vcs id with
421 | Some { state = FullState _ } -> true
422 | _ -> false in
423 let is_red id =
424 match get_info vcs id with
425 | Some { state = ErrorState _ } -> true
426 | _ -> false in
427 let head = current_branch vcs in
428 let heads =
429 List.map (fun x -> x, (get_branch vcs x).pos) (branches vcs) in
430 let graph = dag vcs in
431 let quote s =
432 Str.global_replace (Str.regexp "\n") "<BR/>"
433 (Str.global_replace (Str.regexp "<") "&lt;"
434 (Str.global_replace (Str.regexp ">") "&gt;"
435 (Str.global_replace (Str.regexp "\"") "&quot;"
436 (Str.global_replace (Str.regexp "&") "&amp;"
437 (String.sub s 0 (min (String.length s) 20)))))) in
438 let fname_dot, fname_ps =
439 let f = "/tmp/" ^ Filename.basename fname in
440 f ^ ".dot", f ^ ".pdf" in
441 let node id = "s" ^ Stateid.to_string id in
442 let edge tr =
443 sprintf "<<FONT POINT-SIZE=\"12\" FACE=\"sans\">%s</FONT>>"
444 (quote (string_of_transaction tr)) in
445 let node_info id =
446 match get_info vcs id with
447 | None -> ""
448 | Some info ->
449 sprintf "<<FONT POINT-SIZE=\"12\">%s</FONT>" (Stateid.to_string id) ^
450 sprintf " <FONT POINT-SIZE=\"11\">r:%d g:%d</FONT>>"
451 info.n_reached info.n_goals in
452 let color id =
453 if is_red id then "red" else if is_green id then "green" else "white" in
454 let nodefmt oc id =
455 fprintf oc "%s [label=%s,style=filled,fillcolor=%s];\n"
456 (node id) (node_info id) (color id) in
457
458 let ids = ref Stateid.Set.empty in
459 let boxes = ref [] in
460 (* Fill in *)
461 Dag.iter graph (fun from _ _ l ->
462 ids := Stateid.Set.add from !ids;
463 List.iter (fun box -> boxes := box :: !boxes)
464 (Dag.property_of graph from);
465 List.iter (fun (dest, _) ->
466 ids := Stateid.Set.add dest !ids;
467 List.iter (fun box -> boxes := box :: !boxes)
468 (Dag.property_of graph dest))
469 l);
470 boxes := CList.sort_uniquize Dag.Property.compare !boxes;
471
472 let oc = open_out fname_dot in
473 output_string oc "digraph states {\n";
474 Dag.iter graph (fun from cf _ l ->
475 List.iter (fun (dest, trans) ->
476 fprintf oc "%s -> %s [xlabel=%s,labelfloat=true];\n"
477 (node from) (node dest) (edge trans)) l
478 );
479
480 let contains b1 b2 =
481 Stateid.Set.subset
482 (Dag.Property.having_it b2) (Dag.Property.having_it b1) in
483 let same_box = Dag.Property.equal in
484 let outerboxes boxes =
485 List.filter (fun b ->
486 not (List.exists (fun b1 ->
487 not (same_box b1 b) && contains b1 b) boxes)
488 ) boxes in
489 let rec rec_print b =
490 boxes := CList.remove same_box b !boxes;
491 let sub_boxes = List.filter (contains b) (outerboxes !boxes) in
492 fprintf oc "subgraph cluster_%s {\n" (Dag.Property.to_string b);
493 List.iter rec_print sub_boxes;
494 Stateid.Set.iter (fun id ->
495 if Stateid.Set.mem id !ids then begin
496 ids := Stateid.Set.remove id !ids;
497 nodefmt oc id
498 end)
499 (Dag.Property.having_it b);
500 match Dag.Property.data b with
501 | ProofBlock ({ dynamic_switch = id }, lbl) ->
502 fprintf oc "label=\"%s (test:%s)\";\n" lbl (Stateid.to_string id);
503 fprintf oc "color=red; }\n"
504 | ProofTask _ -> fprintf oc "color=blue; }\n"
505 in
506 List.iter rec_print (outerboxes !boxes);
507 Stateid.Set.iter (nodefmt oc) !ids;
508
509 List.iteri (fun i (b,id) ->
510 let shape = if Branch.equal head b then "box3d" else "box" in
511 fprintf oc "b%d -> %s;\n" i (node id);
512 fprintf oc "b%d [shape=%s,label=\"%s\"];\n" i shape
513 (Branch.to_string b);
514 ) heads;
515
516 output_string oc "}\n";
517 close_out oc;
518 ignore(Sys.command
519 ("dot -Tpdf -Gcharset=latin1 " ^ fname_dot ^ " -o" ^ fname_ps))
520
521 let vcs : vcs ref = ref (empty Stateid.dummy)
522
523 let doc_type = ref (Interactive (Coqargs.TopLogical ""))
524 let ldir = ref Names.DirPath.empty
525
526 let init dt id ps =
527 doc_type := dt;
528 vcs := empty id;
529 let info = { (default_info None) with state = ParsingState ps } in
530 vcs := set_info !vcs id info;
531 dummy_doc
532
533 let set_ldir ld =
534 ldir := ld
535
536 let get_ldir () = !ldir
537 (* let get_type () = !doc_type *)
538
539 let is_interactive () =
540 match !doc_type with
541 | Interactive _ -> true
542 | _ -> false
543
544 let is_vos_doc () =
545 match !doc_type with
546 | VosDoc _ -> true
547 | _ -> false
548
549 let current_branch () = current_branch !vcs
550
551 let checkout head = vcs := checkout !vcs head
552 let branches () = branches !vcs
553 let get_branch head = get_branch !vcs head
554 let get_branch_pos head = (get_branch head).pos
555 let new_node ?(id=Stateid.fresh ()) proof_mode () =
556 assert(Vcs_.get_info !vcs id = None);
557 vcs := set_info !vcs id (default_info proof_mode);
558 id
559 let merge id ~ours ?into branch =
560 vcs := merge !vcs id ~ours ~theirs:Noop ?into branch
561 let delete_branch branch = vcs := delete_branch !vcs branch
562 let reset_branch branch id = vcs := reset_branch !vcs branch id
563 let commit id t = vcs := commit !vcs id t
564 let rewrite_merge id ~ours ~at branch =
565 vcs := rewrite_merge !vcs id ~ours ~theirs:Noop ~at branch
566 let reachable id = reachable !vcs id
567 let mk_branch_name { expr = x } = Branch.make
568 (match x.CAst.v.Vernacexpr.expr with
569 | VernacSynPure (VernacDefinition (_,({CAst.v=Name i},_),_)) -> Id.to_string i
570 | VernacSynPure (VernacStartTheoremProof (_,[({CAst.v=i},_),_])) -> Id.to_string i
571 | VernacSynPure (VernacInstance (({CAst.v=Name i},_),_,_,_,_)) -> Id.to_string i
572 | _ -> "branch")
573 let edit_branch = Branch.make "edit"
574 let branch ?root ?pos name kind = vcs := branch !vcs ?root ?pos name kind
575 let get_info id =
576 match get_info !vcs id with
577 | Some x -> x
578 | None -> raise Vcs_aux.Expired
579 let set_state id s =
580 let info = get_info id in
581 info.state <- s;
582 let is_full_state_valid = match s with
583 | FullState _ -> true
584 | EmptyState | ErrorState _ | ParsingState _ -> false
585 in
586 if async_proofs_is_master (cur_opt()) && is_full_state_valid then
587 !Hooks.state_ready ~doc:dummy_doc (* XXX should be taken in input *) id
588
589 let get_state id = (get_info id).state
590
591 let get_parsing_state id =
592 stm_pperr_endline (fun () -> str "retrieve parsing state state " ++ str (Stateid.to_string id) ++ str " }}}");
593 match (get_info id).state with
594 | FullState s -> Some Vernacstate.(Synterp.parsing s.synterp)
595 | ParsingState s -> Some s
596 | ErrorState (s,_) -> s
597 | EmptyState -> None
598
599 let set_parsing_state id ps =
600 let info = get_info id in
601 let new_state =
602 match info.state with
603 | FullState s -> assert false
604 | ParsingState s -> assert false
605 | ErrorState _ -> assert false
606 | EmptyState -> ParsingState ps
607 in
608 info.state <- new_state
609
610 let get_proof_mode id = (get_info id).proof_mode
611
612 let reached id =
613 let info = get_info id in
614 info.n_reached <- info.n_reached + 1
615 let goals id n = (get_info id).n_goals <- n
616 let cur_tip () = get_branch_pos (current_branch ())
617
618 let proof_nesting () = Vcs_aux.proof_nesting !vcs
619
620 let checkout_shallowest_proof_branch () =
621 if List.mem edit_branch (Vcs_.branches !vcs) then begin
622 checkout edit_branch
623 end else
624 let pl = proof_nesting () in
625 try
626 let branch = fst @@ Vcs_aux.find_proof_at_depth !vcs pl in
627 checkout branch
628 with Failure _ ->
629 checkout Branch.master
630
631 (* copies the transaction on every open branch *)
632 let propagate_sideff ~action =
633 List.map (fun b ->
634 checkout b;
635 let proof_mode = get_proof_mode @@ get_branch_pos b in
636 let id = new_node proof_mode () in
637 merge id ~ours:(Sideff action) ~into:b Branch.master;
638 id)
639 (List.filter (fun b -> not (Branch.equal b Branch.master)) (branches ()))
640
641 let propagate_qed () =
642 List.iter (fun b ->
643 checkout b;
644 let proof_mode = get_proof_mode @@ get_branch_pos b in
645 let id = new_node proof_mode () in
646 let parsing = Option.get @@ get_parsing_state (get_branch_pos b) in
647 merge id ~ours:(Sideff CherryPickEnv) ~into:b Branch.master;
648 set_parsing_state id parsing)
649 (List.filter (fun b -> not (Branch.equal b Branch.master)) (branches ()))
650
651 let visit id = Vcs_aux.visit !vcs id
652
653 let nodes_in_slice ~block_start ~block_stop =
654 let rec aux id =
655 if Stateid.equal id block_start then [] else
656 match visit id with
657 | { next = n; step = SCmd x } -> (id,Cmd x) :: aux n
658 | { next = n; step = SAlias x } -> (id,Alias x) :: aux n
659 | { next = n; step = SSideff (ReplayCommand x,_) } ->
660 (id,Sideff (ReplayCommand x)) :: aux n
661 | _ -> anomaly Pp.(str("Cannot slice from "^ Stateid.to_string block_start ^
662 " to "^Stateid.to_string block_stop^"."))
663 in aux block_stop
664
665 (* [slice] copies a slice of the DAG, keeping only the last known valid state.
666 When it copies a state, it drops the libobjects and keeps only the structure. *)
667 let slice ~block_start ~block_stop =
668 let l = nodes_in_slice ~block_start ~block_stop in
669 let copy_info v id =
670 let info = get_info id in
671 Vcs_.set_info v id
672 { info with state = EmptyState;
673 vcs_backup = None,None } in
674 let make_shallow = function
675 | FullState st -> FullState (Vernacstate.Stm.make_shallow st)
676 | x -> x
677 in
678 let copy_info_w_state v id =
679 let info = get_info id in
680 Vcs_.set_info v id { info with state = make_shallow info.state; vcs_backup = None,None } in
681 let copy_proof_blockes v =
682 let nodes = Vcs_.Dag.all_nodes (Vcs_.dag v) in
683 let props =
684 Stateid.Set.fold (fun n pl -> Vcs_.property_of !vcs n @ pl) nodes [] in
685 let props = CList.sort_uniquize Vcs_.Dag.Property.compare props in
686 List.fold_left (fun v p ->
687 Vcs_.create_property v
688 (Stateid.Set.elements (Vcs_.Dag.Property.having_it p))
689 (Vcs_.Dag.Property.data p)) v props
690 in
691 let v = Vcs_.empty block_start in
692 let v = copy_info v block_start in
693 let v = List.fold_right (fun (id,tr) v ->
694 let v = Vcs_.commit v id tr in
695 let v = copy_info v id in
696 v) l v in
697 (* Stm should have reached the beginning of proof *)
698 assert (match get_state block_start
699 with FullState _ -> true | _ -> false);
700 (* We put in the new dag the most recent state known to master *)
701 let rec fill id =
702 match get_state id with
703 | EmptyState | ErrorState _ | ParsingState _ -> fill (Vcs_aux.visit v id).next
704 | FullState _ -> copy_info_w_state v id
705 in
706 let v = fill block_stop in
707 (* We put in the new dag the first state (since Qed shall run on it,
708 * see check_task_aux) *)
709 let v = copy_info_w_state v block_start in
710 copy_proof_blockes v
711
712 let nodes_in_slice ~block_start ~block_stop =
713 List.rev (List.map fst (nodes_in_slice ~block_start ~block_stop))
714
715 let topo_invariant l =
716 let all = List.fold_right Stateid.Set.add l Stateid.Set.empty in
717 List.for_all
718 (fun x ->
719 let props = property_of !vcs x in
720 let sets = List.map Dag.Property.having_it props in
721 List.for_all (fun s -> Stateid.Set.(subset s all || subset all s)) sets)
722 l
723
724 let create_proof_task_box l ~qed ~block_start:lemma =
725 if not (topo_invariant l) then anomaly Pp.(str "overlapping boxes.");
726 vcs := create_property !vcs l (ProofTask { qed; lemma })
727 let create_proof_block ({ block_start; block_stop} as decl) name =
728 let l = nodes_in_slice ~block_start ~block_stop in
729 if not (topo_invariant l) then anomaly Pp.(str "overlapping boxes.");
730 vcs := create_property !vcs l (ProofBlock (decl, name))
731 let box_of id = List.map Dag.Property.data (property_of !vcs id)
732 let delete_boxes_of id =
733 List.iter (fun x -> vcs := delete_property !vcs x) (property_of !vcs id)
734 let proof_task_box_of id =
735 match
736 CList.map_filter (function ProofTask x -> Some x | _ -> None) (box_of id)
737 with
738 | [] -> None
739 | [x] -> Some x
740 | _ -> anomaly Pp.(str "node with more than 1 proof task box.")
741
742 let gc () =
743 let old_vcs = !vcs in
744 let new_vcs, erased_nodes = gc old_vcs in
745 Stateid.Set.iter (fun id ->
746 match (Vcs_aux.visit old_vcs id).step with
747 | SQed ({ fproof = Some (_, cancel_switch) }, _)
748 | SCmd { cancel_switch } ->
749 cancel_switch := true
750 | _ -> ())
751 erased_nodes;
752 vcs := new_vcs
753
754 module NB : sig (* Non blocking Sys.command *)
755
756 val command : now:bool -> (unit -> unit) -> unit
757
758 end = struct
759
760 let m = Mutex.create ()
761 let c = Condition.create ()
762 let job = ref None
763 let worker = ref None
764
765 let set_last_job j =
766 CThread.with_lock m ~scope:(fun () ->
767 job := Some j;
768 Condition.signal c)
769
770 let get_last_job () =
771 CThread.with_lock m ~scope:(fun () ->
772 while Option.is_empty !job do Condition.wait c m; done;
773 match !job with
774 | None -> assert false
775 | Some x -> job := None; x)
776
777 let run_command () =
778 try while true do get_last_job () () done
779 with e -> () (* No failure *)
780
781 let command ~now job =
782 if now then job ()
783 else begin
784 set_last_job job;
785 if Option.is_empty !worker then
786 worker := Some (CThread.create run_command ())
787 end
788
789 end
790
791 let print ?(now=false) () =
792 if CDebug.(get_flag misc) then NB.command ~now (print_dag !vcs)
793
794 let backup () = !vcs
795 let restore v = vcs := v
796
797 end (* }}} *)
798
799 type state = Valid of Vernacstate.t option | Expired | Error of exn
800
801 let state_of_id ~doc id =
802 try match VCS.get_state id with
803 | FullState s -> Valid (Some s)
804 | ErrorState (_,(e,_)) -> Error e
805 | EmptyState | ParsingState _ -> Valid None
806 with VCS.Expired -> Expired
807
808 let () =
809 Stateid.set_is_valid (fun ~doc id -> state_of_id ~doc id <> Expired)
810
811 (****** A cache: fills in the nodes of the VCS document with their value ******)
812 module State : sig
813
814 type t
815
816 val freeze : unit -> t
817 val unfreeze : t -> unit
818
819 (** The function is from unit, so it uses the current state to define
820 a new one. I.e. one may been to install the right state before
821 defining a new one.
822 Warning: an optimization in installed_cached requires that state
823 modifying functions are always executed using this wrapper. *)
824 val define :
825 doc:doc ->
826 ?safe_id:Stateid.t ->
827 ?redefine:bool -> ?cache:bool ->
828 ?feedback_processed:bool -> (unit -> unit) -> Stateid.t -> unit
829
830 val install_cached : Stateid.t -> unit
831 (* val install_parsing_state : Stateid.t -> unit *)
832 val is_cached : ?cache:bool -> Stateid.t -> bool
833 val is_cached_and_valid : ?cache:bool -> Stateid.t -> bool
834
835 val exn_on : Stateid.t -> valid:Stateid.t -> Exninfo.iexn -> Exninfo.iexn
836
837 (* to send states across worker/master *)
838 val get_cached : Stateid.t -> Vernacstate.t
839
840 type partial_state =
841 | Full of Vernacstate.t
842 | ProofOnly of Stateid.t * Vernacstate.Stm.pstate
843
844 val assign : Stateid.t -> partial_state -> unit
845
846 (* Handlers for initial state, prior to document creation. *)
847 val register_root_state : unit -> unit
848 val restore_root_state : unit -> unit
849
850 val purify : ('a -> 'b) -> 'a -> 'b
851
852 end = struct (* {{{ *)
853
854 type t = { id : Stateid.t; vernac_state : Vernacstate.t }
855
856 (* cur_id holds Stateid.dummy in case the last attempt to define a state
857 * failed, so the global state may contain garbage *)
858 let cur_id = ref Stateid.dummy
859 let freeze () = { id = !cur_id; vernac_state = Vernacstate.freeze_full_state () }
860 let unfreeze st =
861 Vernacstate.unfreeze_full_state st.vernac_state;
862 cur_id := st.id
863
864 let invalidate_cur_state () = cur_id := Stateid.dummy
865
866 type partial_state =
867 | Full of Vernacstate.t
868 | ProofOnly of Stateid.t * Vernacstate.Stm.pstate
869
870 let cache_state id =
871 VCS.set_state id (FullState (Vernacstate.freeze_full_state ()))
872
873 let freeze_invalid id iexn =
874 let ps = VCS.get_parsing_state id in
875 VCS.set_state id (ErrorState (ps,iexn))
876
877 let is_cached ?(cache=false) id only_valid =
878 if Stateid.equal id !cur_id then
879 try match VCS.get_info id with
880 | ({ state = EmptyState } | { state = ParsingState _ }) when cache -> cache_state id; true
881 | _ -> true
882 with VCS.Expired -> false
883 else
884 try match VCS.get_state id with
885 | EmptyState | ParsingState _ -> false
886 | FullState _ -> true
887 | ErrorState _ -> not only_valid
888 with VCS.Expired -> false
889
890 let is_cached_and_valid ?cache id = is_cached ?cache id true
891 let is_cached ?cache id = is_cached ?cache id false
892
893 let install_cached id =
894 match VCS.get_state id with
895 | FullState s ->
896 Vernacstate.unfreeze_full_state s;
897 cur_id := id
898
899 | ErrorState (_,ie) ->
900 Exninfo.iraise ie
901
902 | EmptyState | ParsingState _ ->
903 (* rocq compile has a 1 slot cache and only for valid states *)
904 if (VCS.is_interactive ()) || not (Stateid.equal id !cur_id) then
905 anomaly Pp.(str "installing a non cached state.")
906
907 (*
908 let install_parsing_state id =
909 if not (Stateid.equal id !cur_id) then begin
910 Vernacstate.Parser.install @@ VCS.get_parsing_state id
911 end
912 *)
913
914 let get_cached id =
915 try match VCS.get_state id with
916 | FullState s -> s
917 | _ -> anomaly Pp.(str "not a cached state.")
918 with VCS.Expired -> anomaly Pp.(str "not a cached state (expired).")
919
920 let assign id what =
921 if VCS.get_state id <> EmptyState then () else
922 try match what with
923 | Full s ->
924 let s =
925 try
926 let prev = (VCS.visit id).next in
927 if is_cached_and_valid prev
928 then
929 let open Vernacstate in
930 { s with interp = { s.interp with
931 lemmas = PG_compat.copy_terminators
932 ~src:((get_cached prev).interp.lemmas) ~tgt:s.interp.lemmas }}
933 else s
934 with VCS.Expired -> s in
935 VCS.set_state id (FullState s)
936 | ProofOnly(ontop,pstate) ->
937 if is_cached_and_valid ontop then
938 let s = get_cached ontop in
939 let s = Vernacstate.Stm.set_pstate s pstate in
940 VCS.set_state id (FullState s)
941 with VCS.Expired -> ()
942
943 let exn_on id ~valid (e, info) =
944 match Stateid.get info with
945 | Some _ -> (e, info)
946 | None ->
947 let loc = Loc.get_loc info in
948 execution_error ?loc id (iprint (e, info));
949 (e, Stateid.add info ~valid id)
950
951 (* [define] puts the system in state [id] calling [f ()] *)
952 (* [safe_id] is the last known valid state before execution *)
953 let define ~doc ?safe_id ?(redefine=false) ?(cache=false) ?(feedback_processed=true)
954 f id
955 =
956 feedback ~id:id (ProcessingIn !Flags.async_proofs_worker_id);
957 let str_id = Stateid.to_string id in
958 if is_cached id && not redefine then
959 anomaly Pp.(str"defining state "++str str_id++str" twice.");
960 try
961 stm_prerr_endline (fun () -> "defining "^str_id^" (cache="^
962 if cache then "Y)" else "N)");
963 f ();
964 if cache then cache_state id;
965 stm_prerr_endline (fun () -> "setting cur id to "^str_id);
966 cur_id := id;
967 if feedback_processed then
968 !Hooks.state_computed~doc id ~in_cache:false;
969 VCS.reached id;
970 if PG_compat.there_are_pending_proofs () then
971 VCS.goals id (PG_compat.get_open_goals ())
972 with e ->
973 let (e, info) = Exninfo.capture e in
974 let good_id = !cur_id in
975 invalidate_cur_state ();
976 VCS.reached id;
977 let ie =
978 match Stateid.get info, safe_id with
979 | None, None -> (exn_on id ~valid:good_id (e, info))
980 | None, Some good_id -> (exn_on id ~valid:good_id (e, info))
981 | Some _, None -> (e, info)
982 | Some (_,at), Some id -> (e, Stateid.add info ~valid:id at) in
983 if cache then freeze_invalid id ie;
984 !Hooks.unreachable_state ~doc id ie;
985 Exninfo.iraise ie
986
987 let init_state = ref None
988
989 let register_root_state () =
990 init_state := Some (Vernacstate.freeze_full_state ())
991
992 let restore_root_state () =
993 cur_id := Stateid.dummy;
994 Vernacstate.unfreeze_full_state (Option.get !init_state)
995
996 (* Protect against state changes *)
997 let purify f x =
998 let st = freeze () in
999 try
1000 let res = f x in
1001 Vernacstate.Interp.invalidate_cache ();
1002 unfreeze st;
1003 res
1004 with e ->
1005 let e = Exninfo.capture e in
1006 Vernacstate.Interp.invalidate_cache ();
1007 unfreeze st;
1008 Exninfo.iraise e
1009
1010 end (* }}} *)
1011
1012 (* Wrapper for the proof-closing special path for Qed *)
1013 let stm_qed_delay_proof ?route ~proof ~id ~st ~loc ~control pending : Vernacstate.Interp.t =
1014 set_id_for_feedback ?route dummy_doc id;
1015 Vernacinterp.interp_qed_delayed_proof ~proof ~st ~control (CAst.make ?loc pending)
1016
1017 (* Wrapper for Vernacentries.interp to set the feedback id *)
1018 (* It is currently called 19 times, this number should be certainly
1019 reduced... *)
1020 let stm_vernac_interp ?route id st { verbose; expr } : Vernacstate.t =
1021 (* The Stm will gain the capability to interpret commmads affecting
1022 the whole document state, such as backtrack, etc... so we start
1023 to design the stm command interpreter now *)
1024 set_id_for_feedback ?route dummy_doc id;
1025 Aux_file.record_in_aux_set_at ?loc:expr.CAst.loc ();
1026 (* We need to check if a command should be filtered from
1027 * vernac_entries, as it cannot handle it. This should go away in
1028 * future refactorings.
1029 *)
1030 let is_filtered_command = function
1031 VernacSynPure (VernacResetName _ | VernacResetInitial | VernacBack _
1032 | VernacRestart | VernacUndo _ | VernacUndoTo _
1033 | VernacAbortAll) -> true
1034 | _ -> false
1035 in
1036 (* XXX unsupported attributes *)
1037 let cmd = expr.CAst.v.expr in
1038 if is_filtered_command cmd then
1039 (stm_pperr_endline Pp.(fun () -> str "ignoring " ++ Ppvernac.pr_vernac expr); st)
1040 else begin
1041 stm_pperr_endline Pp.(fun () -> str "interpreting " ++ Ppvernac.pr_vernac expr);
1042 Vernacinterp.(interp ~intern:fs_intern ?verbosely:(Some verbose) ~st expr)
1043 end
1044
1045 (****************************** CRUFT *****************************************)
1046 (******************************************************************************)
1047
1048 (* The backtrack module simulates the classic behavior of a linear document *)
1049 module Backtrack : sig
1050
1051 val record : unit -> unit
1052
1053 (* we could navigate the dag, but this ways easy *)
1054 val branches_of : Stateid.t -> backup
1055
1056 (* Returns the state that the command should backtract to *)
1057 val undo_vernac_classifier : vernac_control -> doc:doc -> Stateid.t
1058 val get_prev_proof : doc:doc -> Stateid.t -> Proof.t option
1059 val get_proof : doc:doc -> Stateid.t -> Proof.t option
1060
1061 end = struct (* {{{ *)
1062
1063 let record () =
1064 List.iter (fun current_branch ->
1065 let mine = current_branch, VCS.get_branch current_branch in
1066 let info = VCS.get_info (VCS.get_branch_pos current_branch) in
1067 let others =
1068 CList.map_filter (fun b ->
1069 if Vcs_.Branch.equal b current_branch then None
1070 else Some(b, VCS.get_branch b)) (VCS.branches ()) in
1071 let backup = if fst info.vcs_backup <> None then fst info.vcs_backup
1072 else Some (VCS.backup ()) in
1073 let branches = if snd info.vcs_backup <> None then snd info.vcs_backup
1074 else Some { mine; others } in
1075 info.vcs_backup <- backup, branches)
1076 [VCS.current_branch (); VCS.Branch.master]
1077
1078 let branches_of id =
1079 let info = VCS.get_info id in
1080 match info.vcs_backup with
1081 | _, None ->
1082 anomaly Pp.(str"Backtrack.branches_of "++str(Stateid.to_string id)++
1083 str": a state with no vcs_backup.")
1084 | _, Some x -> x
1085
1086 type ('a, 'b) cont = Stop of 'a | Cont of 'b
1087
1088 let rec fold_until f acc id =
1089 let next acc =
1090 if id = Stateid.initial then raise Not_found
1091 else fold_until f acc (VCS.visit id).next in
1092 let info = VCS.get_info id in
1093 match info.vcs_backup with
1094 | None, _ -> next acc
1095 | Some vcs, _ ->
1096 let ids, tactic, undo =
1097 if id = Stateid.initial || id = Stateid.dummy then [],false,0 else
1098 match VCS.visit id with
1099 | { step = SFork ((_,_,_,l),_) } -> l, false,0
1100 | { step = SCmd { cids = l; ctac } } -> l, ctac,0
1101 | { step = SAlias (_,{ expr }) } when not (Vernacprop.has_query_control expr) ->
1102 begin match expr.CAst.v.expr with
1103 | VernacSynPure (VernacUndo n) -> [], false, n
1104 | _ -> [],false,0
1105 end
1106 | _ -> [],false,0 in
1107 match f acc (id, vcs, ids, tactic, undo) with
1108 | Stop x -> x
1109 | Cont acc -> next acc
1110
1111 let undo_costly_in_batch_mode =
1112 CWarnings.create ~name:"undo-batch-mode" Pp.(fun v ->
1113 str "Command" ++ spc() ++ quote (Ppvernac.pr_vernac v) ++
1114 strbrk (" is not recommended in batch mode. In particular, going back in the document" ^
1115 " is not efficient in batch mode due to Rocq not caching previous states for memory optimization reasons." ^
1116 " If your use is intentional, you may want to disable this warning and pass" ^
1117 " the \"-async-proofs-cache force\" option to Rocq."))
1118
1119 let back_tactic n (id,_,_,tactic,undo) =
1120 let value = (if tactic then 1 else 0) - undo in
1121 if Int.equal n 0 then Stop id else Cont (n-value)
1122
1123 let get_proof ~doc id =
1124 match state_of_id ~doc id with
1125 | Valid (Some vstate) ->
1126 Option.map (Vernacstate.LemmaStack.with_top ~f:Declare.Proof.get) vstate.Vernacstate.interp.lemmas
1127 | _ -> None
1128
1129 let undo_vernac_classifier v ~doc =
1130 if not (VCS.is_interactive ()) && (cur_opt()).async_proofs_cache <> Some Force
1131 then undo_costly_in_batch_mode v;
1132 try
1133 match v.CAst.v.expr with
1134 | VernacSynPure VernacResetInitial ->
1135 Stateid.initial
1136 | VernacSynPure (VernacResetName {CAst.v=name}) ->
1137 let id = VCS.cur_tip () in
1138 (try
1139 let oid =
1140 fold_until (fun b (id,_,label,_,_) ->
1141 if b then Stop id else Cont (List.mem name label))
1142 false id in
1143 oid
1144 with Not_found ->
1145 id)
1146 | VernacSynPure (VernacBack n) ->
1147 let id = VCS.cur_tip () in
1148 let oid = fold_until (fun n (id,_,_,_,_) ->
1149 if Int.equal n 0 then Stop id else Cont (n-1)) n id in
1150 oid
1151 | VernacSynPure (VernacUndo n) ->
1152 let id = VCS.cur_tip () in
1153 let oid = fold_until back_tactic n id in
1154 oid
1155 | VernacSynPure (VernacUndoTo _
1156 | VernacRestart as e) ->
1157 let m = match e with VernacUndoTo m -> m | _ -> 0 in
1158 let id = VCS.cur_tip () in
1159 let vcs =
1160 match (VCS.get_info id).vcs_backup with
1161 | None, _ -> anomaly Pp.(str"Backtrack: tip with no vcs_backup.")
1162 | Some vcs, _ -> vcs in
1163 let cb, _ =
1164 try Vcs_aux.find_proof_at_depth vcs (Vcs_aux.proof_nesting vcs)
1165 with Failure _ -> raise PG_compat.NoCurrentProof in
1166 let n = fold_until (fun n (_,vcs,_,_,_) ->
1167 if List.mem cb (Vcs_.branches vcs) then Cont (n+1) else Stop n)
1168 0 id in
1169 let oid = fold_until (fun n (id,_,_,_,_) ->
1170 if Int.equal n 0 then Stop id else Cont (n-1)) (n-m-1) id in
1171 oid
1172 | VernacSynPure VernacAbortAll ->
1173 let id = VCS.cur_tip () in
1174 let oid = fold_until (fun () (id,vcs,_,_,_) ->
1175 match Vcs_.branches vcs with [_] -> Stop id | _ -> Cont ())
1176 () id in
1177 oid
1178 | _ -> anomaly Pp.(str "incorrect VtMeta classification")
1179 with
1180 | Not_found ->
1181 CErrors.user_err
1182 Pp.(str "Cannot undo.")
1183
1184 let get_prev_proof ~doc id =
1185 try
1186 let np = get_proof ~doc id in
1187 match np with
1188 | None -> None
1189 | Some cp ->
1190 let rec search did =
1191 let did = fold_until back_tactic 1 did in
1192 match get_proof ~doc did with
1193 | None -> None
1194 | Some rv ->
1195 if Evar.Set.equal (Proof.all_goals rv) (Proof.all_goals cp)
1196 then search did
1197 else Some rv
1198 in
1199 search id
1200 with Not_found | PG_compat.NoCurrentProof -> None
1201
1202 end (* }}} *)
1203
1204 let get_prev_proof = Backtrack.get_prev_proof
1205 let get_proof = Backtrack.get_proof
1206
1207 let hints = ref Aux_file.empty_aux_file
1208 let set_compilation_hints file =
1209 hints := Aux_file.load_aux_file_for file
1210
1211 let get_hint_ctx loc =
1212 let s = Aux_file.get ?loc !hints "context_used" in
1213 let ids = List.map Names.Id.of_string (Str.split (Str.regexp " ") s) in
1214 let ids = List.map (fun id -> CAst.make id) ids in
1215 match ids with
1216 | [] -> SsEmpty
1217 | x :: xs ->
1218 List.fold_left (fun a x -> SsUnion (SsSingl x,a)) (SsSingl x) xs
1219
1220 let get_hint_bp_time proof_name =
1221 try float_of_string (Aux_file.get !hints proof_name)
1222 with Not_found -> 1.0
1223
1224 let record_pb_time ?loc proof_name time =
1225 let proof_build_time = Printf.sprintf "%.3f" time in
1226 Aux_file.record_in_aux_at ?loc "proof_build_time" proof_build_time;
1227 if proof_name <> "" then begin
1228 Aux_file.record_in_aux_at proof_name proof_build_time;
1229 hints := Aux_file.set !hints proof_name proof_build_time
1230 end
1231
1232 (****************** proof structure for error recovery ************************)
1233 (******************************************************************************)
1234
1235 type document_node = {
1236 indentation : int;
1237 ast : Vernacexpr.vernac_control;
1238 id : Stateid.t;
1239 }
1240
1241 type document_view = {
1242 entry_point : document_node;
1243 prev_node : document_node -> document_node option;
1244 }
1245
1246 type static_block_detection =
1247 document_view -> static_block_declaration option
1248
1249 type recovery_action = {
1250 base_state : Stateid.t;
1251 goals_to_admit : Evar.t list;
1252 recovery_command : Vernacexpr.vernac_control option;
1253 }
1254
1255 type block_classification = ValidBlock of recovery_action | Leaks
1256
1257 type dynamic_block_error_recovery =
1258 doc -> static_block_declaration -> block_classification
1259
1260 let proof_block_delimiters = ref []
1261
1262 let register_proof_block_delimiter name static dynamic =
1263 if List.mem_assoc name !proof_block_delimiters then
1264 CErrors.user_err Pp.(str "Duplicate block delimiter " ++ str name ++ str ".");
1265 proof_block_delimiters := (name, (static,dynamic)) :: !proof_block_delimiters
1266
1267 let mk_doc_node id = function
1268 | { step = SCmd { ctac; cast = { indentation; expr }}; next } when ctac ->
1269 Some { indentation; ast = expr; id }
1270 | { step = SSideff (ReplayCommand { indentation; expr }, _); next } ->
1271 Some { indentation; ast = expr; id }
1272 | _ -> None
1273 let prev_node { id } =
1274 let id = (VCS.visit id).next in
1275 mk_doc_node id (VCS.visit id)
1276 let cur_node id = mk_doc_node id (VCS.visit id)
1277
1278 let is_block_name_enabled name =
1279 match (cur_opt()).async_proofs_tac_error_resilience with
1280 | FNone -> false
1281 | FAll -> true
1282 | FOnly l -> List.mem name l
1283
1284 let detect_proof_block id name =
1285 let name = match name with None -> "indent" | Some x -> x in
1286 if is_block_name_enabled name &&
1287 (async_proofs_is_master (cur_opt()) || Flags.async_proofs_is_worker ())
1288 then (
1289 match cur_node id with
1290 | None -> ()
1291 | Some entry_point -> try
1292 let static, _ = List.assoc name !proof_block_delimiters in
1293 begin match static { prev_node; entry_point } with
1294 | None -> ()
1295 | Some ({ block_start; block_stop } as decl) ->
1296 VCS.create_proof_block decl name
1297 end
1298 with Not_found ->
1299 CErrors.user_err
1300 Pp.(str "Unknown proof block delimiter " ++ str name ++ str ".")
1301 )
1302 (****************************** THE SCHEDULER *********************************)
1303 (******************************************************************************)
1304
1305 (* Unused module warning doesn't understand [module rec] *)
1306 [@@@ocaml.warning "-60"]
1307 module rec ProofTask : sig
1308
1309 type competence = Stateid.t list
1310 type task_build_proof = {
1311 t_exn_info : Stateid.exn_info;
1312 t_start : Stateid.t;
1313 t_stop : Stateid.t;
1314 t_drop : bool;
1315 t_states : competence;
1316 t_assign : Declare.Proof.closed_proof_output option Future.assignment -> unit;
1317 t_loc : Loc.t option;
1318 t_uuid : Future.UUID.t;
1319 t_name : string }
1320
1321 type task =
1322 | BuildProof of task_build_proof
1323 | States of Stateid.t list
1324
1325 type request =
1326 | ReqBuildProof of (Future.UUID.t,VCS.vcs) Stateid.request * bool * competence
1327 | ReqStates of Stateid.t list
1328
1329 include AsyncTaskQueue.Task
1330 with type task := task
1331 and type competence := competence
1332 and type request := request
1333
1334 val build_proof_here :
1335 doc:doc ->
1336 ?loc:Loc.t ->
1337 drop_pt:bool ->
1338 Stateid.exn_info -> Stateid.t ->
1339 Declare.Proof.closed_proof_output option Future.computation
1340
1341 end = struct (* {{{ *)
1342
1343 let forward_feedback msg = !Hooks.forward_feedback msg
1344
1345 type competence = Stateid.t list
1346 type task_build_proof = {
1347 t_exn_info : Stateid.exn_info;
1348 t_start : Stateid.t;
1349 t_stop : Stateid.t;
1350 t_drop : bool;
1351 t_states : competence;
1352 t_assign : Declare.Proof.closed_proof_output option Future.assignment -> unit;
1353 t_loc : Loc.t option;
1354 t_uuid : Future.UUID.t;
1355 t_name : string }
1356
1357 type task =
1358 | BuildProof of task_build_proof
1359 | States of Stateid.t list
1360
1361 type worker_status = Fresh | Old of competence
1362
1363 type request =
1364 | ReqBuildProof of (Future.UUID.t,VCS.vcs) Stateid.request * bool * competence
1365 | ReqStates of Stateid.t list
1366
1367 type error = {
1368 e_error_at : Stateid.t;
1369 e_safe_id : Stateid.t;
1370 e_msg : Pp.t;
1371 e_loc : Loc.t option;
1372 e_safe_states : Stateid.t list }
1373
1374 type response =
1375 | RespBuiltProof of Declare.Proof.closed_proof_output option * float
1376 | RespError of error
1377 | RespStates of (Stateid.t * State.partial_state) list
1378
1379 let name = "proof"
1380 let extra_env () = !async_proofs_workers_extra_env
1381
1382 let task_match age t =
1383 match age, t with
1384 | Fresh, BuildProof { t_states } -> true
1385 | Old my_states, States l ->
1386 List.for_all (fun x -> CList.mem_f Stateid.equal x my_states) l
1387 | _ -> false
1388
1389 let name_of_task = function
1390 | BuildProof t -> "proof: " ^ t.t_name
1391 | States l -> "states: " ^ String.concat "," (List.map Stateid.to_string l)
1392 let name_of_request = function
1393 | ReqBuildProof(r,_,_) -> "proof: " ^ r.Stateid.name
1394 | ReqStates l -> "states: "^String.concat "," (List.map Stateid.to_string l)
1395
1396 let request_of_task age = function
1397 | States l -> Some (ReqStates l)
1398 | BuildProof {
1399 t_exn_info;t_start;t_stop;t_loc;t_uuid;t_name;t_states;t_drop
1400 } ->
1401 assert(age = Fresh);
1402 try Some (ReqBuildProof ({
1403 Stateid.exn_info = t_exn_info;
1404 stop = t_stop;
1405 document = VCS.slice ~block_start:t_start ~block_stop:t_stop;
1406 loc = t_loc;
1407 uuid = t_uuid;
1408 name = t_name }, t_drop, t_states))
1409 with VCS.Expired -> None
1410
1411 let use_response (s : worker_status) t r =
1412 match s, t, r with
1413 | Old c, States _, RespStates l ->
1414 List.iter (fun (id,s) -> State.assign id s) l; `End
1415 | Fresh, BuildProof { t_assign; t_loc; t_name; t_states; t_drop },
1416 RespBuiltProof (pl, time) ->
1417 feedback (InProgress ~-1);
1418 t_assign (`Val pl);
1419 record_pb_time ?loc:t_loc t_name time;
1420 if t_drop then `Stay(t_states,[States t_states])
1421 else `End
1422 | Fresh, BuildProof { t_assign; t_loc; t_name; t_states },
1423 RespError { e_error_at; e_safe_id = valid; e_loc; e_msg; e_safe_states } ->
1424 feedback (InProgress ~-1);
1425 let info = match e_loc with
1426 | Some loc -> Loc.add_loc Exninfo.null loc
1427 | None -> Exninfo.null
1428 in
1429 let info = Stateid.add ~valid info e_error_at in
1430 let e = (AsyncTaskQueue.RemoteException e_msg, info) in
1431 t_assign (`Exn e);
1432 `Stay(t_states,[States e_safe_states])
1433 | _ -> assert false
1434
1435 let on_task_cancellation_or_expiration_or_slave_death = function
1436 | None -> ()
1437 | Some (States _) -> ()
1438 | Some (BuildProof { t_start = start; t_assign }) ->
1439 let s = "Worker dies or task expired" in
1440 let info = Stateid.add ~valid:start Exninfo.null start in
1441 let e = (AsyncTaskQueue.RemoteException (Pp.strbrk s), info) in
1442 t_assign (`Exn e);
1443 execution_error start (Pp.strbrk s);
1444 feedback (InProgress ~-1)
1445
1446 let build_proof_here_fun ~doc ?loc ~drop_pt ~id eop =
1447 let wall_clock1 = Unix.gettimeofday () in
1448 Reach.known_state ~doc ~cache:(VCS.is_interactive ()) eop;
1449 let wall_clock2 = Unix.gettimeofday () in
1450 Aux_file.record_in_aux_at ?loc "proof_build_time"
1451 (Printf.sprintf "%.3f" (wall_clock2 -. wall_clock1));
1452 let p = if drop_pt then None else Some (PG_compat.return_proof ()) in
1453 if drop_pt then feedback ~id Complete;
1454 p
1455
1456 let build_proof_here ~doc ?loc ~drop_pt exn_info eop =
1457 Future.create ~fix_exn:(Some exn_info) (fun () -> build_proof_here_fun ~doc ?loc ~drop_pt ~id:exn_info.Stateid.id eop)
1458
1459 let perform_buildp { Stateid.exn_info; stop; document; loc } drop my_states =
1460 try
1461 VCS.restore document;
1462 VCS.print ();
1463 let proof, time =
1464 let wall_clock = Unix.gettimeofday () in
1465 let proof =
1466 try
1467 build_proof_here_fun ~doc:dummy_doc (* XXX should be document *)
1468 ?loc ~drop_pt:drop ~id:exn_info.Stateid.id stop
1469 with exn ->
1470 let iexn = Exninfo.capture exn in
1471 let iexn = State.exn_on exn_info.Stateid.id ~valid:exn_info.Stateid.valid iexn in
1472 Exninfo.iraise iexn
1473 in
1474 proof, Unix.gettimeofday () -. wall_clock in
1475 (* We typecheck the proof with the kernel (in the worker) to spot
1476 * the few errors tactics don't catch, like the "fix" tactic building
1477 * a bad fixpoint *)
1478 (* STATE: We use the current installed imperative state *)
1479 let st = State.freeze () in
1480 let () = match proof with
1481 | None -> (* drop *) ()
1482 | Some proof ->
1483 (* Unfortunately close_future_proof and friends are not pure so we need
1484 to set the state manually here *)
1485 State.unfreeze st;
1486 let pobject =
1487 PG_compat.close_future_proof ~feedback_id:stop (Future.from_val proof) in
1488
1489 let st = Vernacstate.freeze_full_state () in
1490 let opaque = Opaque in
1491 try
1492 let _pstate =
1493 stm_qed_delay_proof ~st ~id:stop
1494 ~proof:pobject ~loc ~control:[] (Proved (opaque,None)) in
1495 ()
1496 with exn ->
1497 (* If [stm_qed_delay_proof] fails above we need to use the
1498 exn callback in the same way than build_proof_here;
1499 actually [fix_exn] there does more more than just
1500 modifying exn info, it also updates the STM state *)
1501 let iexn = Exninfo.capture exn in
1502 let iexn = State.exn_on exn_info.Stateid.id ~valid:exn_info.Stateid.valid iexn in
1503 Exninfo.iraise iexn
1504 in
1505 (* STATE: Restore the state XXX: handle exn *)
1506 State.unfreeze st;
1507 RespBuiltProof(proof,time)
1508 with
1509 | e when CErrors.noncritical e || e = Stack_overflow ->
1510 let e, info = Exninfo.capture e in
1511 (* This can happen if the proof is broken. The error has also been
1512 * signalled as a feedback, hence we can silently recover *)
1513 let e_error_at, e_safe_id = match Stateid.get info with
1514 | Some (safe, err) -> err, safe
1515 | None -> Stateid.dummy, Stateid.dummy in
1516 let e_msg = iprint (e, info) in
1517 stm_pperr_endline Pp.(fun () -> str "failed with the following exception: " ++ fnl () ++ e_msg);
1518 let e_safe_states = List.filter State.is_cached_and_valid my_states in
1519 RespError { e_error_at; e_safe_id; e_msg; e_loc = Loc.get_loc info; e_safe_states }
1520
1521 let perform_states query =
1522 if query = [] then [] else
1523 let is_tac e = match Vernac_classifier.classify_vernac e with
1524 | VtProofStep _ -> true
1525 | _ -> false
1526 in
1527 let initial =
1528 let rec aux id =
1529 try match VCS.visit id with { next } -> aux next
1530 with VCS.Expired -> id in
1531 aux (List.hd query) in
1532 let get_state seen id =
1533 let prev =
1534 try
1535 let { next = prev; step } = VCS.visit id in
1536 if State.is_cached_and_valid prev && List.mem prev seen
1537 then Some (prev, State.get_cached prev, step)
1538 else None
1539 with VCS.Expired -> None in
1540 let this =
1541 if State.is_cached_and_valid id then Some (State.get_cached id) else None in
1542 match prev, this with
1543 | _, None -> None
1544 | Some (prev, o, SCmd { cast = { expr }}), Some n
1545 when is_tac expr && Vernacstate.Stm.same_env o n -> (* A pure tactic *)
1546 Some (id, State.ProofOnly (prev, Vernacstate.Stm.pstate n))
1547 | Some _, Some s ->
1548 if CDebug.(get_flag misc) then msg_debug (Pp.str "STM: sending back a fat state");
1549 Some (id, State.Full s)
1550 | _, Some s -> Some (id, State.Full s) in
1551 let rec aux seen = function
1552 | [] -> []
1553 | id :: rest ->
1554 match get_state seen id with
1555 | None -> aux seen rest
1556 | Some stuff -> stuff :: aux (id :: seen) rest in
1557 aux [initial] query
1558
1559 let perform = function
1560 | ReqBuildProof (bp,drop,states) -> perform_buildp bp drop states
1561 | ReqStates sl -> RespStates (perform_states sl)
1562
1563 let on_marshal_error s = function
1564 | States _ ->
1565 msg_warning Pp.(strbrk("Marshalling error: "^s^". "^
1566 "The system state could not be sent to the master process."))
1567 | BuildProof { t_exn_info; t_stop; t_assign; t_loc; t_drop = drop_pt } ->
1568 msg_warning Pp.(strbrk("Marshalling error: "^s^". "^
1569 "The system state could not be sent to the worker process. "^
1570 "Falling back to local, lazy, evaluation."));
1571 t_assign(`Comp(fun () -> build_proof_here_fun ~doc:dummy_doc (* XXX should be stored in a closure, it is the same doc that was used to generate the task *) ?loc:t_loc ~drop_pt ~id:t_exn_info.Stateid.id t_stop));
1572 feedback (InProgress ~-1)
1573
1574 end (* }}} *)
1575
1576 (* Slave processes (if initialized, otherwise local lazy evaluation) *)
1577 and Slaves : sig
1578
1579 (* (eventually) remote calls *)
1580 val build_proof
1581 : doc:doc
1582 -> ?loc:Loc.t
1583 -> drop_pt:bool
1584 -> exn_info:Stateid.exn_info
1585 -> block_start:Stateid.t
1586 -> block_stop:Stateid.t
1587 -> name:string
1588 -> unit
1589 -> future_proof * AsyncTaskQueue.cancel_switch
1590
1591 (* blocking function that waits for the task queue to be empty *)
1592 val wait_all_done : unit -> unit
1593
1594 (* initialize the whole machinery (optional) *)
1595 val init : spawn_args:string list -> CoqworkmgrApi.priority -> unit
1596
1597 type 'a tasks = (('a,VCS.vcs) Stateid.request * bool) list
1598 val dump_snapshot : unit -> Future.UUID.t tasks
1599
1600 val cancel_worker : WorkerPool.worker_id -> unit
1601
1602 val reset_task_queue : unit -> unit
1603
1604 end = struct (* {{{ *)
1605
1606 module TaskQueue = AsyncTaskQueue.MakeQueue(ProofTask) ()
1607
1608 let queue = ref None
1609 let init ~spawn_args priority =
1610 if async_proofs_is_master (cur_opt()) then
1611 queue := Some (TaskQueue.create ~spawn_args (cur_opt()).async_proofs_n_workers priority)
1612 else
1613 queue := Some (TaskQueue.create ~spawn_args 0 priority)
1614
1615 let build_proof ~doc ?loc ~drop_pt ~exn_info ~block_start ~block_stop ~name:pname () =
1616 let cancel_switch = ref false in
1617 let n_workers = TaskQueue.n_workers (Option.get !queue) in
1618 if Int.equal n_workers 0 && not (VCS.is_vos_doc ()) then
1619 ProofTask.build_proof_here ~doc ?loc ~drop_pt exn_info block_stop, cancel_switch
1620 else
1621 let f, t_assign = Future.create_delegate ~name:pname (Some exn_info) in
1622 let t_uuid = Future.uuid f in
1623 if n_workers > 0 then feedback (InProgress 1);
1624 let task = ProofTask.(BuildProof {
1625 t_exn_info = exn_info; t_start = block_start; t_stop = block_stop; t_assign; t_drop = drop_pt;
1626 t_loc = loc; t_uuid; t_name = pname;
1627 t_states = VCS.nodes_in_slice ~block_start ~block_stop }) in
1628 TaskQueue.enqueue_task (Option.get !queue) task ~cancel_switch;
1629 f, cancel_switch
1630
1631 let wait_all_done () = TaskQueue.join (Option.get !queue)
1632
1633 let cancel_worker n = TaskQueue.cancel_worker (Option.get !queue) n
1634
1635 (* For external users this name is nicer than request *)
1636 type 'a tasks = (('a,VCS.vcs) Stateid.request * bool) list
1637 let dump_snapshot () =
1638 let tasks = TaskQueue.snapshot (Option.get !queue) in
1639 let reqs =
1640 CList.map_filter
1641 ProofTask.(fun x ->
1642 match request_of_task Fresh x with
1643 | Some (ReqBuildProof (r, b, _)) -> Some(r, b)
1644 | _ -> None)
1645 tasks in
1646 stm_prerr_endline (fun () -> Printf.sprintf "dumping %d tasks\n" (List.length reqs));
1647 reqs
1648
1649 let reset_task_queue () = TaskQueue.clear (Option.get !queue)
1650
1651 end (* }}} *)
1652
1653 and QueryTask : sig
1654
1655 type task = { t_where : Stateid.t; t_for : Stateid.t ; t_what : aast }
1656 include AsyncTaskQueue.Task with type task := task
1657
1658 end = struct (* {{{ *)
1659
1660 type task =
1661 { t_where : Stateid.t; t_for : Stateid.t ; t_what : aast }
1662
1663 type request =
1664 { r_where : Stateid.t ; r_for : Stateid.t ; r_what : aast; r_doc : VCS.vcs }
1665 type response = unit
1666
1667 let name = "query"
1668 let extra_env _ = [||]
1669 type competence = unit
1670 type worker_status = Fresh | Old of competence
1671
1672 let task_match _ _ = true
1673
1674 let request_of_task _ { t_where; t_what; t_for } =
1675 try Some {
1676 r_where = t_where;
1677 r_for = t_for;
1678 r_doc = VCS.slice ~block_start:t_where ~block_stop:t_where;
1679 r_what = t_what }
1680 with VCS.Expired -> None
1681
1682 let use_response _ _ _ = `End
1683
1684 let on_marshal_error _ _ =
1685 stm_pr_err ("Fatal marshal error in query");
1686 flush_all (); exit 1
1687
1688 let on_task_cancellation_or_expiration_or_slave_death _ = ()
1689
1690 let forward_feedback msg = !Hooks.forward_feedback msg
1691
1692 let perform { r_where; r_doc; r_what; r_for } =
1693 VCS.restore r_doc;
1694 VCS.print ();
1695 Reach.known_state ~doc:dummy_doc (* XXX should be r_doc *) ~cache:false r_where;
1696 (* STATE *)
1697 let st = Vernacstate.freeze_full_state () in
1698 try
1699 (* STATE SPEC:
1700 * - start: r_where
1701 * - end : after execution of r_what
1702 *)
1703 ignore(stm_vernac_interp r_for st { r_what with verbose = true });
1704 feedback ~id:r_for Processed
1705 with e when CErrors.noncritical e ->
1706 let e,_ as ie = Exninfo.capture e in
1707 let msg = iprint ie in
1708 let qf = Result.value ~default:[] (Quickfix.from_exception e) in
1709 feedback ~id:r_for (Message (Error, None, qf, msg))
1710
1711 let name_of_task { t_what } = string_of_ppcmds (pr_ast t_what)
1712 let name_of_request { r_what } = string_of_ppcmds (pr_ast r_what)
1713
1714 end (* }}} *)
1715
1716 and Query : sig
1717
1718 val init : CoqworkmgrApi.priority -> unit
1719
1720 end = struct (* {{{ *)
1721
1722 module TaskQueue = AsyncTaskQueue.MakeQueue(QueryTask) ()
1723
1724 let queue = ref None
1725
1726 let init priority = queue := Some (TaskQueue.create 0 priority)
1727
1728 end (* }}} *)
1729
1730 (* Runs all transactions needed to reach a state *)
1731 and Reach : sig
1732
1733 val known_state :
1734 doc:doc -> ?redefine_qed:bool -> cache:bool ->
1735 Stateid.t -> unit
1736
1737 end = struct (* {{{ *)
1738
1739 let async_policy () =
1740 if Attributes.is_universe_polymorphism () then false (* FIXME this makes no sense, it is the default value of the attribute *)
1741 else if VCS.is_interactive () then
1742 (async_proofs_is_master (cur_opt()) || (cur_opt()).async_proofs_mode = APonLazy)
1743 else
1744 (VCS.is_vos_doc () || (cur_opt()).async_proofs_mode <> APoff)
1745
1746 let delegate name =
1747 get_hint_bp_time name >= (cur_opt()).async_proofs_delegation_threshold
1748 || VCS.is_vos_doc ()
1749
1750 type reason =
1751 | Aborted
1752 | Alias
1753 | AlreadyEvaluated
1754 | Doesn'tGuaranteeOpacity
1755 | Immediate
1756 | MutualProofs
1757 | NestedProof
1758 | NoPU_NoHint_NoES
1759 | Policy
1760 | Print
1761 | Transparent
1762 | Unknown
1763
1764 type sync_kind =
1765 | Sync of string * reason
1766 | ASync of Stateid.t * Stateid.t list * string * bool
1767 | MaybeASync of Stateid.t * Stateid.t list * string * bool
1768
1769 let collect_proof keep cur hd brkind id =
1770 stm_prerr_endline (fun () -> "Collecting proof ending at "^Stateid.to_string id);
1771 let no_name = "" in
1772 let name = function
1773 | [] -> no_name
1774 | id :: _ -> Names.Id.to_string id in
1775 let loc = (snd cur).expr.CAst.loc in
1776 let is_defined_expr = function
1777 | VernacSynPure (VernacEndProof (Proved (Transparent,_))) -> true
1778 | _ -> false in
1779 let is_defined = function
1780 | _, { expr = e } -> is_defined_expr e.CAst.v.expr
1781 && (not (Vernacprop.has_query_control e)) in
1782 let has_default_proof_using = Option.has_some (Proof_using.get_default_proof_using ()) in
1783 let proof_using_ast = function
1784 | VernacSynPure(VernacProof(_,Some _)) -> true
1785 | VernacSynPure(VernacProof(_,None)) -> has_default_proof_using
1786 | _ -> false
1787 in
1788 let proof_using_ast = function
1789 | Some (_, v) when proof_using_ast v.expr.CAst.v.expr
1790 && (not (Vernacprop.has_query_control v.expr)) -> Some v
1791 | _ -> None in
1792 let has_proof_using x = proof_using_ast x <> None in
1793 let proof_no_using = function
1794 | VernacSynPure (VernacProof(t,None)) -> if has_default_proof_using then None else t
1795 | _ -> assert false
1796 in
1797 let proof_no_using = function
1798 | Some (_, v) -> proof_no_using v.expr.CAst.v.expr, v
1799 | _ -> assert false in
1800 let has_proof_no_using = function
1801 | VernacSynPure (VernacProof(_,None)) -> not has_default_proof_using
1802 | _ -> false
1803 in
1804 let has_proof_no_using = function
1805 | Some (_, v) -> has_proof_no_using v.expr.CAst.v.expr
1806 && (not (Vernacprop.has_query_control v.expr))
1807 | _ -> false in
1808 let too_complex_to_delegate = function
1809 VernacSynterp (VernacDeclareModule _
1810 | VernacDefineModule _
1811 | VernacDeclareModuleType _
1812 | VernacInclude _
1813 | VernacRequire _
1814 | VernacImport _) -> true
1815 | ast -> may_pierce_opaque ast in
1816 let parent = function Some (p, _) -> p | None -> assert false in
1817 let is_empty = function ASync(_,[],_,_) | MaybeASync(_,[],_,_) -> true | _ -> false in
1818 let rec collect last accn id =
1819 let view = VCS.visit id in
1820 match view.step with
1821 | (SSideff (ReplayCommand x,_) | SCmd { cast = x })
1822 when too_complex_to_delegate x.expr.CAst.v.expr ->
1823 Sync(no_name,Print)
1824 | SCmd { cast = x } -> collect (Some (id,x)) (id::accn) view.next
1825 | SSideff (ReplayCommand x,_) -> collect (Some (id,x)) (id::accn) view.next
1826 (* An Alias could jump everywhere... we hope we can ignore it*)
1827 | SAlias _ -> Sync (no_name,Alias)
1828 | SFork((_,_,_,_::_::_), _) ->
1829 Sync (no_name,MutualProofs)
1830 | SFork((_,_,Doesn'tGuaranteeOpacity,_), _) ->
1831 Sync (no_name,Doesn'tGuaranteeOpacity)
1832 | SFork((_,hd',GuaranteesOpacity,ids), _) when has_proof_using last ->
1833 assert (VCS.Branch.equal hd hd' || VCS.Branch.equal hd VCS.edit_branch);
1834 let name = name ids in
1835 ASync (parent last,accn,name,delegate name)
1836 | SFork((_, hd', GuaranteesOpacity, ids), _) when
1837 has_proof_no_using last && not (State.is_cached_and_valid (parent last)) &&
1838 VCS.is_vos_doc () ->
1839 assert (VCS.Branch.equal hd hd'||VCS.Branch.equal hd VCS.edit_branch);
1840 (try
1841 let name, hint = name ids, get_hint_ctx loc in
1842 let t, v = proof_no_using last in
1843 v.expr <- CAst.map (fun _ -> { control = []; attrs = []; expr = VernacSynPure (VernacProof(t, Some hint))}) v.expr;
1844 ASync (parent last,accn,name,delegate name)
1845 with Not_found ->
1846 let name = name ids in
1847 MaybeASync (parent last, accn, name, delegate name))
1848 | SFork((_, hd', GuaranteesOpacity, ids), _) ->
1849 assert (VCS.Branch.equal hd hd' || VCS.Branch.equal hd VCS.edit_branch);
1850 let name = name ids in
1851 MaybeASync (parent last, accn, name, delegate name)
1852 | SSideff (CherryPickEnv,_) ->
1853 Sync (no_name,NestedProof)
1854 | SQed _ -> Sync (no_name,Unknown)
1855 in
1856 let make_sync why = function
1857 | Sync(name,_) -> Sync (name,why)
1858 | MaybeASync(_,_,name,_) -> Sync (name,why)
1859 | ASync(_,_,name,_) -> Sync (name,why) in
1860
1861 let check_policy rc = if async_policy () then rc else make_sync Policy rc in
1862 let is_vernac_exact = function
1863 | VernacSynPure (VernacExactProof _) -> true
1864 | _ -> false
1865 in
1866 match cur, (VCS.visit id).step, brkind with
1867 | (parent, x), SFork _, _ when is_vernac_exact x.expr.CAst.v.expr
1868 && (not (Vernacprop.has_query_control x.expr)) ->
1869 Sync (no_name,Immediate)
1870 | _, _, { VCS.kind = Edit _ } -> check_policy (collect (Some cur) [] id)
1871 | _ ->
1872 if is_defined cur then Sync (no_name,Transparent)
1873 else if keep == VtDrop then Sync (no_name,Aborted)
1874 else
1875 let rc = collect (Some cur) [] id in
1876 if is_empty rc then make_sync AlreadyEvaluated rc
1877 else if (is_vtkeep keep) && (not(State.is_cached_and_valid id))
1878 then check_policy rc
1879 else make_sync AlreadyEvaluated rc
1880
1881 let string_of_reason = function
1882 | Transparent -> "non opaque"
1883 | AlreadyEvaluated -> "proof already evaluated"
1884 | Policy -> "policy"
1885 | NestedProof -> "contains nested proof"
1886 | Immediate -> "proof term given explicitly"
1887 | Aborted -> "aborted proof"
1888 | Doesn'tGuaranteeOpacity -> "not a simple opaque lemma"
1889 | MutualProofs -> "block of mutually recursive proofs"
1890 | Alias -> "contains Undo-like command"
1891 | Print -> "contains Print-like command"
1892 | NoPU_NoHint_NoES -> "no 'Proof using..', no .aux file, inside a section"
1893 | Unknown -> "unsupported case"
1894
1895 let log_string s = stm_prerr_debug (fun () -> "STM: " ^ s)
1896 let log_processing_async id name = log_string Printf.(sprintf
1897 "%s: proof %s: asynch" (Stateid.to_string id) name
1898 )
1899 let log_processing_sync id name reason = log_string Printf.(sprintf
1900 "%s: proof %s: synch (cause: %s)"
1901 (Stateid.to_string id) name (string_of_reason reason)
1902 )
1903
1904 let wall_clock_last_fork = ref 0.0
1905
1906 let known_state ~doc ?(redefine_qed=false) ~cache id =
1907
1908 let error_absorbing_tactic id blockname exn =
1909 (* We keep the static/dynamic part of block detection separate, since
1910 the static part could be performed earlier. As of today there is
1911 no advantage in doing so since no UI can exploit such piece of info *)
1912 detect_proof_block id blockname;
1913
1914 let boxes = VCS.box_of id in
1915 let valid_boxes = CList.map_filter (function
1916 | ProofBlock ({ block_stop } as decl, name) when Stateid.equal block_stop id ->
1917 Some (decl, name)
1918 | _ -> None) boxes in
1919 assert(List.length valid_boxes < 2);
1920 if valid_boxes = [] then Exninfo.iraise exn
1921 else
1922 let decl, name = List.hd valid_boxes in
1923 try
1924 let _, dynamic_check = List.assoc name !proof_block_delimiters in
1925 match dynamic_check dummy_doc decl with
1926 | Leaks -> Exninfo.iraise exn
1927 | ValidBlock { base_state; goals_to_admit; recovery_command } -> begin
1928 let tac =
1929 Proofview.Goal.enter begin fun gl ->
1930 if CList.mem_f Evar.equal
1931 (Proofview.Goal.goal gl) goals_to_admit then
1932 Proofview.give_up else Proofview.tclUNIT ()
1933 end in
1934 match (VCS.get_info base_state).state with
1935 | FullState { Vernacstate.interp = { lemmas } } ->
1936 Option.iter PG_compat.unfreeze lemmas;
1937 PG_compat.with_current_proof (fun p ->
1938 let () = feedback ~id:id Feedback.AddedAxiom in
1939 let (pf, _) = Proof.solve (Global.env ()) Goal_select.SelectAll None tac p in
1940 pf, ());
1941 (* STATE SPEC:
1942 * - start: Modifies the input state adding a proof.
1943 * - end : maybe after recovery command.
1944 *)
1945 (* STATE: We use an updated state with proof *)
1946 let st = Vernacstate.freeze_full_state () in
1947 Option.iter (fun expr -> ignore(stm_vernac_interp id st {
1948 verbose = true; expr; indentation = 0;
1949 strlen = 0 } ))
1950 recovery_command
1951 | _ -> assert false
1952 end
1953 with Not_found ->
1954 CErrors.user_err
1955 (str "Unknown proof block delimiter " ++ str name ++ str ".")
1956 in
1957
1958 (* Absorb tactic errors from f () *)
1959 let resilient_tactic id blockname f =
1960 if (cur_opt()).async_proofs_tac_error_resilience = FNone ||
1961 (async_proofs_is_master (cur_opt()) &&
1962 (cur_opt()).async_proofs_mode = APoff)
1963 then f ()
1964 else
1965 try f ()
1966 with e when CErrors.noncritical e ->
1967 let ie = Exninfo.capture e in
1968 error_absorbing_tactic id blockname ie in
1969 (* Absorb errors from f x *)
1970 let resilient_command f x =
1971 if not (cur_opt()).async_proofs_cmd_error_resilience ||
1972 (async_proofs_is_master (cur_opt()) &&
1973 (cur_opt()).async_proofs_mode = APoff)
1974 then f x
1975 else
1976 try f x
1977 with e when CErrors.noncritical e -> () in
1978
1979 (* extract proof_ending in qed case, note that `Abort` and `Proof
1980 term.` could also fail in this case, however that'd be a bug I do
1981 believe as proof injection shouldn't happen here. *)
1982 let extract_pe (x : aast) =
1983 match x.expr.CAst.v.expr with
1984 | VernacSynPure (VernacEndProof pe) -> x.expr.CAst.v.control, pe
1985 | _ -> CErrors.anomaly Pp.(str "Non-qed command classified incorrectly") in
1986
1987 (* ugly functions to process nested lemmas, i.e. hard to reproduce
1988 * side effects *)
1989 let inject_non_pstate (s_synterp,l_synterp,s_interp,l_interp) =
1990 Summary.Synterp.unfreeze_summaries ~partial:true s_synterp;
1991 Lib.Synterp.unfreeze l_synterp;
1992 Summary.Interp.unfreeze_summaries ~partial:true s_interp;
1993 Lib.Interp.unfreeze l_interp;
1994 if PG_compat.there_are_pending_proofs () then
1995 PG_compat.update_sigma_univs (Global.universes ())
1996 in
1997
1998 let rec pure_cherry_pick_non_pstate safe_id id =
1999 State.purify (fun id ->
2000 stm_prerr_endline (fun () -> "cherry-pick non pstate " ^ Stateid.to_string id);
2001 reach ~safe_id id;
2002 let st = Vernacstate.freeze_full_state () in
2003 Vernacstate.Stm.non_pstate st)
2004 id
2005
2006 (* traverses the dag backward from nodes being already calculated *)
2007 and reach ?safe_id ?(redefine_qed=false) ?(cache=cache) id =
2008 stm_prerr_endline (fun () -> "reaching: " ^ Stateid.to_string id);
2009 if not redefine_qed && State.is_cached ~cache id then begin
2010 !Hooks.state_computed ~doc id ~in_cache:true;
2011 stm_prerr_endline (fun () -> "reached (cache)");
2012 State.install_cached id
2013 end else
2014 let step, cache_step, feedback_processed =
2015 let view = VCS.visit id in
2016 match view.step with
2017 | SAlias (id,_) -> (fun () ->
2018 reach view.next; reach id
2019 ), cache, true
2020 | SCmd { cast = x; cqueue = SkipQueue } -> (fun () ->
2021 reach view.next), cache, true
2022 | SCmd { cast = x; ceff = eff; ctac = true; cblock } -> (fun () ->
2023 resilient_tactic id cblock (fun () ->
2024 reach view.next;
2025 let st = Vernacstate.freeze_full_state () in
2026 ignore(stm_vernac_interp id st x)
2027 )
2028 ), eff || cache, true
2029 | SCmd { cast = x; ceff = eff } -> (fun () ->
2030 (match (cur_opt()).async_proofs_mode with
2031 | APon | APonLazy ->
2032 resilient_command reach view.next
2033 | APoff -> reach view.next);
2034 let st = Vernacstate.freeze_full_state () in
2035 ignore(stm_vernac_interp id st x)
2036 ), eff || cache, true
2037 | SFork ((x,_,_,_), None) -> (fun () ->
2038 resilient_command reach view.next;
2039 let st = Vernacstate.freeze_full_state () in
2040 ignore(stm_vernac_interp id st x);
2041 wall_clock_last_fork := Unix.gettimeofday ()
2042 ), true, true
2043 | SFork ((x,_,_,_), Some prev) -> (fun () -> (* nested proof *)
2044 reach ~cache:true prev;
2045 reach view.next;
2046
2047 (try
2048 let st = Vernacstate.freeze_full_state () in
2049 ignore(stm_vernac_interp id st x);
2050 with e when CErrors.noncritical e ->
2051 let (e, info) = Exninfo.capture e in
2052 let info = Stateid.add info ~valid:prev id in
2053 Exninfo.iraise (e, info));
2054 wall_clock_last_fork := Unix.gettimeofday ()
2055 ), true, true
2056 | SQed ({ qast = x; keep; brinfo; brname } as qed, eop) ->
2057 let rec aux = function
2058 | ASync (block_start, nodes, name, delegate) -> (fun () ->
2059 let keep' = get_vtkeep keep in
2060 let drop_pt = keep' == VtKeepAxiom in
2061 let block_stop, exn_info, loc = eop, Stateid. { id; valid = eop }, x.expr.CAst.loc in
2062 log_processing_async id name;
2063 VCS.create_proof_task_box nodes ~qed:id ~block_start;
2064 begin match brinfo, qed.fproof with
2065 | { VCS.kind = Edit _ }, None -> assert false
2066 | { VCS.kind = Edit (_,_, okeep, _) }, Some (ofp, cancel) ->
2067 assert(redefine_qed = true);
2068 if okeep <> keep then
2069 msg_warning(strbrk("The command closing the proof changed. "
2070 ^"The kernel cannot take this into account and will "
2071 ^(if not drop_pt then "not check " else "reject ")
2072 ^"the "^(if not drop_pt then "new" else "incomplete")
2073 ^" proof. Reprocess the command declaring "
2074 ^"the proof's statement to avoid that."));
2075 let fp, cancel =
2076 Slaves.build_proof ~doc
2077 ?loc ~drop_pt ~exn_info ~block_start ~block_stop ~name () in
2078 Future.replace (Option.get ofp) fp;
2079 qed.fproof <- Some (Some fp, cancel);
2080 (* We don't generate a new state, but we still need
2081 * to install the right one *)
2082 State.install_cached id
2083 | { VCS.kind = Proof _ }, Some _ -> assert false
2084 | { VCS.kind = Proof _ }, None ->
2085 reach ~cache:true block_start;
2086 let fp, cancel =
2087 if delegate then
2088 Slaves.build_proof ~doc
2089 ?loc ~drop_pt ~exn_info ~block_start ~block_stop ~name ()
2090 else
2091 ProofTask.build_proof_here ~doc ?loc
2092 ~drop_pt exn_info block_stop, ref false
2093 in
2094 qed.fproof <- Some (Some fp, cancel);
2095 let () = match keep' with
2096 | VtKeepAxiom | VtKeepOpaque -> ()
2097 | VtKeepDefined ->
2098 CErrors.anomaly (Pp.str "Cannot delegate transparent proofs, this is a bug in the STM.")
2099 in
2100 let fp' = Future.chain fp (function
2101 | Some p -> p
2102 | None ->
2103 CErrors.anomaly Pp.(str "Attempting to force admitted proof contents."))
2104 in
2105 let control, pe = extract_pe x in
2106 let control = VernacControl.from_syntax control in
2107 let control, proof =
2108 VernacControl.under_control ~loc:x.expr.loc
2109 ~with_local_state:VernacControl.trivial_state
2110 control
2111 ~noop:None
2112 (fun () -> Some (PG_compat.close_future_proof ~feedback_id:id fp'))
2113 in
2114 (* We only get [noop] from [Fail],
2115 but we can't see [Fail] in this classification. *)
2116 let proof = Option.get proof in
2117 if not delegate then ignore(Future.compute fp);
2118 reach view.next;
2119 let st = Vernacstate.freeze_full_state () in
2120 ignore(stm_qed_delay_proof ~id ~st ~proof ~loc ~control pe);
2121 feedback ~id:id Incomplete
2122 | { VCS.kind = Master }, _ -> assert false
2123 end;
2124 PG_compat.discard_all ()
2125 ), not redefine_qed, true
2126 | Sync (name, Immediate) -> (fun () ->
2127 reach eop;
2128 let st = Vernacstate.freeze_full_state () in
2129 ignore(stm_vernac_interp id st x);
2130 PG_compat.discard_all ()
2131 ), true, true
2132 | Sync (name, reason) -> (fun () ->
2133 log_processing_sync id name reason;
2134 reach eop;
2135 let wall_clock = Unix.gettimeofday () in
2136 let loc = x.expr.CAst.loc in
2137 record_pb_time name ?loc (wall_clock -. !wall_clock_last_fork);
2138 let proof =
2139 match keep with
2140 | VtDrop -> None
2141 | VtKeep VtKeepAxiom ->
2142 qed.fproof <- Some (None, ref false); None
2143 | VtKeep opaque ->
2144 let opaque = match opaque with
2145 | VtKeepOpaque -> Opaque | VtKeepDefined -> Transparent
2146 | VtKeepAxiom -> assert false
2147 in
2148 let control, pe = extract_pe x in
2149 let control = VernacControl.from_syntax control in
2150 let control, proof =
2151 try
2152 VernacControl.under_control ~loc:x.expr.loc
2153 ~with_local_state:VernacControl.trivial_state
2154 control
2155 (* noop should be unreachable in this classification *)
2156 ~noop:None
2157 (fun () ->
2158 Some (PG_compat.close_proof ~opaque ~keep_body_ucst_separate:false))
2159 with exn ->
2160 let iexn = Exninfo.capture exn in
2161 Exninfo.iraise (State.exn_on id ~valid:eop iexn)
2162 in
2163 match proof with
2164 | None -> assert false
2165 | Some proof -> Some (control, pe, proof)
2166 in
2167 if keep <> VtKeep VtKeepAxiom then
2168 reach view.next;
2169 let wall_clock2 = Unix.gettimeofday () in
2170 let st = Vernacstate.freeze_full_state () in
2171 let _st = match proof with
2172 | None -> stm_vernac_interp id st x
2173 | Some (control,pe,proof) ->
2174 { st with interp = stm_qed_delay_proof ~id ~st ~proof ~loc ~control pe }
2175 in
2176 let wall_clock3 = Unix.gettimeofday () in
2177 Aux_file.record_in_aux_at ?loc:x.expr.CAst.loc "proof_check_time"
2178 (Printf.sprintf "%.3f" (wall_clock3 -. wall_clock2));
2179 PG_compat.discard_all ()
2180 ), true, true
2181 | MaybeASync (start, nodes, name, delegate) -> (fun () ->
2182 reach ~cache:true start;
2183 if CList.is_empty (Environ.named_context (Global.env ())) (* no sections *)
2184 || PG_compat.get_pstate () |> (* #[using] attribute *)
2185 Option.cata (fun x -> Option.has_some (Declare.Proof.get_used_variables x)) false
2186 then Util.pi1 (aux (ASync (start, nodes, name, delegate))) ()
2187 else Util.pi1 (aux (Sync (name, NoPU_NoHint_NoES))) ()
2188 ), not redefine_qed, true
2189 in
2190 aux (collect_proof keep (view.next, x) brname brinfo eop)
2191 | SSideff (ReplayCommand x,_) -> (fun () ->
2192 reach view.next;
2193 let st = Vernacstate.freeze_full_state () in
2194 ignore(stm_vernac_interp id st x)
2195 ), cache, true
2196 | SSideff (CherryPickEnv, origin) -> (fun () ->
2197 reach view.next;
2198 inject_non_pstate (pure_cherry_pick_non_pstate view.next origin);
2199 ), cache, true
2200 in
2201 let cache_step =
2202 (cur_opt()).async_proofs_cache = Some Force || cache_step
2203 in
2204 State.define ~doc ?safe_id
2205 ~cache:cache_step ~redefine:redefine_qed ~feedback_processed step id;
2206 stm_prerr_endline (fun () -> "reached: "^ Stateid.to_string id) in
2207 reach ~redefine_qed id
2208
2209 end (* }}} *)
2210 [@@@ocaml.warning "+60"]
2211
2212 (********************************* STM API ************************************)
2213 (******************************************************************************)
2214
2215 (** STM initialization options: *)
2216
2217 type stm_init_options =
2218 { doc_type : stm_doc_type
2219 (** The STM does set some internal flags differently depending on
2220 the specified [doc_type]. This distinction should disappear at
2221 some some point. *)
2222
2223 ; injections : Coqargs.injection_command list
2224 (** Injects Require and Set/Unset commands before the initial
2225 state is ready *)
2226
2227 }
2228
2229 let init_process stm_flags =
2230 Spawned.init_channels ();
2231 set_cur_opt stm_flags;
2232 CoqworkmgrApi.(init stm_flags.AsyncOpts.async_proofs_worker_priority);
2233 if (cur_opt()).async_proofs_mode = APon then Control.enable_thread_delay := true;
2234 if !Flags.async_proofs_worker_id = "master" && (cur_opt()).async_proofs_n_tacworkers > 0 then
2235 Partac.enable_par ~spawn_args:stm_flags.spawn_args ~nworkers:(cur_opt()).async_proofs_n_tacworkers
2236
2237 let init_core () =
2238 State.register_root_state ()
2239
2240 let new_doc { doc_type ; injections } =
2241
2242 (* We must reset the whole state before creating a document! *)
2243 State.restore_root_state ();
2244
2245 let doc =
2246 let ps = Procq.freeze () in
2247 VCS.init doc_type Stateid.initial ps
2248 in
2249
2250 Safe_typing.allow_delayed_constants := (cur_opt()).async_proofs_mode <> APoff;
2251
2252 let top =
2253 match doc_type with
2254 | Interactive top -> Coqinit.dirpath_of_top top
2255
2256 | VoDoc f ->
2257 let ldir = Coqargs.(Coqinit.dirpath_of_top (TopPhysical f)) in
2258 VCS.set_ldir ldir;
2259 set_compilation_hints f;
2260 ldir
2261
2262 | VosDoc f ->
2263 let ldir = Coqargs.(Coqinit.dirpath_of_top (TopPhysical f)) in
2264 VCS.set_ldir ldir;
2265 set_compilation_hints f;
2266 ldir
2267 in
2268
2269 (* Start this library and import initial libraries. *)
2270 let intern = Vernacinterp.fs_intern in
2271 Coqinit.start_library ~intern ~top injections;
2272
2273 (* We record the state at this point! *)
2274 State.define ~doc ~cache:true ~redefine:true (fun () -> ()) Stateid.initial;
2275 Backtrack.record ();
2276 Slaves.init ~spawn_args:((cur_opt()).spawn_args) (cur_opt()).async_proofs_worker_priority;
2277 if async_proofs_is_master (cur_opt()) then begin
2278 stm_prerr_endline (fun () -> "Initializing workers");
2279 Query.init (cur_opt()).async_proofs_worker_priority;
2280 let opts = match (cur_opt()).async_proofs_private_flags with
2281 | None -> []
2282 | Some s -> Str.split_delim (Str.regexp ",") s in
2283 begin try
2284 let env_opt = Str.regexp "^extra-env=" in
2285 let env = List.find (fun s -> Str.string_match env_opt s 0) opts in
2286 async_proofs_workers_extra_env := Array.of_list
2287 (Str.split_delim (Str.regexp ";") (Str.replace_first env_opt "" env))
2288 with Not_found -> () end;
2289 end;
2290 doc, VCS.cur_tip ()
2291
2292 let observe ~doc id =
2293 !Hooks.sentence_exec id;
2294 let vcs = VCS.backup () in
2295 try
2296 Reach.known_state ~doc ~cache:(VCS.is_interactive ()) id;
2297 VCS.print ()
2298 with e ->
2299 let e = Exninfo.capture e in
2300 VCS.print ();
2301 VCS.restore vcs;
2302 Exninfo.iraise e
2303
2304 let finish ~doc =
2305 let head = VCS.current_branch () in
2306 let () = observe ~doc (VCS.get_branch_pos head) in
2307 let tip = VCS.cur_tip () in
2308 if not (State.is_cached ~cache:true tip) then
2309 CErrors.anomaly Pp.(str "Stm.finish: tip not cached");
2310 VCS.print ();
2311 State.get_cached tip
2312
2313 let wait ~doc =
2314 let () = observe ~doc (VCS.get_branch_pos VCS.Branch.master) in
2315 Slaves.wait_all_done ();
2316 VCS.print ()
2317
2318 let rec join_admitted_proofs id =
2319 if Stateid.equal id Stateid.initial then () else
2320 let view = VCS.visit id in
2321 match view.step with
2322 | SQed ({ keep = VtKeep VtKeepAxiom; fproof = Some (fp,_) },_) ->
2323 Option.iter (fun fp -> ignore(Future.force fp)) fp;
2324 join_admitted_proofs view.next
2325 | _ -> join_admitted_proofs view.next
2326
2327 (* Error resiliency may have tolerated some broken commands *)
2328 let rec check_no_err_states ~doc visited id =
2329 let open Stateid in
2330 if Set.mem id visited then visited else
2331 match state_of_id ~doc id with
2332 | Error e -> raise e
2333 | _ ->
2334 let view = VCS.visit id in
2335 match view.step with
2336 | SQed(_,id) ->
2337 let visited = check_no_err_states ~doc (Set.add id visited) id in
2338 check_no_err_states ~doc visited view.next
2339 | _ -> check_no_err_states ~doc (Set.add id visited) view.next
2340
2341 let join ~doc =
2342 let () = wait ~doc in
2343 stm_prerr_endline (fun () -> "Joining the environment");
2344 let () = Opaques.Summary.join () in
2345 stm_prerr_endline (fun () -> "Joining Admitted proofs");
2346 join_admitted_proofs (VCS.get_branch_pos VCS.Branch.master);
2347 stm_prerr_endline (fun () -> "Checking no error states");
2348 ignore(check_no_err_states ~doc (Stateid.Set.singleton Stateid.initial)
2349 (VCS.get_branch_pos VCS.Branch.master));
2350 let tip = VCS.cur_tip () in
2351 if not (State.is_cached ~cache:true tip) then
2352 CErrors.anomaly Pp.(str "Stm.join: tip not cached");
2353 VCS.print ()
2354
2355 type branch_result = Ok | Unfocus of Stateid.t
2356
2357 let merge_proof_branch ~valid ?id qast keep brname =
2358 let brinfo = VCS.get_branch brname in
2359 let qed fproof = { qast; keep; brname; brinfo; fproof } in
2360 match brinfo with
2361 | { VCS.kind = Proof _ } ->
2362 VCS.checkout VCS.Branch.master;
2363 let id = VCS.new_node ?id None () in
2364 let parsing = Option.get @@ VCS.get_parsing_state (VCS.cur_tip ()) in
2365 VCS.merge id ~ours:(Qed (qed None)) brname;
2366 VCS.set_parsing_state id parsing;
2367 VCS.delete_branch brname;
2368 VCS.propagate_qed ();
2369 Ok
2370 | { VCS.kind = Edit (qed_id, master_id, _,_) } ->
2371 let ofp =
2372 match VCS.visit qed_id with
2373 | { step = SQed ({ fproof }, _) } -> fproof
2374 | _ -> assert false in
2375 VCS.rewrite_merge qed_id ~ours:(Qed (qed ofp)) ~at:master_id brname;
2376 VCS.delete_branch brname;
2377 VCS.gc ();
2378 let _st : unit = Reach.known_state ~doc:dummy_doc (* XXX should be taken in input *) ~redefine_qed:true ~cache:false qed_id in
2379 VCS.checkout VCS.Branch.master;
2380 Unfocus qed_id
2381 | { VCS.kind = Master } ->
2382 Exninfo.iraise (State.exn_on ~valid Stateid.dummy (PG_compat.NoCurrentProof, Exninfo.null))
2383
2384 (* When tty is true, this code also does some of the job of the user interface:
2385 jump back to a state that is valid *)
2386 let handle_failure (e, info) vcs =
2387 VCS.restore vcs;
2388 VCS.print ();
2389 Exninfo.iraise (e, info)
2390
2391 let snapshot_vos ~doc ~output_native_objects ldir long_f_dot_vo =
2392 let _ : Vernacstate.t = finish ~doc in
2393 if List.length (VCS.branches ()) > 1 then
2394 CErrors.user_err (str"Cannot dump a vos with open proofs.");
2395 (* LATER: when create_vos is true, it could be more efficient to not allocate the futures; but for now it seems useful for synchronization of the workers,
2396 below, [snapshot] gets computed even if [create_vos] is true. *)
2397 let tasks = Slaves.dump_snapshot() in
2398 let except = List.fold_left (fun e (r,_) ->
2399 Future.UUIDSet.add r.Stateid.uuid e) Future.UUIDSet.empty tasks in
2400 let todo_proofs = Library.ProofsTodoSomeEmpty except in
2401 Library.save_library_to todo_proofs ~output_native_objects ldir long_f_dot_vo
2402
2403 let reset_task_queue = Slaves.reset_task_queue
2404
2405 (* Document building *)
2406
2407 (* We process a meta command found in the document *)
2408 let process_back_meta_command ~newtip ~head oid aast =
2409 let valid = VCS.get_branch_pos head in
2410 let old_parsing = Option.get @@ VCS.get_parsing_state oid in
2411
2412 (* Merge in and discard all the branches currently open that were not open in `oid` *)
2413 let { mine; others } = Backtrack.branches_of oid in
2414 List.iter (fun branch ->
2415 if not (List.mem_assoc branch (mine::others)) then
2416 ignore(merge_proof_branch ~valid aast VtDrop branch))
2417 (VCS.branches ());
2418
2419 (* We add a node on top of every branch, to represent state aliasing *)
2420 VCS.checkout_shallowest_proof_branch ();
2421 let head = VCS.current_branch () in
2422 List.iter (fun b ->
2423 VCS.checkout b;
2424 let id = if (VCS.Branch.equal b head) then Some newtip else None in
2425 let proof_mode = VCS.get_proof_mode @@ VCS.cur_tip () in
2426 let id = VCS.new_node ?id proof_mode () in
2427 VCS.commit id (Alias (oid,aast));
2428 VCS.set_parsing_state id old_parsing)
2429 (VCS.branches ());
2430 VCS.checkout_shallowest_proof_branch ();
2431 Backtrack.record (); Ok
2432
2433 let { Goptions.get = get_allow_nested_proofs } =
2434 Goptions.declare_bool_option_and_ref
2435 ~key:Vernac_classifier.stm_allow_nested_proofs_option_name
2436 ~value:false
2437 ()
2438
2439 (** [process_transaction] adds a node in the document *)
2440 let process_transaction ~doc ?(newtip=Stateid.fresh ()) x c =
2441 let { verbose; expr } = x in
2442 stm_pperr_endline (fun () -> str "{{{ processing: " ++ pr_ast x);
2443 let vcs = VCS.backup () in
2444 try
2445 let head = VCS.current_branch () in
2446 VCS.checkout head;
2447 let head_parsing =
2448 Option.get @@ VCS.(get_parsing_state (get_branch_pos head)) in
2449 let proof_mode = VCS.(get_proof_mode (get_branch_pos head)) in
2450 let rc = begin
2451 stm_prerr_endline (fun () ->
2452 " classified as: " ^ Vernac_classifier.string_of_vernac_classification c);
2453 match c with
2454 (* Meta *)
2455 | VtMeta ->
2456 let id = Backtrack.undo_vernac_classifier expr ~doc in
2457 process_back_meta_command ~newtip ~head id x
2458
2459 (* Query *)
2460 | VtQuery ->
2461 let id = VCS.new_node ~id:newtip proof_mode () in
2462 let queue =
2463 if VCS.is_vos_doc () &&
2464 VCS.((get_branch head).kind = Master) &&
2465 may_pierce_opaque x.expr.CAst.v.expr
2466 then SkipQueue
2467 else MainQueue in
2468 VCS.commit id (mkTransCmd x [] false queue);
2469 VCS.set_parsing_state id head_parsing;
2470 Backtrack.record (); Ok
2471
2472 (* Proof *)
2473 | VtStartProof (guarantee, names) ->
2474
2475 if not (get_allow_nested_proofs ()) && VCS.proof_nesting () > 0 then
2476 "Nested proofs are discouraged and not allowed by default. \
2477 This error probably means that you forgot to close the last \"Proof.\" with \"Qed.\" or \"Defined.\". \
2478 If you really intended to use nested proofs, you can do so by turning the \"Nested Proofs Allowed\" flag on."
2479 |> Pp.strbrk
2480 |> (fun s -> (UserError s, Exninfo.null))
2481 |> State.exn_on ~valid:Stateid.dummy newtip
2482 |> Exninfo.iraise
2483 else
2484
2485 let proof_mode = Some (Synterp.get_default_proof_mode ()) in
2486 let id = VCS.new_node ~id:newtip proof_mode () in
2487 let bname = VCS.mk_branch_name x in
2488 VCS.checkout VCS.Branch.master;
2489 if VCS.Branch.equal head VCS.Branch.master then begin
2490 VCS.commit id (Fork (x, bname, guarantee, names));
2491 VCS.branch bname (Proof (VCS.proof_nesting () + 1))
2492 end else begin
2493 VCS.branch bname (Proof (VCS.proof_nesting () + 1));
2494 VCS.merge id ~ours:(Fork (x, bname, guarantee, names)) head
2495 end;
2496 VCS.set_parsing_state id head_parsing;
2497 Backtrack.record (); Ok
2498
2499 | VtProofStep { proof_block_detection = cblock } ->
2500 let id = VCS.new_node ~id:newtip proof_mode () in
2501 let queue = MainQueue in
2502 VCS.commit id (mkTransTac x cblock queue);
2503 (* Static proof block detection delayed until an error really occurs.
2504 If/when and UI will make something useful with this piece of info,
2505 detection should occur here.
2506 detect_proof_block id cblock; *)
2507 VCS.set_parsing_state id head_parsing;
2508 Backtrack.record (); Ok
2509
2510 | VtQed keep ->
2511 let valid = VCS.get_branch_pos head in
2512 let rc =
2513 merge_proof_branch ~valid ~id:newtip x keep head in
2514 VCS.checkout_shallowest_proof_branch ();
2515 Backtrack.record ();
2516 rc
2517
2518 (* Side effect in a (still open) proof is replayed on all branches*)
2519 | VtSideff (l, w) ->
2520 let id = VCS.new_node ~id:newtip proof_mode () in
2521 let new_ids =
2522 match (VCS.get_branch head).VCS.kind with
2523 | Edit _ -> VCS.commit id (mkTransCmd x l true MainQueue); []
2524 | Master -> VCS.commit id (mkTransCmd x l false MainQueue); []
2525 | Proof _ ->
2526 VCS.checkout VCS.Branch.master;
2527 VCS.commit id (mkTransCmd x l true MainQueue);
2528 (* We can't replay a Definition since universes may be differently
2529 * inferred. This holds in Coq >= 8.5 *)
2530 let action = match x.expr.CAst.v.expr with
2531 | VernacSynPure (VernacDefinition(_, _, DefineBody _)) -> CherryPickEnv
2532 | _ -> ReplayCommand x in
2533 VCS.propagate_sideff ~action
2534 in
2535 VCS.checkout_shallowest_proof_branch ();
2536 Backtrack.record ();
2537 let parsing_state =
2538 begin match w with
2539 | VtNow ->
2540 (* We need to execute to get the new parsing state *)
2541 let () = observe ~doc:dummy_doc (VCS.get_branch_pos (VCS.current_branch ())) in
2542 let parsing = Procq.freeze () in
2543 (* If execution has not been put in cache, we need to save the parsing state *)
2544 if (VCS.get_info id).state == EmptyState then VCS.set_parsing_state id parsing;
2545 parsing
2546 | VtLater -> VCS.set_parsing_state id head_parsing; head_parsing
2547 end
2548 in
2549 (* We save the parsing state on non-master branches *)
2550 List.iter (fun id ->
2551 if (VCS.get_info id).state == EmptyState then
2552 VCS.set_parsing_state id parsing_state) new_ids;
2553 Ok
2554
2555 | VtProofMode proof_mode ->
2556 let id = VCS.new_node ~id:newtip (Some proof_mode) () in
2557 VCS.commit id (mkTransCmd x [] false MainQueue);
2558 VCS.set_parsing_state id head_parsing;
2559 Backtrack.record (); Ok
2560
2561 end in
2562 let pr_rc rc = match rc with
2563 | Ok -> Pp.(seq [str "newtip ("; str (Stateid.to_string (VCS.cur_tip ())); str ")"])
2564 | _ -> Pp.(str "unfocus")
2565 in
2566 stm_pperr_endline (fun () -> str "processed with " ++ pr_rc rc ++ str " }}}");
2567 VCS.print ();
2568 rc
2569 with e ->
2570 let e = Exninfo.capture e in
2571 handle_failure e vcs
2572
2573 let get_ast ~doc id =
2574 match (VCS.visit id).step with
2575 | SCmd { cast = { expr } }
2576 | SFork (({ expr }, _, _, _), _)
2577 | SSideff ((ReplayCommand { expr }) , _)
2578 | SQed ({ qast = { expr } }, _) ->
2579 Some expr
2580 | SAlias _ | SSideff (CherryPickEnv, _) -> None
2581
2582 let stop_worker n = Slaves.cancel_worker n
2583
2584 let parse_sentence ~doc sid ~entry pa =
2585 let ps = Option.get @@ VCS.get_parsing_state sid in
2586 let proof_mode = VCS.get_proof_mode sid in
2587 Procq.unfreeze ps;
2588 Procq.Entry.parse (entry proof_mode) pa
2589
2590 (* You may need to know the len + indentation of previous command to compute
2591 * the indentation of the current one.
2592 * Eg. foo. bar.
2593 * Here bar is indented of the indentation of foo + its strlen (4) *)
2594 let ind_len_loc_of_id sid =
2595 if Stateid.equal sid Stateid.initial then None
2596 else match (VCS.visit sid).step with
2597 | SCmd { ctac = true; cast = { indentation; strlen; expr } } ->
2598 Some (indentation, strlen, expr.CAst.loc)
2599 | _ -> None
2600
2601 (* the indentation logic works like this: if the beginning of the
2602 command is different than the start we are in a new line, thus
2603 indentation follows from the starting position. Otherwise, we use
2604 the previous one plus the offset.
2605
2606 Note, this could maybe improved by handling more cases in
2607 compute_indentation. *)
2608
2609 let compute_indentation ?loc sid = Option.cata (fun loc ->
2610 let open Loc in
2611 (* The effective length is the length on the last line *)
2612 let len = loc.ep - loc.bp in
2613 let prev_indent = match ind_len_loc_of_id sid with
2614 | None -> 0
2615 | Some (i,l,p) -> i + l
2616 in
2617 (* Now if the line has not changed, the need to add the previous indent *)
2618 let eff_indent = loc.bp - loc.bol_pos in
2619 if loc.bol_pos = 0 then
2620 eff_indent + prev_indent, len
2621 else
2622 eff_indent, len
2623 ) (0, 0) loc
2624
2625 type add_focus = NewAddTip | Unfocus of Stateid.t
2626
2627 let add ~doc ~ontop ?newtip verb ast =
2628 !Hooks.document_add ast ontop;
2629 let loc = ast.CAst.loc in
2630 let cur_tip = VCS.cur_tip () in
2631 if not (Stateid.equal ontop cur_tip) then
2632 user_err ?loc
2633 (str "Stm.add called for a different state (" ++ str (Stateid.to_string ontop) ++
2634 str ") than the tip: " ++ str (Stateid.to_string cur_tip) ++ str "." ++ fnl () ++
2635 str "This is not supported yet, sorry.");
2636 let indentation, strlen = compute_indentation ?loc ontop in
2637 (* XXX: Classifiy vernac should be moved inside process transaction *)
2638 let clas = Vernac_classifier.classify_vernac ast in
2639 let aast = { verbose = verb; indentation; strlen; expr = ast } in
2640 match process_transaction ~doc ?newtip aast clas with
2641 | Ok -> doc, VCS.cur_tip (), NewAddTip
2642 | Unfocus qed_id -> doc, qed_id, Unfocus (VCS.cur_tip ())
2643
2644 type focus = {
2645 start : Stateid.t;
2646 stop : Stateid.t;
2647 tip : Stateid.t
2648 }
2649
2650 type edit_focus = NewTip | Focus of focus
2651
2652 let query ~doc ~at ~route s =
2653 State.purify (fun s ->
2654 if Stateid.equal at Stateid.dummy then ignore(finish ~doc:dummy_doc)
2655 else Reach.known_state ~doc ~cache:true at;
2656 let rec loop () =
2657 match parse_sentence ~doc at ~entry:Pvernac.main_entry s with
2658 | None -> ()
2659 | Some ast ->
2660 let loc = ast.CAst.loc in
2661 let indentation, strlen = compute_indentation ?loc at in
2662 let st = State.get_cached at in
2663 let aast = {
2664 verbose = true; indentation; strlen;
2665 expr = ast } in
2666 ignore(stm_vernac_interp ~route at st aast);
2667 loop ()
2668 in
2669 loop ()
2670 )
2671 s
2672
2673 let edit_at ~doc id =
2674 assert (VCS.is_interactive());
2675 !Hooks.document_edit id;
2676 if Stateid.equal id Stateid.dummy then anomaly(str"edit_at dummy.") else
2677 let vcs = VCS.backup () in
2678 let on_cur_branch id =
2679 let rec aux cur =
2680 match VCS.visit cur with
2681 | { step = SFork _ } -> false
2682 | { next } -> if id = cur then true else aux next in
2683 aux (VCS.get_branch_pos (VCS.current_branch ())) in
2684 let rec is_pure_aux id =
2685 let view = VCS.visit id in
2686 match view.step with
2687 | SCmd _ -> is_pure_aux view.next
2688 | SFork _ -> true
2689 | _ -> false in
2690 let is_pure id =
2691 match (VCS.visit id).step with
2692 | SQed (_,last_step) -> is_pure_aux last_step
2693 | _ -> assert false
2694 in
2695 let is_ancestor_of_cur_branch id =
2696 Stateid.Set.mem id
2697 (VCS.reachable (VCS.get_branch_pos (VCS.current_branch ()))) in
2698 let has_failed qed_id =
2699 match VCS.visit qed_id with
2700 | { step = SQed ({ fproof = Some (Some fp,_) }, _) } -> Future.is_exn fp
2701 | _ -> false in
2702 let rec master_for_br root tip =
2703 if Stateid.equal tip Stateid.initial then tip else
2704 match VCS.visit tip with
2705 | { step = (SFork _ | SQed _) } -> tip
2706 | { step = SSideff (ReplayCommand _,id) } -> id
2707 | { step = SSideff _ } -> tip
2708 | { next } -> master_for_br root next in
2709 let reopen_branch start at_id qed_id tip old_branch =
2710 let master_id, cancel_switch, keep =
2711 (* Hum, this should be the real start_id in the cluster and not next *)
2712 match VCS.visit qed_id with
2713 | { step = SQed ({ fproof = Some (_,cs); keep },_) } -> start, cs, keep
2714 | _ -> anomaly (str "ProofTask not ending with Qed.") in
2715 VCS.branch ~root:master_id ~pos:id
2716 VCS.edit_branch (Edit (qed_id, master_id, keep, old_branch));
2717 VCS.delete_boxes_of id;
2718 cancel_switch := true;
2719 Reach.known_state ~doc ~cache:(VCS.is_interactive ()) id;
2720 VCS.checkout_shallowest_proof_branch ();
2721 Focus { stop = qed_id; start = master_id; tip } in
2722 let no_edit = function
2723 | Edit (_,_,_,_) -> Proof 1
2724 | x -> x in
2725 let backto id bn =
2726 List.iter VCS.delete_branch (VCS.branches ());
2727 let ancestors = VCS.reachable id in
2728 let { mine = brname, brinfo; others } = Backtrack.branches_of id in
2729 List.iter (fun (name,{ VCS.kind = k; root; pos }) ->
2730 if not(VCS.Branch.equal name VCS.Branch.master) &&
2731 Stateid.Set.mem root ancestors then
2732 VCS.branch ~root ~pos name k)
2733 others;
2734 VCS.reset_branch VCS.Branch.master (master_for_br brinfo.VCS.root id);
2735 VCS.branch ~root:brinfo.VCS.root ~pos:brinfo.VCS.pos
2736 (Option.default brname bn)
2737 (no_edit brinfo.VCS.kind);
2738 VCS.delete_boxes_of id;
2739 VCS.gc ();
2740 VCS.print ();
2741 Reach.known_state ~doc ~cache:(VCS.is_interactive ()) id;
2742 VCS.checkout_shallowest_proof_branch ();
2743 NewTip in
2744 try
2745 let rc =
2746 let focused = List.exists ((=) VCS.edit_branch) (VCS.branches ()) in
2747 let branch_info =
2748 match snd (VCS.get_info id).vcs_backup with
2749 | Some{ mine = bn, { VCS.kind = Proof _ }} -> Some bn
2750 | Some{ mine = _, { VCS.kind = Edit(_,_,_,bn) }} -> Some bn
2751 | _ -> None in
2752 match focused, VCS.proof_task_box_of id, branch_info with
2753 | _, Some _, None -> assert false
2754 | false, Some { qed = qed_id ; lemma = start }, Some bn ->
2755 let tip = VCS.cur_tip () in
2756 if has_failed qed_id && is_pure qed_id && not (cur_opt()).async_proofs_never_reopen_branch
2757 then reopen_branch start id qed_id tip bn
2758 else backto id (Some bn)
2759 | true, Some { qed = qed_id }, Some bn ->
2760 if on_cur_branch id then begin
2761 assert false
2762 end else if is_ancestor_of_cur_branch id then begin
2763 backto id (Some bn)
2764 end else begin
2765 anomaly(str"Cannot leave an Edit branch open.")
2766 end
2767 | true, None, _ ->
2768 if on_cur_branch id then begin
2769 VCS.reset_branch (VCS.current_branch ()) id;
2770 Reach.known_state ~doc ~cache:(VCS.is_interactive ()) id;
2771 VCS.checkout_shallowest_proof_branch ();
2772 NewTip
2773 end else if is_ancestor_of_cur_branch id then begin
2774 backto id None
2775 end else begin
2776 anomaly(str"Cannot leave an Edit branch open.")
2777 end
2778 | false, None, Some bn -> backto id (Some bn)
2779 | false, None, None -> backto id None
2780 in
2781 VCS.print ();
2782 doc, rc
2783 with
2784 | Vcs_aux.Expired -> user_err Pp.(str "Unknown state " ++ Stateid.print id ++ str".")
2785 | e ->
2786 let (e, info) = Exninfo.capture e in
2787 match Stateid.get info with
2788 | None ->
2789 VCS.print ();
2790 anomaly (str ("edit_at "^Stateid.to_string id^": ") ++
2791 CErrors.print_no_report e ++ str ".")
2792 | Some (_, id) ->
2793 stm_prerr_endline (fun () -> "Failed at state " ^ Stateid.to_string id);
2794 VCS.restore vcs;
2795 VCS.print ();
2796 Exninfo.iraise (e, info)
2797
2798 let get_current_state ~doc = VCS.cur_tip ()
2799 let get_ldir ~doc = VCS.get_ldir ()
2800
2801 let get_doc did = dummy_doc
2802
2803 (*********************** TTY API (PG, coqtop, coqc) ***************************)
2804 (******************************************************************************)
2805
2806 let current_proof_depth ~doc =
2807 let head = VCS.current_branch () in
2808 match VCS.get_branch head with
2809 | { VCS.kind = Master } -> 0
2810 | { VCS.pos = cur; VCS.kind = (Proof _ | Edit _); VCS.root = root } ->
2811 let rec distance root =
2812 if Stateid.equal cur root then 0
2813 else 1 + distance (VCS.visit cur).next in
2814 distance cur
2815
2816 let unmangle n =
2817 let n = VCS.Branch.to_string n in
2818 let idx = String.index n '_' + 1 in
2819 Names.Id.of_string (String.sub n idx (String.length n - idx))
2820
2821 let proofname b = match VCS.get_branch b with
2822 | { VCS.kind = (Proof _| Edit _) } -> Some b
2823 | _ -> None
2824
2825 let get_all_proof_names ~doc =
2826 List.map unmangle (CList.map_filter proofname (VCS.branches ()))
2827
2828 (* Export hooks *)
2829 let state_computed_hook v = Hooks.state_computed := v
2830 let state_ready_hook v = Hooks.state_ready := v
2831 let forward_feedback_hook v = Hooks.forward_feedback := v
2832 let unreachable_state_hook v = Hooks.unreachable_state := v
2833 let document_add_hook v = Hooks.document_add := v
2834 let document_edit_hook v = Hooks.document_edit := v
2835 let sentence_exec_hook v = Hooks.sentence_exec := v
2836
2837 type document = VCS.vcs
2838 let backup () = VCS.backup ()
2839 let restore d = VCS.restore d
2840
2841
2842 (* vim:set foldmethod=marker: *)