Debian Codegraph @

ide/rocqide/rocqOps.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 Util
12 open RocqDriver
13 open Interface
14 open Feedback
15
16 type flag = [ `INCOMPLETE | `UNSAFE | `PROCESSING | `ERROR of string Loc.located | `WARNING of string Loc.located ]
17 type mem_flag = [ `INCOMPLETE | `UNSAFE | `PROCESSING | `ERROR | `WARNING ]
18 let mem_flag_of_flag : flag -> mem_flag = function
19 | `ERROR _ -> `ERROR
20 | `WARNING _ -> `WARNING
21 | (`INCOMPLETE | `UNSAFE | `PROCESSING) as mem_flag -> mem_flag
22 let str_of_flag = function
23 | `UNSAFE -> "U"
24 | `PROCESSING -> "P"
25 | `ERROR _ -> "E"
26 | `WARNING _ -> "W"
27 | `INCOMPLETE -> "I"
28
29 class type signals =
30 object
31 inherit GUtil.ml_signals
32 method changed : callback:(int * mem_flag list -> unit) -> GtkSignal.id
33 end
34
35 module SentenceId : sig
36
37 type sentence = private {
38 start : GText.mark;
39 stop : GText.mark;
40 mutable flags : flag list;
41 mutable tooltips : (int * int * string) list;
42 start_offset : int;
43 (** Original start offset of the sentence, to be compared when moved *)
44 start_line : int;
45 (** Original start line of the sentence, to be compared when moved *)
46 edit_id : int;
47 mutable index : int;
48 changed_sig : (int * mem_flag list) GUtil.signal;
49 }
50
51 val mk_sentence :
52 start:GText.mark -> stop:GText.mark -> start_offset:int -> start_line:int -> flag list -> sentence
53
54 val add_flag : sentence -> flag -> unit
55 val has_flag : sentence -> mem_flag -> bool
56 val remove_flag : sentence -> mem_flag -> unit
57 val find_all_tooltips : sentence -> int -> string list
58 val add_tooltip : sentence -> int -> int -> string -> unit
59 val set_index : sentence -> int -> unit
60
61 val connect : sentence -> signals
62
63 val start_iter : GText.buffer -> sentence -> GText.iter
64 val start_stop_iters : GText.buffer -> sentence -> GText.iter * GText.iter
65
66 (** [offset_compensation] Drift of a sentence over its original
67 location, as an [(offset, line)] pair. Needed to repair outdated
68 Rocq locations *)
69 val offset_compensation : GText.buffer -> sentence -> int * int
70
71 val phrase : GText.buffer -> sentence -> string
72
73 val dbg_to_string :
74 GText.buffer -> bool -> Stateid.t option -> sentence -> Pp.t
75
76 end = struct
77
78 type sentence = {
79 start : GText.mark;
80 stop : GText.mark;
81 mutable flags : flag list;
82 mutable tooltips : (int * int * string) list;
83 start_offset : int;
84 (** Original start offset of the sentence, to be compared when moved *)
85 start_line : int;
86 (** Original start line of the sentence, to be compared when moved *)
87 edit_id : int;
88 mutable index : int;
89 changed_sig : (int * mem_flag list) GUtil.signal;
90 }
91
92 let connect s : signals =
93 object
94 inherit GUtil.ml_signals [s.changed_sig#disconnect]
95 method changed = s.changed_sig#connect ~after
96 end
97
98 let id = ref 0
99 let mk_sentence ~start ~stop ~start_offset ~start_line flags = decr id; {
100 start;
101 stop;
102 flags;
103 edit_id = !id;
104 tooltips = [];
105 start_offset;
106 start_line;
107 index = -1;
108 changed_sig = new GUtil.signal ();
109 }
110
111 let changed s =
112 s.changed_sig#call (s.index, List.map mem_flag_of_flag s.flags)
113
114 let add_flag s f = s.flags <- CList.add_set (=) f s.flags; changed s
115 let has_flag s mf =
116 List.exists (fun f -> mem_flag_of_flag f = mf) s.flags
117 let remove_flag s mf =
118 s.flags <- List.filter (fun f -> mem_flag_of_flag f <> mf) s.flags; changed s
119 let find_all_tooltips s off =
120 CList.map_filter (fun (start,stop,t) ->
121 if start <= off && off <= stop then Some t else None)
122 s.tooltips
123 let add_tooltip s a b t = s.tooltips <- (a,b,t) :: s.tooltips
124
125 let set_index s i = s.index <- i
126
127 let start_iter buffer sentence = buffer#get_iter_at_mark sentence.start
128 let stop_iter buffer sentence = buffer#get_iter_at_mark sentence.stop
129 let start_stop_iters buffer sentence = start_iter buffer sentence, stop_iter buffer sentence
130 let offset_compensation buffer sentence =
131 let s_start = buffer#get_iter_at_mark sentence.start in
132 s_start#offset - sentence.start_offset, s_start#line - sentence.start_line
133
134 let phrase buffer sentence =
135 let start, stop = start_stop_iters buffer sentence in
136 start#get_slice ~stop
137
138 let dbg_to_string (b : GText.buffer) focused id s =
139 let ellipsize s =
140 Str.global_replace (Str.regexp "^[\n ]*") ""
141 (if String.length s > 20 then String.sub s 0 17 ^ "..."
142 else s) in
143 Pp.str (Printf.sprintf "%s[%3d,%3s](%5d,%5d) %s [%s] %s"
144 (if focused then "*" else " ")
145 s.edit_id
146 (Stateid.to_string (Option.default Stateid.dummy id))
147 (b#get_iter_at_mark s.start)#offset
148 (b#get_iter_at_mark s.stop)#offset
149 (ellipsize
150 ((b#get_iter_at_mark s.start)#get_slice ~stop:(b#get_iter_at_mark s.stop)))
151 (String.concat "," (List.map str_of_flag s.flags))
152 (ellipsize
153 (String.concat ","
154 (List.map (fun (a,b,t) ->
155 Printf.sprintf "<%d,%d> %s" a b t) s.tooltips))))
156
157
158 end
159 open SentenceId
160
161 (* Given a Rocq loc, convert it to a pair of iterators start / end in
162 the buffer. *)
163 let rocq_loc_to_gtk_offset ?(line_drift=0) (buffer : GText.buffer) loc =
164 Ideutils.get_iter_at_byte buffer ~line:(loc.Loc.line_nb - 1 + line_drift) (loc.bp - loc.bol_pos),
165 Ideutils.get_iter_at_byte buffer ~line:(loc.Loc.line_nb_last - 1 + line_drift) (loc.ep - loc.bol_pos_last)
166
167 (** increase [uni_off] by the number of bytes until [s_uni] This can
168 be used to convert a character offset to byte offset if we know a
169 previous point denoted by the pair [s_byte, s_uni] *)
170 let c2b (buffer : GText.buffer) (s_byte, s_uni) uni_off =
171 if s_uni < 0 then
172 raise (invalid_arg "c2b: s_uni must be >= 0");
173 let rec cvt iter rv =
174 if iter#offset <= s_uni then
175 rv
176 else
177 cvt iter#backward_char (rv + (Ideutils.ulen iter#char))
178 in
179 cvt (buffer#get_iter (`OFFSET uni_off)) s_byte
180
181 (* Given [sentence], returns [bp, line, bol] where [bp] is the
182 absolute offset in _bytes_ for the start of [sentence], [line] is
183 the line number for the start of sentence and [bol] is the line
184 ofsset of [sentence] in _bytes_.
185
186 This is meant to be used in the resumption of parsing, to tell Rocq
187 where the input stream was left at. In this case, these 3 points
188 uniquely determine the position where to restart
189 from. [CLexer.after] can compute this from the position of the last
190 parsed token.
191
192 However, for RocqIDE, we have a huge problem in the sense that
193 RocqIDE will do its own parsing and the locations may not start at
194 the same point. Thus, we need to perform potentially very costly
195 char to offset conversion, for that we need the whole buffer.
196 *)
197 let rocq_loc_from_gtk_offset cached buffer sentence =
198 let start = start_iter buffer sentence in
199 (* This is in chars not in bytes, thus needs conversion *)
200 let bp = c2b buffer cached start#offset in
201 (* Rocq lines start at 1, GTK lines at 0 *)
202 let line = start#line + 1 in
203 (* [line_index] already returns byte offsets *)
204 let bol_pos = bp - start#line_index in
205 (* *)
206 let new_cached = bp, start#offset in
207 bp, line, bol_pos, new_cached
208
209 let log msg : unit task =
210 RocqDriver.lift (fun () -> Minilib.log msg)
211
212 class type ops =
213 object
214 method go_to_insert : unit task
215 method go_to_mark : GText.mark -> unit task
216 method process_next_phrase : unit task
217 method process_db_cmd : string ->
218 next:(Interface.db_cmd_rty Interface.value -> unit task) -> unit task
219 method process_db_configd : unit ->
220 next:(Interface.db_configd_rty Interface.value -> unit task) -> unit task
221 method process_db_upd_bpts : ((string * int) * bool) list ->
222 next:(Interface.db_upd_bpts_rty Interface.value -> unit task) -> unit task
223 method process_db_continue : db_continue_opt ->
224 next:(Interface.db_continue_rty Interface.value -> unit task) -> unit task
225 method process_db_stack :
226 next:(Interface.db_stack_rty Interface.value -> unit task) -> unit task
227 method process_db_vars : int ->
228 next:(Interface.db_vars_rty Interface.value -> unit task) -> unit task
229 method process_until_end_or_error : unit task
230 method handle_reset_initial : unit task
231 method raw_rocq_query :
232 route_id:int -> next:(query_rty value -> unit task) -> string -> unit task
233 method proof_diff : GText.mark -> next:(Pp.t value -> unit task) -> unit task
234 method show_goals : unit task
235 method backtrack_last_phrase : unit task
236 method initialize : unit task
237 method join_document : unit task
238 method stop_worker : string -> unit task
239
240 method get_n_errors : int
241 method get_warnings : (int * string) list
242 method get_errors : (int * string) list
243 method get_slaves_status : int * int * string CString.Map.t
244 method backtrack_to_begin : unit -> unit task
245 method handle_failure : handle_exn_rty -> unit task
246
247 method destroy : unit -> unit
248 method scroll_to_start_of_input : unit -> unit
249 method set_forward_clear_db_highlight : (unit -> unit) -> unit
250 method set_forward_set_goals_of_dbg_session : (Pp.t -> unit) -> unit
251 method set_forward_init_db : (unit -> unit) -> unit
252 method set_debug_goal : Pp.t -> unit
253 end
254
255 let flags_to_color f =
256 if List.mem `PROCESSING f then `NAME "blue"
257 else if List.mem `ERROR f then `NAME "red"
258 else if List.mem `UNSAFE f then `NAME "orange"
259 else if List.mem `INCOMPLETE f then `NAME "gray"
260 else `NAME Preferences.processed_color#get
261
262 module Doc = Document
263
264 let segment_model (doc : sentence Doc.document) : Wg_Segment.model =
265 object (self)
266
267 val mutable cbs = []
268
269 val mutable document_length = 0
270
271 method length = document_length
272
273 method changed ~callback = cbs <- callback :: cbs
274
275 method fold : 'a. ('a -> Wg_Segment.color -> 'a) -> 'a -> 'a = fun f accu ->
276 let fold accu _ _ s =
277 let flags = List.map mem_flag_of_flag s.flags in
278 f accu (flags_to_color flags)
279 in
280 Doc.fold_all doc accu fold
281
282 method private on_changed (i, f) =
283 let data = (i, flags_to_color f) in
284 List.iter (fun f -> f (`SET data)) cbs
285
286 method private on_push s ctx =
287 let after = match ctx with
288 | None -> []
289 | Some (l, _) -> l
290 in
291 List.iter (fun s -> set_index s (s.index + 1)) after;
292 set_index s (document_length - List.length after);
293 ignore ((SentenceId.connect s)#changed ~callback:self#on_changed);
294 document_length <- document_length + 1;
295 List.iter (fun f -> f `INSERT) cbs
296
297 method private on_pop s ctx =
298 let () = match ctx with
299 | None -> ()
300 | Some (l, _) -> List.iter (fun s -> set_index s (s.index - 1)) l
301 in
302 set_index s (-1);
303 document_length <- document_length - 1;
304 List.iter (fun f -> f `REMOVE) cbs
305
306 initializer
307 let _ = (Doc.connect doc)#pushed ~callback:self#on_push in
308 let _ = (Doc.connect doc)#popped ~callback:self#on_pop in
309 ()
310
311 end
312
313 type queue_msg =
314 | MsgFeedback of Feedback.feedback
315 | MsgDebug of string * Pp.t
316
317 let rec flatten = function
318 | [] -> []
319 | (lg, rg) :: l ->
320 let inner = flatten l in
321 List.rev_append lg inner @ rg
322
323 class rocqops
324 (_script:Wg_ScriptView.script_view)
325 (_pv:Wg_ProofView.proof_view)
326 (_mv:Wg_RoutedMessageViews.message_views_router)
327 (_sg:Wg_Segment.segment)
328 (_ct:RocqDriver.rocqtop)
329 get_filename =
330 object(self)
331 val script = _script
332 val buffer = (_script#source_buffer :> GText.buffer)
333 val proof = _pv
334 val messages = _mv
335 val segment = _sg
336
337 val document : sentence Doc.document = Doc.create ()
338 val mutable document_length = 0
339
340 val mutable initial_state = Stateid.initial
341
342 (* proofs being processed by the slaves *)
343 val mutable to_process = 0
344 val mutable processed = 0
345 val mutable slaves_status = CString.Map.empty
346
347 val mutable last_offsets = (0,0)
348
349 val mutable forward_clear_db_highlight = ((fun x -> failwith "forward_clear_db_highlight")
350 : unit -> unit)
351
352 val mutable forward_set_goals_of_dbg_session = ((fun x -> failwith "forward_set_goals_of_dbg_session")
353 : Pp.t -> unit)
354
355 val mutable forward_init_db = ((fun x -> failwith "forward_init_db")
356 : unit -> unit)
357 initializer
358 RocqDriver.set_feedback_handler _ct
359 (fun msg -> self#process_feedback (MsgFeedback msg));
360 RocqDriver.set_debug_prompt_handler _ct
361 (fun ~tag msg -> self#process_feedback (MsgDebug (tag, msg)));
362 script#misc#set_has_tooltip true;
363 ignore(script#misc#connect#query_tooltip ~callback:self#tooltip_callback);
364 let md = segment_model document in
365 segment#set_model md;
366 let on_click id =
367 let find _ _ s = Int.equal s.index id in
368 let sentence = Doc.find document find in
369 let mark = sentence.start in
370 let iter = script#buffer#get_iter_at_mark mark in
371 (* Sentence starts tend to be at the end of a line, so we rather choose
372 the first non-line-ending position. *)
373 let rec sentence_start iter =
374 if iter#ends_line then sentence_start iter#forward_line
375 else iter
376 in
377 let iter = sentence_start iter in
378 script#buffer#place_cursor ~where:iter;
379 ignore (script#scroll_to_iter ~use_align:true ~yalign:0. iter)
380 in
381 let _ = segment#connect#clicked ~callback:on_click in
382 ()
383
384 method private tooltip_callback ~x ~y ~kbd tooltip =
385 let x, y = script#window_to_buffer_coords ~tag:`WIDGET ~x ~y in
386 let iter = script#get_iter_at_location ~x ~y in
387 if iter#has_tag Tags.Script.tooltip then begin
388 let rec aux iter =
389 let marks = iter#marks in
390 if marks = [] then aux_rec iter#backward_char
391 else
392 let mem_marks _ _ s =
393 List.exists (fun m ->
394 Gobject.get_oid m =
395 Gobject.get_oid (buffer#get_mark s.start)) marks in
396 try Some (Doc.find document mem_marks)
397 with Not_found -> aux_rec iter#backward_char
398 and aux_rec iter =
399 if iter#is_start then None
400 else aux iter
401 in
402 let s : SentenceId.sentence option = aux iter in
403 let ss = match s with
404 | None -> []
405 | Some s ->
406 (* The original list of tooltips contains offset that were not
407 set up to date if the sentences moved, however the GTK model
408 has the up-to-date information in the marks, so we can
409 compare and compensate for the shift. *)
410 let offset, _line_shift = offset_compensation script#buffer s in
411 find_all_tooltips s (iter#offset - offset)
412 in
413 let ss = if ss = [] then Doc.get_errors document else ss in
414 let msg = CString.html_escape (String.concat "\n" (CList.uniquize ss)) in
415 GtkBase.Tooltip.set_icon_from_stock tooltip `INFO `BUTTON;
416 script#misc#set_tooltip_markup ("<tt>" ^ msg ^ "</tt>")
417 end else begin
418 script#misc#set_tooltip_text ""; script#misc#set_has_tooltip true
419 end;
420 false
421
422 method destroy () = ()
423
424 method scroll_to_start_of_input () =
425 let start = buffer#get_iter_at_mark (`NAME "start_of_input") in
426 ignore (script#scroll_to_iter ~use_align:true ~yalign:0. start)
427
428 method set_forward_clear_db_highlight f =
429 forward_clear_db_highlight <- f
430
431 method set_forward_set_goals_of_dbg_session f =
432 forward_set_goals_of_dbg_session <- f
433
434 method set_forward_init_db f =
435 forward_init_db <- f
436
437 method private print_stack =
438 Minilib.log "document:";
439 Minilib.log_pp (Doc.print document (dbg_to_string buffer))
440
441 method private enter_focus start stop =
442 let at id id' _ = Stateid.equal id' id in
443 self#print_stack;
444 Minilib.log("Focusing "^Stateid.to_string start^" "^Stateid.to_string stop);
445 Doc.focus document ~cond_top:(at start) ~cond_bot:(at stop);
446 self#print_stack;
447 let qed_s = Doc.tip_data document in
448 buffer#move_mark ~where:(buffer#get_iter_at_mark qed_s.stop)
449 (`NAME "stop_of_input")
450
451 method private exit_focus =
452 Minilib.log "Unfocusing";
453 Doc.unfocus document;
454 self#print_stack;
455 begin try
456 let where = buffer#get_iter_at_mark (Doc.tip_data document).stop in
457 buffer#move_mark ~where (`NAME "start_of_input");
458 with Doc.Empty -> () end;
459 buffer#move_mark ~where:buffer#end_iter (`NAME "stop_of_input")
460
461 method private get_start_of_input =
462 buffer#get_iter_at_mark (`NAME "start_of_input")
463
464 method private get_end_of_input =
465 buffer#get_iter_at_mark (`NAME "stop_of_input")
466
467 method private get_insert =
468 buffer#get_iter_at_mark `INSERT
469
470 method private show_goals_aux ?(move_insert=false) () =
471 if move_insert then begin
472 let dest = self#get_start_of_input in
473 if (buffer#get_iter_at_mark `INSERT)#compare dest <= 0 then begin
474 buffer#place_cursor ~where:dest;
475 script#recenter_insert
476 end
477 end;
478 let gf_bg = PrintOpt.printing_unfocused () in
479 let flags = { gf_mode = "full"; gf_fg = true; gf_bg; gf_shelved = false; gf_given_up = false } in
480 let return x = RocqDriver.return (Good x) in
481 let (>>=) m f = RocqDriver.bind m (function
482 | Fail x -> RocqDriver.return (Fail x)
483 | Good v -> f v)
484 in
485 let call =
486 RocqDriver.subgoals flags >>= begin function
487 | None -> return Wg_ProofView.NoGoals
488 | Some { fg_goals = ((_ :: _) as fg); bg_goals = bg } ->
489 let bg = flatten (List.rev bg) in
490 return (Wg_ProofView.FocusGoals { fg; bg; })
491 | Some { fg_goals = []; bg_goals = bg } ->
492 let flags = { gf_mode = "short"; gf_fg = false; gf_bg = false; gf_shelved = true; gf_given_up = true } in
493 RocqDriver.subgoals flags >>= fun rem ->
494 let bg = flatten (List.rev bg) in
495 let shelved, given_up = match rem with
496 | None -> [], []
497 | Some goals -> goals.shelved_goals, goals.given_up_goals
498 in
499 return (Wg_ProofView.NoFocusGoals { bg; shelved; given_up })
500 end
501 in
502 RocqDriver.bind call begin function
503 | Fail x -> self#handle_failure_aux ~move_insert x
504 | Good goals ->
505 proof#set_goals goals;
506 proof#refresh ~force:true;
507 RocqDriver.return ()
508 end
509
510 method show_goals = self#show_goals_aux ()
511
512 (* This method is intended to perform stateless commands *)
513 method raw_rocq_query ~route_id ~next phrase : unit RocqDriver.task =
514 let sid = try Document.tip document
515 with Document.Empty -> Stateid.initial
516 in
517 let action = log "raw_rocq_query starting now" in
518 let query = RocqDriver.query (route_id,(phrase,sid)) in
519 RocqDriver.bind (RocqDriver.seq action query) next
520
521 method proof_diff where ~next : unit RocqDriver.task =
522 (* todo: would be nice to ignore comments, too *)
523 let rec back iter =
524 if iter#is_start then iter
525 else
526 let c = iter#char in
527 if Glib.Unichar.isspace c || c = 0 then back (iter#backward_char)
528 else if c = int_of_char '.' then iter#backward_char
529 else iter in
530
531 let where = back (buffer#get_iter_at_mark where) in
532 let until _ start stop =
533 (buffer#get_iter_at_mark stop)#compare where >= 0 &&
534 (buffer#get_iter_at_mark start)#compare where <= 0 in
535 let state_id = fst @@ self#find_id until in
536 let diff_opt = Interface.(match RocqDriver.PrintOpt.(get diff) with
537 | StringValue diffs -> diffs
538 | _ -> "off") in
539 let proof_diff = RocqDriver.proof_diff (diff_opt, state_id) in
540 RocqDriver.bind proof_diff next
541
542 method private still_valid { edit_id = id } =
543 try ignore(Doc.find_id document (fun _ { edit_id = id1 } -> id = id1)); true
544 with Not_found -> false
545
546 method private mark_as_needed sentence =
547 if self#still_valid sentence then begin
548 Minilib.log_pp Pp.(str "Marking " ++ dbg_to_string buffer false None sentence);
549 let start = buffer#get_iter_at_mark sentence.start in
550 let stop = buffer#get_iter_at_mark sentence.stop in
551 let to_process = Tags.Script.to_process in
552 let processed = Tags.Script.processed in
553 let unjustified = Tags.Script.unjustified in
554 let error_bg = Tags.Script.error_bg in
555 let error = Tags.Script.error in
556 let incomplete = Tags.Script.incomplete in
557 let all_tags = [
558 error_bg; to_process; incomplete; processed; unjustified; error ] in
559 let tags =
560 (if has_flag sentence `PROCESSING then [to_process]
561 else if has_flag sentence `ERROR then [error_bg]
562 else if has_flag sentence `INCOMPLETE then [incomplete]
563 else [processed]) @
564 (if has_flag sentence `UNSAFE then [unjustified] else [])
565 in
566 List.iter (fun t -> buffer#remove_tag t ~start ~stop) all_tags;
567 List.iter (fun t -> buffer#apply_tag t ~start ~stop) tags
568 end
569
570 (* Invariant, we store the tooltips with "original" Rocq locations,
571 that means we must correct the offset even the Some case will get
572 the actual offset, beware this is a big fragile, but kinda
573 inherent to the model *)
574 method private attach_tooltip ?loc sentence text =
575 let offset, line_drift = offset_compensation buffer sentence in
576 let start, stop = match loc with
577 | None ->
578 start_stop_iters buffer sentence
579 | Some loc ->
580 rocq_loc_to_gtk_offset ~line_drift buffer loc
581 in
582 let markup = Glib.Markup.escape_text text in
583 buffer#apply_tag Tags.Script.tooltip ~start ~stop;
584 add_tooltip sentence (start#offset - offset) (stop#offset - offset) markup
585
586 method private debug_prompt ~tag msg =
587 match tag with
588 | "prompt" ->
589 messages#default_route#debug_prompt msg
590 | "goal" ->
591 forward_set_goals_of_dbg_session msg
592 | "init" -> forward_init_db ()
593 | _ ->
594 messages#default_route#push Debug msg
595
596 method set_debug_goal msg =
597 proof#set_debug_goal msg
598
599 method private process_feedback msg =
600 (* Minilib.log ("Feedback received: " ^ Xml_printer.to_string_fmt Xmlprotocol.(of_feedback Ppcmds msg)); *)
601 let pr_feedback msg =
602 let id = msg.span_id in
603 let sentence =
604 let finder _ state_id s =
605 match state_id, id with
606 | Some id', id when Stateid.equal id id' -> Some (state_id, s)
607 | _ -> None in
608 try Some (Doc.find_map document finder)
609 with Not_found -> None in
610 let log_pp ?id s =
611 Minilib.log_pp Pp.(seq
612 [str "Feedback "; s; pr_opt (fun id -> str " on " ++ str (Stateid.to_string id)) id])
613 in
614 let msg_wo_sent mtype =
615 Minilib.log (mtype ^ " feedback message without a sentence") in
616 let unsupp_msg mtype =
617 if sentence <> None then
618 Minilib.log ("Unsupported feedback message " ^ mtype ^ " with a sentence")
619 in
620 let log ?id s = log_pp ?id (Pp.str s) in
621 begin match msg.contents, sentence with
622 | AddedAxiom, Some (id,sentence) ->
623 log ?id "AddedAxiom";
624 remove_flag sentence `PROCESSING;
625 remove_flag sentence `ERROR;
626 add_flag sentence `UNSAFE;
627 self#mark_as_needed sentence
628 | AddedAxiom, None -> msg_wo_sent "AddedAxiom"
629 | Processed, Some (id,sentence) ->
630 log ?id "Processed" ;
631 remove_flag sentence `PROCESSING;
632 self#mark_as_needed sentence;
633 forward_clear_db_highlight ()
634 | Processed, None -> msg_wo_sent "Processed"
635 | ProcessingIn _, Some (id,sentence) ->
636 log ?id "ProcessingIn";
637 add_flag sentence `PROCESSING;
638 self#mark_as_needed sentence
639 | ProcessingIn _, None -> msg_wo_sent "ProcessingIn"
640 | Incomplete, Some (id, sentence) ->
641 log ?id "Incomplete";
642 add_flag sentence `INCOMPLETE;
643 self#mark_as_needed sentence
644 | Incomplete, None -> msg_wo_sent "Incomplete"
645 | Complete, Some (id, sentence) ->
646 log ?id "Complete";
647 remove_flag sentence `INCOMPLETE;
648 self#mark_as_needed sentence
649 | Complete, None -> msg_wo_sent "Complete"
650 | GlobRef(loc, filepath, modpath, ident, ty), Some (id,sentence) ->
651 log ?id "GlobRef";
652 self#attach_tooltip ~loc sentence
653 (Printf.sprintf "%s %s %s" filepath ident ty)
654 | GlobRef (_, _, _, _, _), None -> msg_wo_sent "GlobRef"
655 | Message(Error, loc, _, msg), Some (id,sentence) ->
656 log_pp ?id Pp.(str "ErrorMsg " ++ msg);
657 remove_flag sentence `PROCESSING;
658 let rmsg = Pp.string_of_ppcmds msg in
659 add_flag sentence (`ERROR (loc, rmsg));
660 self#mark_as_needed sentence;
661 self#attach_tooltip ?loc sentence rmsg;
662 self#apply_tag_in_sentence ?loc Tags.Script.error sentence
663 | Message(Warning, loc, _, message), Some (id,sentence) ->
664 log_pp ?id Pp.(str "WarningMsg " ++ message);
665 let rmsg = Pp.string_of_ppcmds message in
666 add_flag sentence (`WARNING (loc, rmsg));
667 self#attach_tooltip ?loc sentence rmsg;
668 self#apply_tag_in_sentence ?loc Tags.Script.warning sentence;
669 (messages#route msg.route)#push Warning message
670 | Message(lvl, loc, _, message), Some (id,sentence) ->
671 log_pp ?id Pp.(str "Msg " ++ message);
672 (messages#route msg.route)#push lvl message
673 (* We do nothing here as for BZ#5583 *)
674 | Message(Error, loc, _, msg), None ->
675 log_pp Pp.(str "Error Msg without a sentence" ++ msg)
676 | Message(lvl, loc, _, message), None ->
677 log_pp Pp.(str "Msg without a sentence " ++ message);
678 (messages#route msg.route)#push lvl message
679 | InProgress n, _ ->
680 if n < 0 then processed <- processed + abs n
681 else to_process <- to_process + n
682 | WorkerStatus(id,status), _ ->
683 log "WorkerStatus";
684 slaves_status <- CString.Map.add id status slaves_status
685 (* log unused feedback messages with a sentence *)
686 | GlobDef (_, _, _, _), _ -> unsupp_msg "GlobDef"
687 | FileDependency (_, _), _ -> unsupp_msg "FileDependency"
688 | FileLoaded (_, _), _ -> unsupp_msg "FileLoaded"
689 | Custom (_, _, _), _ -> unsupp_msg "Custom"
690 end
691 in
692 try match msg with
693 | MsgFeedback msg2 -> pr_feedback msg2
694 | MsgDebug (tag, msg2) ->
695 if tag = "prompt" then
696 RocqDriver.set_stopped_in_debugger _ct true;
697 self#debug_prompt ~tag msg2
698 with e -> (Printf.printf "Exception: %s\n%!" (Printexc.to_string e);
699 flush stdout;
700 raise e)
701
702 method private commit_queue_transaction sentence =
703 (* A queued command has been successfully done, we push it to [cmd_stack].
704 We reget the iters here because Gtk is unable to warranty that they
705 were not modified meanwhile. Not really necessary but who knows... *)
706 self#mark_as_needed sentence;
707 let stop = buffer#get_iter_at_mark sentence.stop in
708 buffer#move_mark ~where:stop (`NAME "start_of_input");
709
710 method private apply_tag_in_sentence ?loc tag sentence =
711 match loc with
712 | None ->
713 let start, stop = start_stop_iters buffer sentence in
714 buffer#apply_tag tag ~start ~stop
715 | Some loc ->
716 let _offset, line_drift = offset_compensation buffer sentence in
717 let start, stop = rocq_loc_to_gtk_offset ~line_drift buffer loc in
718 buffer#apply_tag tag ~start ~stop
719
720 method private process_interp_error ?loc queue sentence msg tip id =
721 RocqDriver.bind (RocqDriver.return ()) (function () ->
722 let start, stop = start_stop_iters buffer sentence in
723 buffer#remove_tag Tags.Script.to_process ~start ~stop;
724 self#discard_command_queue queue;
725 Ideutils.pop_info ();
726 if Stateid.equal id tip || Stateid.equal id Stateid.dummy then begin
727 self#attach_tooltip ?loc sentence (Pp.string_of_ppcmds msg);
728 self#apply_tag_in_sentence ?loc Tags.Script.error sentence;
729 buffer#place_cursor ~where:stop;
730 messages#default_route#clear;
731 messages#default_route#push Feedback.Error msg;
732 self#show_goals
733 end else
734 self#show_goals_aux ~move_insert:true ()
735 )
736
737 (** [fill_command_queue until q] fills a command queue until the [until]
738 condition returns true; it is fed with the number of phrases read and the
739 iters enclosing the current sentence. *)
740 method private fill_command_queue until queue =
741 let topstack =
742 if Doc.focused document then fst (Doc.context document) else [] in
743 let rec loop n iter prev_start =
744 (* prev_start is a workaround to avoid an endless loop. See #15873/#15984 *)
745 match Sentence.find buffer iter with
746 | None -> ()
747 | Some (start, stop) ->
748 if until n start stop then begin
749 ()
750 end else if
751 List.exists (fun (_, s) ->
752 start#equal (buffer#get_iter_at_mark s.start) &&
753 stop#equal (buffer#get_iter_at_mark s.stop)) topstack
754 then begin
755 Queue.push (`Skip (start, stop)) queue;
756 loop n stop start#offset
757 end else begin
758 buffer#apply_tag Tags.Script.to_process ~start ~stop;
759 let sentence =
760 let start_offset = start#offset in
761 let start_line = start#line in
762 let start = `MARK (buffer#create_mark start) in
763 let stop = `MARK (buffer#create_mark stop) in
764 mk_sentence ~start ~stop ~start_offset ~start_line []
765 in
766 Queue.push (`Sentence sentence) queue;
767 if start#offset <> prev_start && not stop#is_end then loop (succ n) stop start#offset
768 end
769 in
770 loop 0 self#get_start_of_input (-1)
771
772 method private discard_command_queue queue =
773 while not (Queue.is_empty queue) do
774 match Queue.pop queue with
775 | `Skip _ -> ()
776 | `Sentence sentence ->
777 let start = buffer#get_iter_at_mark sentence.start in
778 let stop = buffer#get_iter_at_mark sentence.stop in
779 buffer#remove_tag Tags.Script.to_process ~start ~stop;
780 buffer#delete_mark sentence.start;
781 buffer#delete_mark sentence.stop;
782 done
783
784 (** Compute the phrases until [until] returns [true]. *)
785 method private process_until ?move_insert until verbose =
786 let logger lvl msg = if verbose then messages#default_route#push lvl msg in
787 let fill_queue = RocqDriver.lift (fun () ->
788 let queue = Queue.create () in
789 (* Lock everything and fill the waiting queue *)
790 Ideutils.push_info "Coq is computing";
791 messages#default_route#clear;
792 script#set_editable false;
793 self#fill_command_queue until queue;
794 (* Now unlock and process asynchronously. Since [until]
795 may contain iterators, it shouldn't be used anymore *)
796 script#set_editable true;
797 Minilib.log "Begin command processing";
798 queue) in
799 let conclude topstack =
800 Ideutils.pop_info ();
801 script#recenter_insert;
802 match topstack with
803 | [] -> self#show_goals_aux ?move_insert ()
804 | (_,s)::_ -> self#backtrack_to_iter (buffer#get_iter_at_mark s.start) in
805 let process_queue queue =
806 let rec loop tip topstack =
807 if Queue.is_empty queue then conclude topstack else
808 match Queue.pop queue, topstack with
809 | `Skip(start,stop), [] ->
810 logger Feedback.Error (Pp.str "You must close the proof with Qed or Admitted");
811 self#discard_command_queue queue;
812 conclude []
813 | `Skip(start,stop), (_,s) :: topstack ->
814 assert(start#equal (buffer#get_iter_at_mark s.start));
815 assert(stop#equal (buffer#get_iter_at_mark s.stop));
816 loop tip topstack
817 | `Sentence sentence, _ :: _ -> assert false
818 | `Sentence ({ edit_id } as sentence), [] ->
819 add_flag sentence `PROCESSING;
820 Doc.push document sentence;
821 let phrase = phrase buffer sentence in
822 (* When we retract, the cached offsets are invalid, thus we need to reset the cache *)
823 let start = start_iter buffer sentence in
824 let cached_offset = if start#offset > (snd last_offsets) then last_offsets else (0,0) in
825 let bp, line_nb, bol_pos, new_cached = rocq_loc_from_gtk_offset cached_offset buffer sentence in
826 last_offsets <- new_cached;
827 let rocq_query = RocqDriver.add ((((phrase,edit_id),(tip,verbose)),bp),(line_nb,bol_pos)) in
828 Doc.set_errors document [];
829 let handle_answer = function
830 | Good (id, Util.Inl (* NewTip *) ()) ->
831 Doc.assign_tip_id document id;
832 self#commit_queue_transaction sentence;
833 loop id []
834 | Good (id, Util.Inr (* Unfocus *) tip) ->
835 Doc.assign_tip_id document id;
836 let topstack, _ = Doc.context document in
837 self#exit_focus;
838 self#cleanup (Doc.cut_at document tip);
839 self#mark_as_needed sentence;
840 if Queue.is_empty queue then loop tip []
841 else loop tip (List.rev topstack)
842 | Fail (id, loc, msg) ->
843 let sentence = Doc.pop document in
844 Doc.set_errors document [Pp.string_of_ppcmds msg];
845 self#process_interp_error ?loc queue sentence msg tip id in
846 RocqDriver.bind rocq_query handle_answer
847 in
848 let tip =
849 try Doc.tip document
850 with Doc.Empty -> initial_state | Invalid_argument _ -> assert false in
851 loop tip [] in
852 RocqDriver.bind fill_queue process_queue
853
854 method join_document =
855 let next = function
856 | Good _ ->
857 messages#default_route#clear;
858 messages#default_route#push
859 Feedback.Info (Pp.str "All proof terms checked by the kernel");
860 RocqDriver.return ()
861 | Fail x -> self#handle_failure x in
862 RocqDriver.bind (RocqDriver.status true) next
863
864 method stop_worker n =
865 RocqDriver.bind (RocqDriver.stop_worker n) (fun _ -> RocqDriver.return ())
866
867 method get_slaves_status = processed, to_process, slaves_status
868
869 method get_n_errors =
870 Doc.fold_all document 0 (fun n _ _ s -> if has_flag s `ERROR then n+1 else n)
871
872 method private get_flagged (f : flag -> (Loc.t option * string) option) =
873 let extract s =
874 let map item = match f item with
875 | None -> None
876 | Some (loc, msg) ->
877 let iter = match loc with
878 | None -> buffer#get_iter_at_mark s.start
879 | Some loc -> fst (rocq_loc_to_gtk_offset buffer loc)
880 in
881 Some (iter#line + 1, msg)
882 in
883 List.map_filter map s.flags
884 in
885 List.rev (Doc.fold_all document [] (fun acc _ _ s -> extract s @ acc))
886
887 method get_warnings =
888 let f (item : flag) = match item with
889 | `WARNING (loc, msg) -> Some (loc, msg)
890 | _ -> None
891 in
892 self#get_flagged f
893
894 method get_errors =
895 let f (item : flag) = match item with
896 | `ERROR (loc, msg) -> Some (loc, msg)
897 | _ -> None
898 in
899 self#get_flagged f
900
901 method process_next_phrase =
902 let until n _ _ = n >= 1 in
903 self#process_until ~move_insert:true until true
904
905 method process_db_cmd cmd ~next : unit RocqDriver.task =
906 let db_cmd = RocqDriver.db_cmd cmd in
907 RocqDriver.bind db_cmd next
908
909 method process_db_configd cmd ~next : unit RocqDriver.task =
910 let db_configd = RocqDriver.db_configd cmd in
911 RocqDriver.bind db_configd next
912
913 method process_db_upd_bpts updates ~next : unit RocqDriver.task =
914 let db_upd_bpts = RocqDriver.db_upd_bpts updates in
915 RocqDriver.bind db_upd_bpts next
916
917 method process_db_continue opt ~next : unit RocqDriver.task =
918 let db_continue = RocqDriver.db_continue opt in
919 RocqDriver.bind db_continue next
920
921 method process_db_stack ~next : unit RocqDriver.task =
922 let db_stack = RocqDriver.db_stack () in
923 RocqDriver.bind db_stack next
924
925 method process_db_vars framenum ~next : unit RocqDriver.task =
926 let db_vars = RocqDriver.db_vars framenum in
927 RocqDriver.bind db_vars next
928
929 method private process_until_iter iter =
930 let until _ start stop =
931 if Preferences.stop_before#get then stop#compare iter > 0
932 else start#compare iter >= 0
933 in
934 self#process_until until false
935
936 method process_until_end_or_error =
937 self#process_until_iter self#get_end_of_input
938
939 (* finds the state_id and if it an unfocus is needed to reach it *)
940 method private find_id until =
941 try
942 Doc.find_id document (fun id { start;stop } -> until (Some id) start stop)
943 with Not_found -> initial_state, Doc.focused document
944
945 method private cleanup seg =
946 if seg <> [] then begin
947 let start = buffer#get_iter_at_mark (CList.last seg).start in
948 let stop = buffer#get_iter_at_mark (CList.hd seg).stop in
949 Minilib.log
950 (Printf.sprintf "Cleanup in range %d -> %d" start#offset stop#offset);
951 buffer#remove_tag Tags.Script.processed ~start ~stop;
952 buffer#remove_tag Tags.Script.incomplete ~start ~stop;
953 buffer#remove_tag Tags.Script.unjustified ~start ~stop;
954 buffer#remove_tag Tags.Script.tooltip ~start ~stop;
955 buffer#remove_tag Tags.Script.to_process ~start ~stop;
956 buffer#move_mark ~where:start (`NAME "start_of_input")
957 end;
958 List.iter (fun { start } -> buffer#delete_mark start) seg;
959 List.iter (fun { stop } -> buffer#delete_mark stop) seg;
960 self#print_stack
961
962 (** Wrapper around the raw undo command *)
963 method private backtrack_to_id ?(move_insert=true) (to_id, unfocus_needed) =
964 Minilib.log("backtrack_to_id "^Stateid.to_string to_id^
965 " (unfocus_needed="^string_of_bool unfocus_needed^")");
966 let opening () =
967 Ideutils.push_info "Coq is undoing" in
968 let conclusion () =
969 Ideutils.pop_info ();
970 if move_insert then begin
971 buffer#place_cursor ~where:self#get_start_of_input;
972 script#recenter_insert;
973 end;
974 let start = self#get_start_of_input in
975 let stop = self#get_end_of_input in
976 Minilib.log(Printf.sprintf "cleanup tags %d %d" start#offset stop#offset);
977 buffer#remove_tag Tags.Script.tooltip ~start ~stop;
978 buffer#remove_tag Tags.Script.processed ~start ~stop;
979 buffer#remove_tag Tags.Script.incomplete ~start ~stop;
980 buffer#remove_tag Tags.Script.to_process ~start ~stop;
981 buffer#remove_tag Tags.Script.unjustified ~start ~stop;
982 self#show_goals in
983 RocqDriver.bind (RocqDriver.lift opening) (fun () ->
984 let rec undo to_id unfocus_needed =
985 RocqDriver.bind (RocqDriver.edit_at to_id) (function
986 | Good (CSig.Inl (* NewTip *) ()) ->
987 if unfocus_needed then self#exit_focus;
988 self#cleanup (Doc.cut_at document to_id);
989 conclusion ()
990 | Good (CSig.Inr (* Focus *) (stop_id,(start_id,tip))) ->
991 if unfocus_needed then self#exit_focus;
992 self#cleanup (Doc.cut_at document tip);
993 self#enter_focus start_id stop_id;
994 self#cleanup (Doc.cut_at document to_id);
995 conclusion ()
996 | Fail (safe_id, loc, msg) ->
997 (* if loc <> None then messages#push Feedback.Error (Richpp.richpp_of_string "Fixme LOC"); *)
998 messages#default_route#push Feedback.Error msg;
999 if Stateid.equal safe_id Stateid.dummy then self#show_goals
1000 else undo safe_id
1001 (Doc.focused document && Doc.is_in_focus document safe_id))
1002 in
1003 undo to_id unfocus_needed)
1004
1005 method backtrack_to_begin =
1006 let until (id : Doc.id option) _ stop = (id = (Some (Stateid.of_int 1))) in
1007 fun () -> self#backtrack_to_id ~move_insert:false (self#find_id until)
1008
1009 method private backtrack_until ?move_insert until =
1010 self#backtrack_to_id ?move_insert (self#find_id until)
1011
1012 method private backtrack_to_iter ?move_insert iter =
1013 let until _ _ stop = iter#compare (buffer#get_iter_at_mark stop) >= 0 in
1014 self#backtrack_until ?move_insert until
1015
1016 method private handle_failure_aux
1017 ?(move_insert=false) (safe_id, (loc : Interface.location), msg)
1018 =
1019 messages#default_route#push Feedback.Error msg;
1020 if Stateid.equal safe_id Stateid.dummy then RocqDriver.lift (fun () -> ())
1021 else
1022 RocqDriver.seq
1023 (self#backtrack_until ~move_insert
1024 (fun id _ _ -> id = Some safe_id))
1025 (RocqDriver.lift (fun () -> script#recenter_insert))
1026
1027 method handle_failure f = self#handle_failure_aux f
1028
1029 method backtrack_last_phrase =
1030 messages#default_route#clear;
1031 try
1032 let tgt = Doc.before_tip document in
1033 self#backtrack_to_id tgt
1034 with Not_found -> RocqDriver.return (RocqDriver.reset_rocqtop _ct)
1035
1036 method go_to_insert =
1037 RocqDriver.bind (RocqDriver.return ()) (fun () ->
1038 messages#default_route#clear;
1039 let point = self#get_insert in
1040 if point#compare self#get_start_of_input >= 0
1041 then self#process_until_iter point
1042 else self#backtrack_to_iter ~move_insert:false point)
1043
1044 method go_to_mark m =
1045 RocqDriver.bind (RocqDriver.return ()) (fun () ->
1046 messages#default_route#clear;
1047 let point = buffer#get_iter_at_mark m in
1048 if point#compare self#get_start_of_input >= 0
1049 then RocqDriver.seq (self#process_until_iter point)
1050 (RocqDriver.lift (fun () -> Sentence.tag_on_insert buffer))
1051 else RocqDriver.seq (self#backtrack_to_iter ~move_insert:false point)
1052 (RocqDriver.lift (fun () -> Sentence.tag_on_insert buffer)))
1053
1054 method handle_reset_initial =
1055 let action () =
1056 (* clear the stack *)
1057 if Doc.focused document then Doc.unfocus document;
1058 while not (Doc.is_empty document) do
1059 let phrase = Doc.pop document in
1060 buffer#delete_mark phrase.start;
1061 buffer#delete_mark phrase.stop
1062 done;
1063 List.iter
1064 (buffer#remove_tag ~start:buffer#start_iter ~stop:buffer#end_iter)
1065 Tags.Script.all_but_bpt;
1066 (* reset the buffer *)
1067 buffer#move_mark ~where:buffer#start_iter (`NAME "start_of_input");
1068 buffer#move_mark ~where:buffer#end_iter (`NAME "stop_of_input");
1069 Sentence.tag_all buffer;
1070 (* clear the views *)
1071 messages#default_route#clear;
1072 proof#clear ();
1073 Ideutils.clear_info ();
1074 processed <- 0;
1075 to_process <- 0;
1076 Ideutils.push_info "Restarted";
1077 (* apply the initial commands to rocq *)
1078 in
1079 RocqDriver.seq (RocqDriver.lift action) self#initialize
1080
1081 method initialize =
1082 let get_initial_state =
1083 let next = function
1084 | Fail (_, _, message) ->
1085 let message = "Couldn't initialize coqtop\n\n" ^ (Pp.string_of_ppcmds message) in
1086 let popup = GWindow.message_dialog ~buttons:GWindow.Buttons.ok ~message_type:`ERROR ~message () in
1087 ignore (popup#run ()); exit 1
1088 | Good id -> initial_state <- id; RocqDriver.return () in
1089 RocqDriver.bind (RocqDriver.init (get_filename ())) next in
1090 RocqDriver.seq get_initial_state RocqDriver.PrintOpt.enforce
1091
1092 end