Debian Codegraph @

ide/rocqide/rocqDriver.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 open Ideutils
12 open Preferences
13
14 let ideslave_rocqtop_flags = ref None
15
16 (** * Version *)
17
18 let get_version () =
19 try
20 (* the following makes sense only when running with local layout *)
21 let rocqroot = Filename.concat
22 (Filename.dirname Sys.executable_name)
23 Filename.parent_dir_name
24 in
25 let ch = open_in (Filename.concat rocqroot "revision") in
26 let ver = input_line ch in
27 let rev = input_line ch in
28 close_in ch;
29 Printf.sprintf "%s (%s)" ver rev
30 with _ -> Coq_config.version
31
32 let short_version () =
33 Printf.sprintf "The Rocq Prover, version %s\n" (get_version ())
34
35 let version () =
36 Printf.sprintf
37 "The Rocq Prover, version %s\
38 \nArchitecture %s running %s operating system\
39 \nGtk version is %s\
40 \nThis is %s \n"
41 (get_version ())
42 Coq_config.arch Sys.os_type
43 (let x,y,z = GMain.Main.version in Printf.sprintf "%d.%d.%d" x y z)
44 (Filename.basename Sys.executable_name)
45
46 (** * Initial checks by launching test rocqtop processes *)
47
48 let rec read_all_lines in_chan =
49 try
50 let arg = input_line in_chan in
51 let len = String.length arg in
52 let arg =
53 if len > 0 && arg.[len - 1] = '\r' then
54 String.sub arg 0 (len - 1)
55 else arg
56 in
57 arg::(read_all_lines in_chan)
58 with End_of_file -> []
59
60 let rocq_error_popup ~code ~msg data =
61 let callback _ = exit code in
62 let popup = GWindow.dialog () in
63 let button = GButton.button ~stock:`OK ~packing:popup#action_area#add () in
64 let _ = GMisc.label ~text:msg ~packing:popup#vbox#add () in
65 let container = GPack.notebook ~packing:popup#vbox#add () in
66 let iter (label, data) =
67 let scroll = GBin.scrolled_window ~hpolicy:`NEVER ~vpolicy:`AUTOMATIC ~height:500 () in
68 let label = GMisc.label ~text:label () in
69 let text = GText.view ~editable:false ~packing:scroll#add_with_viewport () in
70 let () = text#buffer#set_text data in
71 ignore (container#append_page ~tab_label:label#coerce scroll#coerce)
72 in
73 let () = List.iter iter data in
74 let _ = popup#connect#destroy ~callback in
75 let _ = button#connect#clicked ~callback in
76 let _ = popup#run () in
77 callback ()
78
79 let connection_error cmd lines exn =
80 rocq_error_popup ~code:1 ~msg:"Connection with coqtop failed!"
81 [
82 "Command", cmd;
83 "Answer", (String.concat "\n" lines);
84 "Exception", Printexc.to_string exn
85 ]
86
87 let display_rocqtop_answer cmd lines =
88 rocq_error_popup ~code:0 ~msg:"The coqtop process has exited."
89 [
90 "Command", cmd;
91 "Answer", String.concat "\n" lines;
92 ]
93
94 let rec filter_rocq_opts args =
95 let argstr = String.concat " " (List.map Filename.quote args) in
96 let cmd = Filename.quote (rocqtop_path ()) ^" -q -nois -batch " ^ argstr in
97 let cmd = requote cmd in
98 let filtered_args = ref [] in
99 let errlines = ref [] in
100 try
101 let oc,ic,ec = Unix.open_process_full cmd (Unix.environment ()) in
102 filtered_args := read_all_lines oc;
103 errlines := read_all_lines ec;
104 match Unix.close_process_full (oc,ic,ec) with
105 | Unix.WEXITED 0 -> !filtered_args
106 | Unix.WEXITED 127 -> asks_for_rocqtop args
107 | _ -> display_rocqtop_answer cmd (!filtered_args @ !errlines)
108 with Sys_error _ -> asks_for_rocqtop args
109 | e -> connection_error cmd (!filtered_args @ !errlines) e
110
111 and asks_for_rocqtop args =
112 let pb_mes = GWindow.message_dialog
113 ~message:"Failed to load coqidetop. Reset the preference to default?"
114 ~message_type:`QUESTION ~buttons:GWindow.Buttons.yes_no () in
115 match pb_mes#run () with
116 | `YES ->
117 let () = cmd_rocqtop#set None in
118 let () = custom_rocqtop := None in
119 let () = pb_mes#destroy () in
120 filter_rocq_opts args
121 | `DELETE_EVENT | `NO ->
122 let file = select_file_for_open
123 ~title:"coqidetop to execute (edit your preference then)"
124 ~filter:false
125 ~filename:(rocqtop_path ()) () in
126 match file with
127 | [file] ->
128 let () = custom_rocqtop := Some file in
129 filter_rocq_opts args
130 | _ -> exit 0
131
132 exception WrongExitStatus of string
133
134 let print_status = function
135 | Unix.WEXITED n -> "WEXITED "^string_of_int n
136 | Unix.WSIGNALED n -> "WSIGNALED "^string_of_int n
137 | Unix.WSTOPPED n -> "WSTOPPED "^string_of_int n
138
139 let check_connection args =
140 let lines = ref [] in
141 let argstr = String.concat " " (List.map Filename.quote args) in
142 let cmd = Filename.quote (rocqtop_path ()) ^ " -batch " ^ argstr in
143 let cmd = requote cmd in
144 try
145 let oc,ic,ec = Unix.open_process_full cmd (Unix.environment ()) in
146 lines := read_all_lines oc @ read_all_lines ec;
147 match Unix.close_process_full (oc,ic,ec) with
148 | Unix.WEXITED 0 -> () (* rocqtop seems ok *)
149 | st -> raise (WrongExitStatus (print_status st))
150 with e -> connection_error cmd !lines e
151
152 (** Useful stuff *)
153
154 let ignore_error f arg =
155 try ignore (f arg) with _ -> ()
156
157 (** An abstract copy of unit.
158 This will help ensuring that we do not forget to finally call
159 continuations when building tasks in other modules. *)
160
161 type void = Void
162
163 (** ccb : existential type for a (call + callback) type.
164
165 Reference: http://alan.petitepomme.net/cwn/2004.01.13.html
166 To rewrite someday with GADT. *)
167
168 type 'a poly_ccb = 'a Xmlprotocol.call * ('a Interface.value -> void)
169 type 't scoped_ccb = { bind_ccb : 'a. 'a poly_ccb -> 't }
170 type ccb = { open_ccb : 't. 't scoped_ccb -> 't }
171
172 let mk_ccb poly = { open_ccb = fun scope -> scope.bind_ccb poly }
173 let with_ccb ccb e = ccb.open_ccb e
174
175 (* overridden on Windows; see file rocqide_WIN32.c.in *)
176 let interrupter = ref (fun pid -> Unix.kill pid Sys.sigint)
177
178 (* todo: does not work on windows (sigusr1 not supported) *)
179 let breaker = ref (fun pid -> Unix.kill pid Sys.sigusr1)
180
181 (** * The structure describing a rocqtop sub-process *)
182
183 module GlibMainLoop = struct
184 type async_chan = Glib.Io.channel
185 type watch_id = Glib.Io.id
186 type condition = Glib.Io.condition
187 let add_watch ~callback chan =
188 Glib.Io.add_watch ~cond:[`ERR; `HUP; `IN; `NVAL; `PRI] ~callback chan
189 let remove_watch x = try Glib.Io.remove x with Glib.GError _ -> ()
190 let read_all = Ideutils.io_read_all
191 let async_chan_of_file_or_socket fd = Glib.Io.channel_of_descr fd
192 end
193
194 module RocqTop = Spawn.Async(GlibMainLoop)
195
196 type handle = {
197 proc : RocqTop.process;
198 xml_oc : Xml_printer.t;
199 mutable alive : bool;
200 mutable waiting_for : ccb option; (* last non-debug call + callback *)
201 mutable db_waiting_for : ccb option; (* last debug call + callback *)
202 }
203
204 type status = New | Ready | Busy | Closed
205
206 type 'a task = handle -> ('a -> void) -> void
207
208 type reset_kind = Planned | Unexpected
209
210 type rocqtop = {
211 (* non quoted command-line arguments of rocqtop *)
212 mutable sup_args : string list;
213 (* called whenever rocqtop dies *)
214 mutable reset_handler : unit task;
215 (* called whenever rocqtop sends a feedback message *)
216 mutable feedback_handler : Feedback.feedback -> unit;
217 (* called when the Ltac debugger sends an input prompt message *)
218 mutable debug_prompt_handler : tag:string -> Pp.t -> unit;
219 (* actual rocqtop process and its status *)
220 mutable handle : handle;
221 mutable status : status;
222 mutable stopped_in_debugger : bool;
223 (* i.e., RocqIDE has received a prompt message *)
224 mutable do_when_ready : (unit -> unit) Queue.t;
225 (* for debug msgs only; functions are called when rocqtop is Ready *)
226 mutable basename : string;
227 mutable set_script_editable : bool -> unit;
228 mutable restore_bpts : unit -> unit
229 }
230
231 let return (x : 'a) : 'a task =
232 (); fun _ k -> k x
233
234 let bind (m : 'a task) (f : 'a -> 'b task) : 'b task =
235 (); fun h k -> m h (fun x -> f x h k)
236
237 let seq (m : unit task) (n : 'a task) : 'a task =
238 (); fun h k -> m h (fun () -> n h k)
239
240 let lift (f : unit -> 'a) : 'a task =
241 (); fun _ k -> k (f ())
242
243 (** * Starting / signaling / ending a real rocqtop sub-process *)
244
245 (** We simulate a Unix.open_process that also returns the pid of
246 the created process. Note: this uses Unix.create_process, which
247 doesn't call bin/sh, so args shouldn't be quoted. The process
248 cannot be terminated by a Unix.close_process, but rather by a
249 kill of the pid.
250
251 >--ide2top_w--[pipe]--ide2top_r-->
252 rocqide rocqtop
253 <--top2ide_r--[pipe]--top2ide_w--<
254
255 Note: we use Unix.stderr in Unix.create_process to get debug
256 messages from the rocqtop's Ide_slave loop.
257
258 NB: it's important to close rocqide's descriptors (ide2top_w and top2ide_r)
259 in rocqtop. We do this indirectly via [Unix.set_close_on_exec].
260 This way, rocqide has the only remaining copies of these descriptors,
261 and closing them later will have visible effects in rocqtop. Cf man 7 pipe :
262
263 - If all file descriptors referring to the write end of a pipe have been
264 closed, then an attempt to read(2) from the pipe will see end-of-file
265 (read(2) will return 0).
266 - If all file descriptors referring to the read end of a pipe have been
267 closed, then a write(2) will cause a SIGPIPE signal to be generated for
268 the calling process. If the calling process is ignoring this signal,
269 then write(2) fails with the error EPIPE.
270
271 Symmetrically, rocqtop's descriptors (ide2top_r and top2ide_w) should be
272 closed in rocqide.
273 *)
274
275 exception TubeError of string
276 exception AnswerWithoutRequest of string
277
278 let rec check_errors = function
279 | [] -> ()
280 | (`IN | `PRI) :: conds -> check_errors conds
281 | `ERR :: _ -> raise (TubeError "ERR")
282 | `HUP :: _ -> raise (TubeError "HUP")
283 | `NVAL :: _ -> raise (TubeError "NVAL")
284 | `OUT :: _ -> raise (TubeError "OUT")
285
286 let handle_feedback feedback_processor xml =
287 let feedback = Xmlprotocol.to_feedback xml in
288 feedback_processor feedback
289
290 let handle_ltac_debug ltac_debug_processor xml =
291 let tag, msg = Xmlprotocol.to_ltac_debug_answer xml in
292 ltac_debug_processor ~tag msg
293
294 let handle_final_answer handle xml =
295 let () = Minilib.log "Handling rocqtop answer" in
296 let ccb = match handle.db_waiting_for, handle.waiting_for with
297 | None, None -> raise (AnswerWithoutRequest (Xml_printer.to_string_fmt xml))
298 | Some c, _ -> handle.db_waiting_for <- None; c
299 | None, Some c -> handle.waiting_for <- None; c in
300 with_ccb ccb { bind_ccb = fun (c, f) -> f (Xmlprotocol.to_answer c xml) }
301
302 type input_state = {
303 mutable fragment : string;
304 mutable lexerror : int option;
305 }
306
307 let unsafe_handle_input handle (feedback_processor, ltac_debug_processor) state conds ~read_all =
308 check_errors conds;
309 let s = read_all () in
310 if String.length s = 0 then raise (TubeError "EMPTY");
311 let s = state.fragment ^ s in
312 state.fragment <- s;
313 let lex = Lexing.from_string s in
314 let p = Xml_parser.make (Xml_parser.SLexbuf lex) in
315 let rec loop () =
316 let xml = Xml_parser.parse ~canonicalize:false p in
317 let l_end = Lexing.lexeme_end lex in
318 state.fragment <- String.sub s l_end (String.length s - l_end);
319 state.lexerror <- None;
320 match Xmlprotocol.msg_kind xml with
321 | Xmlprotocol.Feedback ->
322 handle_feedback feedback_processor xml;
323 loop ()
324 | Xmlprotocol.LtacDebugInfo ->
325 handle_ltac_debug ltac_debug_processor xml;
326 loop ()
327 | Xmlprotocol.Other ->
328 ignore (handle_final_answer handle xml); (* request completed *)
329 if handle.waiting_for <> None then (* i.e., just finished a db request *)
330 loop ()
331 in
332 try loop ()
333 with Xml_parser.Error _ as e ->
334 (* Parsing error at the end of s : we have only received a part of
335 an xml answer. We store the current fragment for later *)
336 let l_end = Lexing.lexeme_end lex in
337 (* Heuristic hack not to reimplement the lexer: if ever the lexer dies
338 twice at the same place, then this is a non-recoverable error *)
339 if state.lexerror = Some l_end then raise e;
340 state.lexerror <- Some l_end
341
342 let print_exception = function
343 | Xml_parser.Error e -> Xml_parser.error e
344 | Serialize.Marshal_error(expected,actual) ->
345 "Protocol violation. Expected: " ^ expected ^ " Actual: "
346 ^ Xml_printer.to_string actual
347 | e -> Printexc.to_string e
348
349 let input_watch handle respawner processors =
350 let state = { fragment = ""; lexerror = None; } in
351 (fun conds ~read_all ->
352 let h = handle () in
353 if not h.alive then false
354 else
355 try unsafe_handle_input h processors state conds ~read_all; true
356 with e ->
357 Minilib.log ("Rocqtop reader failed, resetting: "^print_exception e);
358 respawner ();
359 false)
360
361 let bind_self_as f =
362 let me = ref None in
363 let get_me () = Option.get !me in
364 me := Some(f get_me);
365 Option.get !me
366
367 (** This launches a fresh handle from its command line arguments. *)
368 let spawn_handle args respawner processors =
369 let prog = rocqtop_path () in
370 let async_default =
371 (* disable async processing by default in Windows *)
372 if List.mem Sys.os_type ["Win32"; "Cygwin"] then
373 "off"
374 else
375 "on"
376 in
377 let args = Array.of_list ("--xml_format=Ppcmds" :: "-async-proofs" :: async_default :: args) in
378 let env =
379 match !ideslave_rocqtop_flags with
380 | None -> None
381 | Some s ->
382 let open Str in
383 let open Array in
384 let opts = split_delim (regexp ",") s in
385 begin try
386 let erex = regexp "^extra-env=" in
387 let echunk = List.find (fun s -> string_match erex s 0) opts in
388 Some (append
389 (of_list (split_delim (regexp ";") (replace_first erex "" echunk)))
390 (Unix.environment ()))
391 with Not_found -> None end in
392 bind_self_as (fun handle ->
393 let proc, oc =
394 RocqTop.spawn ?env prog args (input_watch handle respawner processors) in
395 {
396 proc;
397 xml_oc = Xml_printer.make (Xml_printer.TChannel oc);
398 alive = true;
399 waiting_for = None;
400 db_waiting_for = None;
401 })
402
403 (** This clears any potentially remaining open garbage. *)
404 let clear_handle h =
405 if h.alive then begin
406 (* invalidate the old handle *)
407 RocqTop.kill h.proc;
408 ignore(RocqTop.wait h.proc);
409 h.alive <- false;
410 h.db_waiting_for <- None;
411 end
412
413 let pstatus = function
414 | Closed -> "Closed"
415 | Busy -> "Busy"
416 | Ready -> "Ready"
417 | New -> "New"
418
419 let can_send_db_msg rocqtop =
420 rocqtop.handle.db_waiting_for = None &&
421 match rocqtop.status with
422 | Busy -> rocqtop.stopped_in_debugger
423 | Ready -> true
424 | _ -> false
425
426 let add_do_when_ready rocqtop hook =
427 let q = rocqtop.do_when_ready in
428 Queue.add hook q;
429 if not (Queue.is_empty q) && can_send_db_msg rocqtop then
430 let f = Queue.pop q in f ()
431
432 let mkready rocqtop db =
433 fun () ->
434 if not db then begin
435 rocqtop.status <- Ready;
436 rocqtop.set_script_editable true
437 end;
438 if rocqtop.status = Ready || (db && can_send_db_msg rocqtop) then begin
439 let q = rocqtop.do_when_ready in
440 if not (Queue.is_empty q) then
441 let f = Queue.pop q in f ()
442 end;
443 Void
444
445 let save_all = ref (fun () -> assert false)
446
447 let rec respawn_rocqtop ?(why=Unexpected) rocqtop =
448 let () = match why with
449 | Unexpected ->
450 let title = "Warning" in
451 let icon = (warn_image ())#coerce in
452 let buttons = ["Reset"; "Save all and quit"; "Quit without saving"] in
453 let ans = GToolbox.question_box ~title ~buttons ~icon (rocqtop.basename ^ ": coqidetop died.") in
454 if ans = 2 then (!save_all (); GtkMain.Main.quit ())
455 else if ans = 3 then GtkMain.Main.quit ()
456 | Planned -> ()
457 in
458 clear_handle rocqtop.handle;
459 Queue.clear rocqtop.do_when_ready;
460 ignore_error (fun () ->
461 let processors = (rocqtop.feedback_handler, rocqtop.debug_prompt_handler) in
462 rocqtop.handle <-
463 spawn_handle
464 rocqtop.sup_args
465 (fun () -> respawn_rocqtop rocqtop)
466 processors) ();
467 (* Normally, the handle is now a fresh one.
468 If not, there isn't much we can do ... *)
469 assert (rocqtop.handle.alive = true);
470 rocqtop.status <- New;
471 rocqtop.set_script_editable true;
472 ignore (rocqtop.reset_handler rocqtop.handle (mkready rocqtop false));
473 rocqtop.restore_bpts () (* queue call to restore previous breakpoints *)
474
475 let spawn_rocqtop basename sup_args =
476 bind_self_as (fun this ->
477 let processors =
478 (fun msg -> (this ()).feedback_handler msg)
479 , (fun ~tag msg -> (this ()).debug_prompt_handler ~tag msg)
480 in
481 {
482 handle = spawn_handle sup_args
483 (fun () -> respawn_rocqtop (this ()))
484 processors;
485 sup_args;
486 reset_handler = (fun _ k -> k ());
487 feedback_handler = (fun _ -> ());
488 debug_prompt_handler = (fun ~tag:_ _ -> ());
489 status = New;
490 stopped_in_debugger = false;
491 do_when_ready = Queue.create ();
492 basename;
493 set_script_editable = (fun v -> failwith "set_script_editable");
494 restore_bpts = (fun _ -> failwith "restore_bpts")
495 })
496
497 let set_restore_bpts rocqtop f = rocqtop.restore_bpts <- f
498
499 let set_reset_handler rocqtop hook = rocqtop.reset_handler <- hook
500
501 let set_feedback_handler rocqtop hook = rocqtop.feedback_handler <- hook
502 let set_debug_prompt_handler rocqtop hook = rocqtop.debug_prompt_handler <- hook
503
504 let setup_script_editable rocqtop f = rocqtop.set_script_editable <- f
505
506 let is_computing rocqtop = (rocqtop.status = Busy)
507
508 let is_stopped_in_debugger rocqtop = rocqtop.stopped_in_debugger
509
510 let is_ready_or_stopped_in_debugger rocqtop =
511 rocqtop.status = Ready || (is_stopped_in_debugger rocqtop)
512
513 let set_stopped_in_debugger rocqtop v =
514 rocqtop.stopped_in_debugger <- v
515
516 (* For closing a rocqtop, we don't try to send it a Quit call anymore,
517 but rather close its channels:
518 - a listening rocqtop will handle this just as a Quit call
519 - a busy rocqtop will anyway have to be killed *)
520
521 let close_rocqtop rocqtop =
522 rocqtop.status <- Closed;
523 clear_handle rocqtop.handle
524
525 let reset_rocqtop rocqtop = respawn_rocqtop ~why:Planned rocqtop
526
527 let get_arguments rocqtop = rocqtop.sup_args
528
529 let set_arguments rocqtop args =
530 rocqtop.sup_args <- args;
531 reset_rocqtop rocqtop
532
533 let process_task ?(db=false) rocqtop task =
534 (* todo: queuing is probably better than assert. *)
535 if not (rocqtop.status = Ready || rocqtop.status = New || (db && rocqtop.status = Busy)) then
536 Printf.printf "Assert failure in process_task rocqtop.status = %s db = %b\n" (pstatus rocqtop.status) db;
537 assert (rocqtop.status = Ready || rocqtop.status = New || (db && rocqtop.status = Busy));
538 if not db then begin
539 rocqtop.status <- Busy;
540 rocqtop.set_script_editable false
541 end;
542 try ignore (task rocqtop.handle (mkready rocqtop db))
543 with e ->
544 Minilib.log ("Rocqtop writer failed, resetting: " ^ Printexc.to_string e);
545 if rocqtop.status <> Closed then respawn_rocqtop rocqtop
546
547 (* todo: logic for functions such as "forward one" should not rely on try_grab
548 to discard the request; a small amount of queuing would make this a trivial
549 routine, perhaps not even needed. The "abort" should go away. *)
550 let try_grab ?(db=false) rocqtop task abort =
551 match rocqtop.status with
552 | _ when db && rocqtop.handle.db_waiting_for <> None -> (abort (); false)
553 | Closed -> abort (); false
554 | Busy when db ->
555 if (*rocqtop.stopped_in_debugger &&*) rocqtop.handle.db_waiting_for = None then
556 (process_task ~db rocqtop task; true)
557 else
558 (abort (); false)
559 | Busy | New -> abort (); false
560 | Ready -> process_task ~db rocqtop task; true
561
562 let init_rocqtop rocqtop task =
563 assert (rocqtop.status = New);
564 process_task rocqtop task
565
566 (** * Calls to rocqtop *)
567
568 (** Cf [Ide_intf] for more details *)
569
570 type 'a query = 'a Interface.value task
571
572 (* todo: it's too easy to fail the asserts here when changing the code.
573 We should look at making handle.waiting_for and handle.db_waiting_for into
574 queues, perhaps have a queue for the call to Xml_printer.print with flow
575 control. Then rocqtop.do_when_ready would not be needed and other
576 logic such as mkready and rocqtop initialization might be simplified. *)
577
578 let eval_call ?(db=false) call handle k =
579 (* Send messages to rocqtop and prepare the decoding of the answer *)
580 let in_db = if db then "db " else "" in
581 Minilib.log ("Start " ^ in_db ^ "eval_call " ^ Xmlprotocol.pr_call call);
582 if db then begin
583 assert (handle.alive && handle.db_waiting_for = None);
584 handle.db_waiting_for <- Some (mk_ccb (call,k))
585 end else begin
586 assert (handle.alive && handle.waiting_for = None);
587 handle.waiting_for <- Some (mk_ccb (call,k))
588 end;
589 Xml_printer.print handle.xml_oc (Xmlprotocol.of_call call);
590 Minilib.log ("End " ^ in_db ^ "eval_call");
591 Void
592
593 let add x = eval_call (Xmlprotocol.add x)
594 let edit_at i = eval_call (Xmlprotocol.edit_at i)
595 let query x = eval_call (Xmlprotocol.query x)
596 let mkcases s = eval_call (Xmlprotocol.mkcases s)
597 let status force = eval_call (Xmlprotocol.status force)
598 let hints x = eval_call (Xmlprotocol.hints x)
599 let search flags = eval_call (Xmlprotocol.search flags)
600 let init x = eval_call (Xmlprotocol.init x)
601 let stop_worker x = eval_call (Xmlprotocol.stop_worker x)
602 let proof_diff x = eval_call (Xmlprotocol.proof_diff x)
603 let db_cmd x = eval_call ~db:true (Xmlprotocol.db_cmd x)
604 let db_upd_bpts x = eval_call ~db:true (Xmlprotocol.db_upd_bpts x)
605 let db_continue x = eval_call ~db:true (Xmlprotocol.db_continue x)
606 let db_stack x = eval_call ~db:true (Xmlprotocol.db_stack x)
607 let db_vars x = eval_call ~db:true (Xmlprotocol.db_vars x)
608 let db_configd x = eval_call ~db:true (Xmlprotocol.db_configd x)
609
610 let interrupt_rocqtop rocqtop workers =
611 if rocqtop.status = Busy then
612 try !interrupter (RocqTop.unixpid rocqtop.handle.proc)
613 with _ -> Minilib.log "Error while sending Ctrl-C"
614 else
615 let rec aux = function
616 | [] -> Void
617 | w :: ws -> stop_worker w rocqtop.handle (fun _ -> aux ws)
618 in
619 let Void = aux workers in ()
620
621 let send_break rocqtop =
622 try
623 !breaker (RocqTop.unixpid rocqtop.handle.proc)
624 with _ -> Minilib.log "Error while sending Break"
625
626 module PrintOpt =
627 struct
628 type _ t =
629 | BoolOpt : string list -> bool t
630 | StringOpt : string list -> string t
631
632 let opt_name (type a) : a t -> string list = function
633 | BoolOpt l -> l
634 | StringOpt l -> l
635
636 let opt_data (type a) (key : a t) (v : a) = match key with
637 | BoolOpt l -> Interface.BoolValue v
638 | StringOpt l -> Interface.StringValue v
639
640 (* Boolean options *)
641
642 let implicit = BoolOpt ["Printing"; "Implicit"]
643 let coercions = BoolOpt ["Printing"; "Coercions"]
644 let nested_matching = BoolOpt ["Printing"; "Matching"]
645 let notations = BoolOpt ["Printing"; "Notations"]
646 let parentheses = BoolOpt ["Printing"; "Parentheses"]
647 let all_basic = BoolOpt ["Printing"; "All"]
648 let existential = BoolOpt ["Printing"; "Existential"; "Instances"]
649 let universes = BoolOpt ["Printing"; "Universes"]
650 let unfocused = BoolOpt ["Printing"; "Unfocused"]
651 let goal_names = BoolOpt ["Printing"; "Goal"; "Names"]
652 let record = BoolOpt ["Printing"; "Records"]
653 let synth = BoolOpt ["Printing"; "Synth"]
654 let diff = StringOpt ["Diffs"]
655
656 type 'a descr = { opts : 'a t list; init : 'a; label : string }
657
658 let bool_items = [
659 { opts = [implicit]; init = false; label = "Display _implicit arguments" };
660 { opts = [coercions]; init = false; label = "Display _coercions" };
661 { opts = [nested_matching]; init = true;
662 label = "Display nested _matching expressions" };
663 { opts = [notations]; init = true; label = "Display _notations" };
664 { opts = [parentheses]; init = false; label = "Display _parentheses" };
665 { opts = [all_basic]; init = false;
666 label = "Display _all basic low-level contents" };
667 { opts = [existential]; init = false;
668 label = "Display _existential variable instances" };
669 { opts = [universes]; init = false; label = "Display _universe levels" };
670 { opts = [all_basic;existential;universes]; init = false;
671 label = "Display all _low-level contents" };
672 { opts = [unfocused]; init = false; label = "Display un_focused goals" };
673 { opts = [goal_names]; init = false; label = "Display _goal names" };
674 { opts = [record]; init = true; label = "Use _record syntax" };
675 { opts = [synth]; init = true; label = "Hide _synthesizable types" }
676 ]
677
678 let diff_item = { opts = [diff]; init = "off"; label = "Display _proof diffs" }
679
680 (** The current status of the boolean options *)
681
682 let current_state = Hashtbl.create 11
683
684 let set (type a) (opt : a t) (v : a) =
685 Hashtbl.replace current_state (opt_name opt) (opt_data opt v)
686
687 let get (type a) (opt : a t) =
688 Hashtbl.find current_state (opt_name opt)
689
690 let reset () =
691 let init_descr d = List.iter (fun o -> set o d.init) d.opts in
692 List.iter init_descr bool_items;
693 List.iter (fun o -> set o diff_item.init) diff_item.opts
694
695 let _ = reset ()
696
697 let printing_unfocused () =
698 let BoolOpt unfocused = unfocused in
699 match Hashtbl.find current_state unfocused with
700 | Interface.BoolValue b -> b
701 | _ -> assert false
702
703 (** Transmitting options to rocqtop *)
704
705 (* todo: if Rocq hasn't processed any statements since the last enforce,
706 it's unnecessary to send another. In particular, "goals" and "evars"
707 below are generally called one after the other. *)
708 let enforce h k =
709 let mkopt o v acc = (o, v) :: acc in
710 let opts = List.sort (fun a b ->
711 String.compare (String.concat " " (fst a)) (String.concat " " (fst b)))
712 (Hashtbl.fold mkopt current_state []) in
713 eval_call (Xmlprotocol.set_options opts) h
714 (function
715 | Interface.Good () -> k ()
716 | _ -> failwith "Cannot set options. Resetting rocqtop")
717
718 end
719
720 let goals x h k =
721 PrintOpt.enforce h (fun () -> eval_call (Xmlprotocol.goals x) h k)
722
723 let subgoals x h k =
724 PrintOpt.enforce h (fun () -> eval_call (Xmlprotocol.subgoals x) h k)
725
726 let evars x h k =
727 PrintOpt.enforce h (fun () -> eval_call (Xmlprotocol.evars x) h k)