Debian Codegraph @

ide/rocqide/idetop.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 Vernacexpr
12 open Vernacprop
13 open CErrors
14 open Util
15 open Pp
16 open Printer
17
18 module NamedDecl = Context.Named.Declaration
19 module CompactedDecl = Context.Compacted.Declaration
20
21 (** Idetop : an implementation of [Interface], i.e. mainly an interp
22 function and a rewind function. *)
23
24
25 (** Signal handling: we postpone ^C during input and output phases,
26 but make it directly raise a Sys.Break during evaluation of the request. *)
27
28 let catch_break = ref false
29
30 (* tell whether we have a bona fide interrupt *)
31 let valid_interrupt () =
32 if Sys.os_type = "Win32" then begin
33 let fname = Shared.get_interrupt_fname (Unix.getpid ()) in
34 let exists = Sys.file_exists fname in
35 if exists then Unix.unlink fname;
36 exists
37 end else
38 true
39
40 let init_signal_handler () =
41 let f _ = if valid_interrupt () then
42 if !catch_break then raise Sys.Break else Control.interrupt := true in
43 Sys.set_signal Sys.sigint (Sys.Signal_handle f)
44
45 let pr_with_pid s = Printf.eprintf "[pid %d] %s\n%!" (Unix.getpid ()) s
46
47 let pr_error s = pr_with_pid s
48 let pr_debug s =
49 if CDebug.(get_flag misc) then pr_with_pid s
50 let pr_debug_call q =
51 if CDebug.(get_flag misc) then pr_with_pid ("<-- " ^ Xmlprotocol.pr_call q)
52 let pr_debug_answer q r =
53 if CDebug.(get_flag misc) then pr_with_pid ("--> " ^ Xmlprotocol.pr_full_value q r)
54
55 (** Categories of commands *)
56
57 let rocqide_known_option table = List.mem table [
58 ["Printing";"Implicit"];
59 ["Printing";"Coercions"];
60 ["Printing";"Matching"];
61 ["Printing";"Synth"];
62 ["Printing";"Notations"];
63 ["Printing";"Parentheses"];
64 ["Printing";"All"];
65 ["Printing";"Records"];
66 ["Printing";"Existential";"Instances"];
67 ["Printing";"Universes"];
68 ["Printing";"Unfocused"];
69 ["Printing";"Goal";"Names"];
70 ["Diffs"]]
71
72 let is_known_option cmd = match cmd with
73 VernacSynterp (VernacSetOption (_, o, OptionSetTrue)
74 | VernacSetOption (_, o, OptionSetString _)
75 | VernacSetOption (_, o, OptionUnset)) -> rocqide_known_option o
76 | _ -> false
77
78 let ide_cmd_warns ~id { CAst.loc; v } =
79 let warn msg = Feedback.(feedback ~id (Message (Warning, loc, [], strbrk msg))) in
80 if is_known_option v.expr then
81 warn "Set this option from the IDE menu instead";
82 if is_navigation_vernac v.expr || is_undo v.expr then
83 warn "Use IDE navigation instead"
84
85 (** Interpretation (cf. [Ide_intf.interp]) *)
86
87 let ide_doc = ref None
88 let get_doc () = Option.get !ide_doc
89 let set_doc doc = ide_doc := Some doc
90
91 let add ((((s,eid),(sid,verbose)),off),(line_nb,bol_pos)) =
92 let doc = get_doc () in
93 let open Loc in
94 (* This needs to be akin to what CLexer.after does *)
95 let loc = { (initial ToplevelInput) with
96 bp=off
97 ; line_nb
98 ; bol_pos
99 ; ep=off
100 ; line_nb_last=line_nb
101 ; bol_pos_last=bol_pos } in
102 let r_stream = Gramlib.Stream.of_string ~offset:off s in
103 let pa = Procq.Parsable.make ~loc r_stream in
104 match Stm.parse_sentence ~doc sid ~entry:Pvernac.main_entry pa with
105 | None -> assert false (* s may not be empty *)
106 | Some ast ->
107 let doc, newid, rc = Stm.add ~doc ~ontop:sid verbose ast in
108 set_doc doc;
109 let rc = match rc with Stm.NewAddTip -> CSig.Inl () | Stm.Unfocus id -> CSig.Inr id in
110 ide_cmd_warns ~id:newid ast;
111 (* All output is sent through the feedback mechanism rather than stdout/stderr *)
112 newid, rc
113
114 let edit_at id =
115 let doc = get_doc () in
116 match Stm.edit_at ~doc id with
117 | doc, Stm.NewTip -> set_doc doc; CSig.Inl ()
118 | doc, Stm.Focus { Stm.start; stop; tip} -> set_doc doc; CSig.Inr (start, (stop, tip))
119
120 (* TODO: the "" parameter is a leftover of the times the protocol
121 * used to include stderr/stdout output.
122 *
123 * Currently, we force all the output meant for the to go via the
124 * feedback mechanism, and we don't manipulate stderr/stdout, which
125 * are left to the client's discrection. The parameter is still there
126 * as not to break the core protocol for this minor change, but it should
127 * be removed in the next version of the protocol.
128 *)
129 let query (route, (s,id)) =
130 let pa = Procq.Parsable.make (Gramlib.Stream.of_string s) in
131 let doc = get_doc () in
132 Stm.query ~at:id ~doc ~route pa
133
134 let annotate phrase =
135 let doc = get_doc () in
136 let pa = Procq.Parsable.make (Gramlib.Stream.of_string phrase) in
137 match Stm.parse_sentence ~doc (Stm.get_current_state ~doc) ~entry:Pvernac.main_entry pa with
138 | None -> Richpp.richpp_of_pp ~width:78 (Pp.mt ())
139 | Some ast ->
140 (* XXX: Width should be a parameter of annotate... *)
141 Richpp.richpp_of_pp ~width:78 (Ppvernac.pr_vernac ast)
142
143 (** Goal display *)
144
145 let hyp_next_tac sigma env decl =
146 let id = NamedDecl.get_id decl in
147 let ast = NamedDecl.get_type decl in
148 let id_s = Names.Id.to_string id in
149 let type_s = string_of_ppcmds (pr_ltype_env env sigma ast) in
150 [
151 ("clear "^id_s),("clear "^id_s^".");
152 ("apply "^id_s),("apply "^id_s^".");
153 ("exact "^id_s),("exact "^id_s^".");
154 ("generalize "^id_s),("generalize "^id_s^".");
155 ("absurd <"^id_s^">"),("absurd "^type_s^".")
156 ] @ [
157 ("discriminate "^id_s),("discriminate "^id_s^".");
158 ("injection "^id_s),("injection "^id_s^".")
159 ] @ [
160 ("rewrite "^id_s),("rewrite "^id_s^".");
161 ("rewrite <- "^id_s),("rewrite <- "^id_s^".")
162 ] @ [
163 ("elim "^id_s), ("elim "^id_s^".");
164 ("inversion "^id_s), ("inversion "^id_s^".");
165 ("inversion clear "^id_s), ("inversion_clear "^id_s^".")
166 ]
167
168 let concl_next_tac =
169 let expand s = (s,s^".") in
170 List.map expand ([
171 "intro";
172 "intros";
173 "intuition"
174 ] @ [
175 "reflexivity";
176 "discriminate";
177 "symmetry"
178 ] @ [
179 "assumption";
180 "ring";
181 "auto";
182 "eauto";
183 "tauto";
184 "trivial";
185 "decide equality";
186 "simpl";
187 "subst";
188 "red";
189 "split";
190 "left";
191 "right"
192 ])
193
194 let process_goal short sigma g =
195 let evi = Evd.find_undefined sigma g in
196 let env = Evd.evar_filtered_env (Global.env ()) evi in
197 let min_env = Environ.reset_context env in
198 let name = if Printer.print_goal_name sigma g then Some (Names.Id.to_string (Termops.evar_suggested_name env sigma g)) else None in
199 let ccl =
200 pr_letype_env ~goal_concl_style:true env sigma (Evd.evar_concl evi)
201 in
202 let process_hyp d (env,l) =
203 let d' = CompactedDecl.to_named_context d in
204 (List.fold_right EConstr.push_named d' env,
205 (pr_ecompacted_decl env sigma d) :: l) in
206 let hyps =
207 if short then [] else
208 let (_env, hyps) =
209 Context.Compacted.fold process_hyp
210 (Termops.compact_named_context sigma (EConstr.named_context env)) ~init:(min_env,[])
211 in
212 hyps
213 in
214 { Interface.goal_hyp = List.rev hyps; Interface.goal_ccl = ccl; Interface.goal_id = Proof.goal_uid g; Interface.goal_name = name }
215
216 let process_goal_diffs ~short diff_goal_map oldp nsigma ng =
217 let env = Global.env () in
218 let name = if Printer.print_goal_name nsigma ng then Some (Names.Id.to_string (Termops.evar_suggested_name env nsigma ng)) else None in
219 let og_s = match oldp, diff_goal_map with
220 | Some oldp, Some diff_goal_map -> Proof_diffs.map_goal ng diff_goal_map
221 | None, _ | _, None -> None
222 in
223 let (hyps_pp_list, concl_pp) =
224 Proof_diffs.diff_goal ~short ?og_s ~flags:(PrintingFlags.current())
225 (Proof_diffs.make_goal env nsigma ng)
226 in
227 { Interface.goal_hyp = hyps_pp_list; Interface.goal_ccl = concl_pp;
228 Interface.goal_id = Proof.goal_uid ng; Interface.goal_name = name }
229
230 let export_pre_goals flags Proof.{ sigma; goals; stack } ~short diff =
231 let open Interface in
232 let process x = match diff with
233 | None -> process_goal short sigma x
234 | Some (diff_goal_map, oldp) -> process_goal_diffs ~short diff_goal_map oldp sigma x
235 in
236 let process x = List.map process x in
237 let fg_goals = if flags.gf_fg then process goals else [] in
238 let bg_goals =
239 if flags.gf_bg then List.(map (fun (lg,rg) -> process lg, process rg)) stack
240 else []
241 in
242 let shelved_goals =
243 if flags.gf_shelved then process @@ Evd.shelf sigma
244 else []
245 in
246 let given_up_goals =
247 if flags.gf_given_up then process (Evar.Set.elements @@ Evd.given_up sigma)
248 else []
249 in
250 { fg_goals; bg_goals; shelved_goals; given_up_goals }
251
252 let subgoals flags =
253 let doc = get_doc () in
254 ignore (Stm.finish ~doc : Vernacstate.t);
255 let short = match flags.Interface.gf_mode with
256 | "short" -> true
257 | _ -> false
258 in
259 try
260 let newp = Vernacstate.Declare.give_me_the_proof () in
261 let sigma = Proof.data newp in
262 if Proof_diffs.show_diffs () then begin
263 let oldp = Stm.get_prev_proof ~doc (Stm.get_current_state ~doc) in
264 (try
265 let diff_goal_map = match oldp with
266 | None -> None
267 | Some oldp -> Some (Proof_diffs.make_goal_map oldp newp)
268 in
269 Some (export_pre_goals flags sigma ~short (Some (diff_goal_map, oldp)))
270 with Pp_diff.Diff_Failure msg ->
271 Proof_diffs.notify_proof_diff_failure msg;
272 Some (export_pre_goals flags sigma ~short None))
273 end else
274 Some (export_pre_goals flags sigma ~short None)
275 with Vernacstate.Declare.NoCurrentProof -> None
276 [@@ocaml.warning "-3"]
277
278 let goals () =
279 let open Interface in
280 let all = { gf_mode = "full"; gf_fg = true; gf_bg = true; gf_shelved = true; gf_given_up = true } in
281 subgoals all
282
283 let evars () =
284 try
285 let doc = get_doc () in
286 ignore (Stm.finish ~doc : Vernacstate.t);
287 let pfts = Vernacstate.Declare.give_me_the_proof () in
288 let Proof.{ sigma } = Proof.data pfts in
289 let exl = Evar.Map.bindings (Evd.undefined_map sigma) in
290 let map_evar ev = { Interface.evar_info = string_of_ppcmds (pr_evar sigma ev); } in
291 let el = List.map map_evar exl in
292 Some el
293 with Vernacstate.Declare.NoCurrentProof -> None
294 [@@ocaml.warning "-3"]
295
296 let hints () =
297 try
298 let pfts = Vernacstate.Declare.give_me_the_proof () in
299 let Proof.{ goals; sigma } = Proof.data pfts in
300 match goals with
301 | [] -> None
302 | g :: _ ->
303 let env = Evd.evar_filtered_env (Global.env ()) (Evd.find_undefined sigma g) in
304 let get_hint_hyp env d accu = hyp_next_tac sigma env d :: accu in
305 let hint_hyps = List.rev (Environ.fold_named_context get_hint_hyp env ~init: []) in
306 Some (hint_hyps, concl_next_tac)
307 with Vernacstate.Declare.NoCurrentProof -> None
308 [@@ocaml.warning "-3"]
309
310 (** Other API calls *)
311
312 let wait () =
313 let doc = get_doc () in
314 Stm.wait ~doc
315
316 let status force =
317 (* We remove the initial part of the current [DirPath.t]
318 (usually Top in an interactive session, cf "coqtop -top"),
319 and display the other parts (opened sections and modules) *)
320 ignore (Stm.finish ~doc:(get_doc ()) : Vernacstate.t);
321 if force then Stm.join ~doc:(get_doc ());
322 let path =
323 let l = Names.DirPath.repr (Libnames.dirpath_of_path @@ Lib.cwd ()) in
324 List.rev_map Names.Id.to_string l
325 in
326 let proof =
327 try Some (Names.Id.to_string (Vernacstate.Declare.get_current_proof_name ()))
328 with Vernacstate.Declare.NoCurrentProof -> None
329 in
330 let allproofs =
331 let l = Vernacstate.Declare.get_all_proof_names () in
332 List.map Names.Id.to_string l
333 in
334 {
335 Interface.status_path = path;
336 Interface.status_proofname = proof;
337 Interface.status_allproofs = allproofs;
338 Interface.status_proofnum = Stm.current_proof_depth ~doc:(get_doc ());
339 }
340 [@@ocaml.warning "-3"]
341
342 let export_rocq_object t = {
343 Interface.coq_object_prefix = t.Search.coq_object_prefix;
344 Interface.coq_object_qualid = t.Search.coq_object_qualid;
345 Interface.coq_object_object =
346 let env = Global.env () in
347 let sigma = Evd.from_env env in
348 Pp.string_of_ppcmds (pr_lconstr_env env sigma t.Search.coq_object_object)
349 }
350
351 let pattern_of_string ?env s =
352 let env =
353 match env with
354 | None -> Global.env ()
355 | Some e -> e
356 in
357 let constr = Procq.parse_string Procq.Constr.cpattern s in
358 let (_, pat) = Constrintern.interp_constr_pattern env (Evd.from_env env) constr in
359 pat
360
361 let dirpath_of_string_list s =
362 let path = String.concat "." s in
363 let qid = Procq.parse_string Procq.Constr.global path in
364 let id =
365 try Nametab.full_name_module qid
366 with Not_found ->
367 CErrors.user_err
368 (str "Module " ++ str path ++ str " not found.")
369 in
370 id
371
372 let import_search_constraint = function
373 | Interface.Name_Pattern s -> Search.Name_Pattern (Str.regexp s)
374 | Interface.Type_Pattern s -> Search.Type_Pattern (pattern_of_string s)
375 | Interface.SubType_Pattern s -> Search.SubType_Pattern (pattern_of_string s)
376 | Interface.In_Module ms -> Search.In_Module (dirpath_of_string_list ms)
377 | Interface.Include_Blacklist -> Search.Include_Blacklist
378
379 let search flags =
380 let pstate = Vernacstate.Declare.get_pstate () in
381 let sigma, env = match pstate with
382 | None -> let env = Global.env () in Evd.(from_env env, env)
383 | Some p -> Declare.Proof.get_goal_context p 1 in
384 List.map export_rocq_object (Search.interface_search env sigma (
385 List.map (fun (c, b) -> (import_search_constraint c, b)) flags)
386 )
387 [@@ocaml.warning "-3"]
388
389 let export_option_value = function
390 | Goptions.BoolValue b -> Interface.BoolValue b
391 | Goptions.IntValue x -> Interface.IntValue x
392 | Goptions.StringValue s -> Interface.StringValue s
393 | Goptions.StringOptValue s -> Interface.StringOptValue s
394
395 let import_option_value = function
396 | Interface.BoolValue b -> Goptions.BoolValue b
397 | Interface.IntValue x -> Goptions.IntValue x
398 | Interface.StringValue s -> Goptions.StringValue s
399 | Interface.StringOptValue s -> Goptions.StringOptValue s
400
401 let export_option_state s = {
402 Interface.opt_sync = true;
403 Interface.opt_depr = Option.has_some s.Goptions.opt_depr;
404 Interface.opt_value = export_option_value s.Goptions.opt_value;
405 }
406
407 let proof_diff (diff_opt, sid) =
408 let diff_opt = Proof_diffs.string_to_diffs diff_opt in
409 let doc = get_doc () in
410 match Stm.get_proof ~doc sid with
411 | None -> CErrors.user_err (Pp.str "No proofs to diff.")
412 | Some proof ->
413 let old = Stm.get_prev_proof ~doc sid in
414 Proof_diffs.diff_proofs ~flags:(PrintingFlags.current()) ~diff_opt ?old proof
415
416 let debug_cmd = ref DebugHook.Action.Ignore
417
418 let db_cmd cmd =
419 debug_cmd := DebugHook.Action.Command cmd
420
421 let db_continue opt =
422 let open DebugHook.Action in
423 debug_cmd := match opt with
424 | Interface.StepIn -> StepIn
425 | Interface.StepOver -> StepOver
426 | Interface.StepOut -> StepOut
427 | Interface.Continue -> Continue
428 | Interface.Interrupt -> Interrupt
429
430 let db_upd_bpts updates =
431 debug_cmd := DebugHook.Action.UpdBpts updates
432
433 let db_stack () =
434 debug_cmd := DebugHook.Action.GetStack;
435 [] (* return value passed through DebugHook.Answer *)
436
437 let db_vars framenum =
438 debug_cmd := DebugHook.Action.GetVars framenum;
439 [] (* return value passed through DebugHook.Answer *)
440
441 let db_configd () =
442 debug_cmd := DebugHook.Action.Configd
443
444 let get_options () =
445 let table = Goptions.get_tables () in
446 let fold key state accu = (key, export_option_state state) :: accu in
447 Goptions.OptionMap.fold fold table []
448
449 let set_options options =
450 let open Goptions in
451 let iter (name, value) = match import_option_value value with
452 | BoolValue b -> set_bool_option_value name b
453 | IntValue i -> set_int_option_value name i
454 | StringValue s -> set_string_option_value name s
455 | StringOptValue (Some s) -> set_string_option_value name s
456 | StringOptValue None -> unset_option_value_gen name
457 in
458 List.iter iter options
459
460 let about () = {
461 Interface.coqtop_version = Coq_config.version;
462 Interface.protocol_version = Xmlprotocol.protocol_version;
463 Interface.release_date = "n/a";
464 Interface.compile_date = "n/a";
465 }
466
467 let handle_exn (e, info) =
468 let dummy = Stateid.dummy in
469 let mk_msg () = CErrors.iprint (e,info) in
470 match e with
471 | e ->
472 match Stateid.get info with
473 | Some (valid, _) -> valid, Loc.get_loc info, mk_msg ()
474 | None -> dummy, Loc.get_loc info, mk_msg ()
475
476 let init =
477 let initialized = ref false in
478 fun file ->
479 if !initialized then anomaly (str "Already initialized.")
480 else begin
481 let init_sid = Stm.get_current_state ~doc:(get_doc ()) in
482 initialized := true;
483 match file with
484 | None -> init_sid
485 | Some file ->
486 let doc, initial_id, _ =
487 get_doc (), init_sid, `NewTip in
488 if Filename.check_suffix file ".v" then
489 Stm.set_compilation_hints file;
490 ignore (Stm.finish ~doc : Vernacstate.t);
491 initial_id
492 end
493
494 (* Retrocompatibility stuff, disabled since 8.7 *)
495 let interp ((_raw, verbose), s) =
496 Stateid.dummy, CSig.Inr "The interp call has been disabled, please use Add."
497
498 (** When receiving the Quit call, we don't directly do an [exit 0],
499 but rather set this reference, in order to send a final answer
500 before exiting. *)
501 let quit = ref false
502
503 (** Disabled *)
504 let print_ast id = Xml_datatype.PCData "ERROR"
505
506 let idetop_make_cases iname =
507 let qualified_iname = Libnames.qualid_of_string iname in
508 let iref = Nametab.global_inductive qualified_iname in
509 ComInductive.make_cases iref
510
511 (** Grouping all call handlers together + error handling *)
512 let eval_call c =
513 let interruptible f x =
514 catch_break := true;
515 Control.check_for_interrupt ();
516 let r = f x in
517 catch_break := false;
518 r
519 in
520 let handler = {
521 Interface.add = interruptible add;
522 Interface.edit_at = interruptible edit_at;
523 Interface.query = interruptible query;
524 Interface.goals = interruptible goals;
525 Interface.evars = interruptible evars;
526 Interface.hints = interruptible hints;
527 Interface.status = interruptible status;
528 Interface.search = interruptible search;
529 Interface.proof_diff = interruptible proof_diff;
530 Interface.db_cmd = db_cmd;
531 Interface.db_upd_bpts = db_upd_bpts;
532 Interface.db_continue = db_continue;
533 Interface.db_stack = db_stack;
534 Interface.db_vars = db_vars;
535 Interface.db_configd = db_configd;
536 Interface.get_options = interruptible get_options;
537 Interface.set_options = interruptible set_options;
538 Interface.mkcases = interruptible idetop_make_cases;
539 Interface.quit = (fun () -> quit := true);
540 Interface.init = interruptible init;
541 Interface.about = interruptible about;
542 Interface.wait = interruptible wait;
543 Interface.interp = interruptible interp;
544 Interface.handle_exn = handle_exn;
545 Interface.stop_worker = Stm.stop_worker;
546 Interface.print_ast = print_ast;
547 Interface.annotate = interruptible annotate;
548 Interface.subgoals = interruptible subgoals;
549 } in
550 Xmlprotocol.abstract_eval_call handler c
551
552 let xml_debug = ref false
553
554 (** Message dispatching.
555 Since [coqidetop] starts 1 thread per slave, and each
556 thread forwards feedback messages from the slave to the GUI on the same
557 xml channel, we need mutual exclusion. The mutex should be per-channel, but
558 here we only use 1 channel. *)
559 let print_xml =
560 let m = Mutex.create () in
561 fun oc xml ->
562 CThread.with_lock m ~scope:(fun () ->
563 if !xml_debug then
564 Printf.printf "SENT --> %s\n%!" (Xml_printer.to_string_fmt xml);
565 try Control.protect_sigalrm (Xml_printer.print oc) xml
566 with e -> let e = Exninfo.capture e in Exninfo.iraise e)
567
568 let slave_feeder fmt xml_oc msg =
569 let xml = Xmlprotocol.(of_feedback fmt msg) in
570 print_xml xml_oc xml
571
572 (** The main loop *)
573
574 (** Exceptions during eval_call should be converted into [Interface.Fail]
575 messages by [handle_exn] above. Otherwise, we die badly, without
576 trying to answer malformed requests. *)
577
578 let msg_format = ref (fun () ->
579 let width = Option.default 72 (Topfmt.get_margin ()) in
580 let depth = Option.default max_int (Topfmt.get_depth_boxes ()) in
581 Xmlprotocol.Richpp { width; depth }
582 )
583
584 (* The loop ignores the command line arguments as the current model delegates
585 its handing to the toplevel container. *)
586 let loop ( { Coqtop.run_mode; color_mode },_) ~opts:_ state =
587 match run_mode with
588 | Coqtop.Batch -> exit 0
589 | Coqtop.(Query PrintTags) -> Colors.print_style_tags color_mode; exit 0
590 | Coqtop.(Query _) -> Printf.eprintf "Unknown query"; exit 1
591 | Coqtop.Interactive ->
592 let open Vernac.State in
593 set_doc state.doc;
594 init_signal_handler ();
595 catch_break := false;
596 let in_ch, out_ch = Spawned.get_channels () in
597 let xml_oc = Xml_printer.make (Xml_printer.TChannel out_ch) in
598 let in_lb = Lexing.from_function (fun s len ->
599 CThread.thread_friendly_read in_ch s ~off:0 ~len) in
600 (* SEXP parser make *)
601 let xml_ic = Xml_parser.make (Xml_parser.SLexbuf in_lb) in
602 let () = Xml_parser.check_eof xml_ic false in
603 ignore (Feedback.add_feeder (slave_feeder (!msg_format ()) xml_oc));
604 let process_xml_msg xml_ic xml_oc out_ch =
605 try
606 let xml_query = Xml_parser.parse xml_ic in
607 if !xml_debug then
608 pr_with_pid (Xml_printer.to_string_fmt xml_query);
609 let Xmlprotocol.Unknown q = Xmlprotocol.to_call xml_query in
610 let () = pr_debug_call q in
611 let (send, r) = eval_call q in
612 (* conditional send so that db_stack and db_vars can reply through DebugHook.Answer *)
613 if send then begin
614 let () = pr_debug_answer q r in
615 (* pr_with_pid (Xml_printer.to_string_fmt (Xmlprotocol.of_answer q r)); *)
616 print_xml xml_oc Xmlprotocol.(of_answer (!msg_format ()) q r);
617 flush out_ch
618 end
619 with
620 | Xml_parser.Error (Xml_parser.Empty, _) ->
621 pr_debug "End of input, exiting gracefully.";
622 exit 0
623 | Xml_parser.Error (err, loc) ->
624 pr_error ("XML syntax error: " ^ Xml_parser.error_msg err)
625 | Serialize.Marshal_error (msg,node) ->
626 pr_error "Unexpected XML message";
627 pr_error ("Expected XML node: " ^ msg);
628 pr_error ("XML tree received: " ^ Xml_printer.to_string_fmt node)
629 | any ->
630 pr_debug ("Fatal exception in rocqtop:\n" ^ Printexc.to_string any);
631 exit 1
632 in
633
634 (* output the xml message using the feeder, note that the
635 xmlprotocol file doesn't depend on vernac thus it has no access
636 to DebugHook data, we may want to fix that. *)
637 let ltac_debug_answer ans =
638 let open DebugHook.Answer in
639 let open Xmlprotocol in
640 let xml = match ans with
641 | Prompt msg -> of_ltac_debug_answer ~tag:"prompt" msg
642 | Goal msg -> of_ltac_debug_answer ~tag:"goal" msg
643 | Output msg -> of_ltac_debug_answer ~tag:"output" msg
644 | Init -> of_ltac_debug_answer ~tag:"init" (str "")
645 | Vars vars -> of_vars vars;
646 | Stack s -> of_stack s
647 in
648 print_xml xml_oc xml in
649
650 (* XXX: no need to have a ref here *)
651 let ltac_debug_parse () =
652 let raw_cmd =
653 debug_cmd := DebugHook.Action.Ignore;
654 process_xml_msg xml_ic xml_oc out_ch;
655 !debug_cmd
656 in
657 let open DebugHook in
658 match raw_cmd with
659 | Action.Command cmd ->
660 (match Action.parse cmd with
661 | Ok act -> act
662 | Error error -> ltac_debug_answer (Answer.Output (str error)); Action.Failed)
663 | act -> act
664 in
665
666 DebugHook.Intf.(set
667 { read_cmd = ltac_debug_parse
668 ; submit_answer = ltac_debug_answer
669 ; isTerminal = false;
670 });
671
672 while not !quit do
673 process_xml_msg xml_ic xml_oc out_ch
674 done;
675 pr_debug "Exiting gracefully.";
676 exit 0
677
678 let rec parse = function
679 | "--help-XML-protocol" :: rest ->
680 Xmlprotocol.document Xml_printer.to_string_fmt; exit 0
681 | "--xml_format=Ppcmds" :: rest ->
682 msg_format := (fun () -> Xmlprotocol.Ppcmds); parse rest
683 | "-xml-debug" :: rest ->
684 xml_debug := true; parse rest
685 | x :: rest ->
686 if String.length x > 0 && x.[0] = '-' then
687 (prerr_endline ("Unknown option " ^ x); exit 1)
688 else
689 x :: parse rest
690 | [] -> []
691
692 let rocqidetop_specific_usage = Boot.Usage.{
693 executable_name = "coqidetop";
694 extra_args = "";
695 extra_options = "\n\
696 coqidetop specific options:\n\
697 \n --xml_formatinclude dir (idem)\
698 \n --xml_format=Ppcmds serialize pretty printing messages using the std_ppcmds format\
699 \n --help-XML-protocol print documentation of the Coq XML protocol\n"
700 }
701
702 let islave_parse opts extra_args =
703 let open Coqtop in
704 let ({ run_mode; color_mode }, stm_opts), extra_args = coqtop_toplevel.parse_extra opts extra_args in
705 let extra_args = parse extra_args in
706 (* One of the role of coqidetop is to find the name of buffers to open *)
707 (* in the command line; Rocqide is waiting these names on stdout *)
708 (* (see filter_rocq_opts in rocq.ml), so we send them now *)
709 print_string (String.concat "\n" extra_args);
710 ( { Coqtop.run_mode; color_mode }, stm_opts), []
711
712 let islave_init ( { Coqtop.run_mode; color_mode }, stm_opts) injections ~opts =
713 if run_mode = Coqtop.Batch then Flags.quiet := true;
714 (* -xml-debug implies -debug. *)
715 let injections = if !xml_debug
716 then Coqargs.OptionInjection (["Debug"], OptionSet (Some "all")) :: injections
717 else injections
718 in
719 Coqtop.init_toploop opts stm_opts injections
720
721 let islave_default_opts = Coqargs.default
722
723 let () =
724 let open Coqtop in
725 Shared_os_specific.init ();
726 let custom = {
727 parse_extra = islave_parse ;
728 usage = rocqidetop_specific_usage;
729 init_extra = islave_init;
730 run = loop;
731 initial_args = islave_default_opts } in
732 start_coq custom (List.tl (Array.to_list Sys.argv))