Debian Codegraph @

plugins/ltac/tactic_debug.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 module StdList = List
12
13 open Util
14 open Names
15 open Pp
16 open Tacexpr
17
18 let (ltac_trace_info : ltac_stack Exninfo.t) = Exninfo.make "ltac_trace"
19
20 let prtac x =
21 let env = Global.env () in
22 Pptactic.pr_glob_tactic env x
23
24 (* This module intends to be a beginning of debugger for tactic expressions.
25 Currently, it is quite simple and we can hope to have, in the future, a more
26 complete panel of commands dedicated to a proof assistant framework *)
27
28 (* Debug information *)
29 type debug_info =
30 | DebugOn of int
31 | DebugOff
32
33 (* An exception handler *)
34 let explain_logic_error e = CErrors.print e
35 let explain_logic_error_no_anomaly e = CErrors.print_no_report e
36
37
38 type breakpoint = {
39 dirpath : string; (* module dirpath *)
40 offset : int;
41 }
42
43 module BPSet = CSet.Make(struct
44 type t = breakpoint
45 let compare b1 b2 =
46 let c1 = Int.compare b1.offset b2.offset in
47 if c1 <> 0 then c1 else String.compare b1.dirpath b2.dirpath
48 end)
49
50 let breakpoints = ref BPSet.empty
51
52
53 (** add or remove a single breakpoint. Maps the breakpoint from
54 IDE format (absolute path name, offset) to (module dirpath, offset)
55 opt - true to add, false to remove
56 ide_bpt - the breakpoint (absolute path name, offset)
57 *)
58 let update_bpt fname offset opt =
59 let open Names in
60 let dp =
61 if fname = "ToplevelInput" then (* todo: or None? *)
62 DirPath.make [Id.of_string "Top"]
63 else begin (* find the DirPath matching the absolute pathname of the file *)
64 (* ? check for .v extension? *)
65 let dirname = Filename.dirname fname in
66 let basename = Filename.basename fname in
67 let base_id = Id.of_string (Filename.remove_extension basename) in
68 DirPath.make (base_id ::
69 (try
70 let p = Loadpath.find_load_path (CUnix.physical_path_of_string dirname) in
71 DirPath.repr (Loadpath.logical p)
72 with exn when CErrors.noncritical exn -> []))
73 end
74 in
75 let dirpath = DirPath.to_string dp in
76 let bp = { dirpath; offset } in
77 (* Printf.printf "update_bpt: %s -> %s %d\n%!" fname dirpath ide_bpt.offset;*)
78 match opt with
79 | true -> breakpoints := BPSet.add bp !breakpoints
80 | false -> breakpoints := BPSet.remove bp !breakpoints
81
82 let upd_bpts updates =
83 List.iter (fun op ->
84 let ((file, offset), opt) = op in
85 update_bpt file offset opt;
86 ) updates
87
88 type debugger_state = {
89 (* location of next code to execute, is not in stack *)
90 mutable cur_loc : Loc.t option;
91 (* yields the call stack *)
92 mutable stack : (string * Loc.t option) list;
93 (* variable value maps for each stack frame *)
94 mutable varmaps : Geninterp.Val.t Names.Id.Map.t list;
95 }
96
97 let debugger_state = { cur_loc=None; stack=[]; varmaps=[] }
98
99 let get_stack () =
100 (* Printf.printf "server: db_stack call\n%!";*)
101 let rec shift s prev_loc res =
102 match s with
103 | (tacn, loc) :: tl ->
104 shift tl loc (((Some tacn), prev_loc) :: res)
105 | [] -> (None, prev_loc) :: res
106 in
107 List.rev (shift debugger_state.stack debugger_state.cur_loc [])
108
109 module CSet = CSet.Make (Names.DirPath)
110 let bad_dirpaths = ref CSet.empty
111
112 (* cvt_loc, format_frame and format_stack belong elsewhere *)
113 let cvt_loc loc =
114 let open Loc in
115 match loc with
116 | Some {fname=ToplevelInput; bp; ep} ->
117 Some ("ToplevelInput", [bp; ep])
118 | Some {fname=InFile {dirpath=None; file}; bp; ep} ->
119 Some (file, [bp; ep]) (* for Load command *)
120 | Some {fname=InFile {dirpath=(Some dirpath)}; bp; ep} ->
121 let open Names in
122 let dirpath = DirPath.make (List.rev_map (fun i -> Id.of_string i)
123 (String.split_on_char '.' dirpath)) in
124 let pfx = DirPath.make (List.tl (DirPath.repr dirpath)) in
125 let paths = Loadpath.find_with_logical_path pfx in
126 let basename = match DirPath.repr dirpath with
127 | hd :: tl -> (Id.to_string hd) ^ ".v"
128 | [] -> ""
129 in
130 let vs_files = List.map (fun p -> (Filename.concat (Loadpath.physical p) basename)) paths in
131 let filtered = List.filter (fun p -> Sys.file_exists p) vs_files in
132 begin match filtered with
133 | [] -> (* todo: maybe tweak this later to allow showing a popup dialog in the GUI *)
134 if not (CSet.mem dirpath !bad_dirpaths) then begin
135 bad_dirpaths := CSet.add dirpath !bad_dirpaths;
136 let msg = Pp.(fnl () ++ str "Unable to locate source code for module " ++
137 str (Names.DirPath.to_string dirpath)) in
138 let msg = if vs_files = [] then msg else
139 (List.fold_left (fun msg f -> msg ++ fnl() ++ str f) (msg ++ str " in:") vs_files) in
140 Feedback.msg_warning msg
141 end;
142 None
143 | [f] -> Some (f, [bp; ep])
144 | f :: tl ->
145 if not (CSet.mem dirpath !bad_dirpaths) then begin
146 bad_dirpaths := CSet.add dirpath !bad_dirpaths;
147 let msg = Pp.(fnl () ++ str "Multiple files found matching module " ++
148 str (Names.DirPath.to_string dirpath) ++ str ":") in
149 let msg = List.fold_left (fun msg f -> msg ++ fnl() ++ str f) msg vs_files in
150 Feedback.msg_warning msg
151 end;
152 Some (f, [bp; ep]) (* be arbitrary unless we can tell which file was loaded *)
153 end
154 | None -> None (* nothing to highlight, e.g. not in a .v file *)
155
156 let format_frame text loc =
157 try
158 let open Loc in
159 match loc with
160 | Some { fname=InFile {dirpath=(Some dp)}; line_nb } ->
161 let dplen = String.length dp in
162 let lastdot = String.rindex dp '.' in
163 let file = String.sub dp (lastdot+1) (dplen - (lastdot + 1)) in
164 let module_name = String.sub dp 0 lastdot in
165 let routine =
166 (* try text as a kername *)
167 if not (CString.is_prefix dp text) then text else
168 try
169 let knlen = String.length text in
170 let lastdot = String.rindex text '.' in
171 String.sub text (lastdot+1) (knlen - (lastdot + 1))
172 with Not_found -> text
173 in
174 Printf.sprintf "%s:%d, %s (%s)" routine line_nb file module_name;
175 | Some { fname=ToplevelInput; line_nb } ->
176 let items = String.split_on_char '.' text in
177 Printf.sprintf "%s:%d, %s" (List.nth items 1) line_nb (List.hd items);
178 | _ -> text
179 with Not_found -> text
180
181 let format_stack s =
182 List.map (fun (tac, loc) ->
183 let floc = cvt_loc loc in
184 match tac with
185 | Some tacn ->
186 let tacn = if loc = None then
187 tacn ^ " (no location)"
188 else
189 format_frame tacn loc in
190 (tacn, floc)
191 | None ->
192 match loc with
193 | Some { Loc.line_nb } ->
194 (":" ^ (string_of_int line_nb), floc)
195 | None -> (": (no location)", floc)
196 ) s
197
198
199 let get_vars framenum =
200 let open Names in
201 (* Printf.printf "server: db_vars call\n%!";*)
202 let vars = List.nth debugger_state.varmaps framenum in
203 List.map (fun b ->
204 let (id, v) = b in
205 (Id.to_string id, Pptactic.pr_value Constrexpr.LevelSome v)
206 ) (Id.Map.bindings vars)
207
208 [@@@ocaml.warning "-32"]
209 let cmd_to_str cmd =
210 let open DebugHook.Action in
211 match cmd with
212 | Continue -> "Continue"
213 | StepIn -> "StepIn"
214 | StepOver -> "StepOver"
215 | StepOut -> "StepOut"
216 | Skip -> "Skip"
217 | Interrupt -> "Interrput"
218 | Help -> "Help"
219 | UpdBpts _ -> "UpdBpts"
220 | Configd -> "Configd"
221 | GetStack -> "GetStack"
222 | GetVars _ -> "GetVars"
223 | RunCnt _ -> "RunCnt"
224 | RunBreakpoint _ -> "RunBreakpoint"
225 | Command _ -> "Command"
226 | Failed -> "Failed"
227 | Ignore -> "Ignore"
228 [@@@ocaml.warning "+32"]
229
230 let action = ref DebugHook.Action.StepOver
231
232 let break = ref false
233 (* causes the debugger to stop at the next step *)
234
235 let get_break () = !break
236 let set_break b = break := b
237
238 (* Communications with the outside world *)
239 module Comm = struct
240 let hook () = Option.get (DebugHook.Intf.get ())
241 let wrap = Proofview.NonLogical.make
242
243 (* TODO: ideally we would check that the debugger hooks are
244 correctly set, however we don't do this yet as debugger
245 initialization is unconditionally done for example in coqc.
246 Improving this would require some tweaks in tacinterp which
247 are out of scope for the current refactoring. *)
248 let init () =
249 let open DebugHook in
250 match Intf.get () with
251 | Some intf ->
252 if Intf.(intf.isTerminal) then
253 action := Action.StepIn
254 else begin
255 set_break false;
256 breakpoints := BPSet.empty;
257 (hook ()).Intf.submit_answer (Answer.Init);
258 while
259 let cmd = (hook ()).Intf.read_cmd () in
260 let open DebugHook.Action in
261 match cmd with
262 | UpdBpts updates -> upd_bpts updates; true
263 | Configd -> action := Action.Continue; false
264 | _ -> failwith "Action type not allowed"
265 do () done
266 end
267 | None -> ()
268 (* CErrors.user_err
269 * (Pp.str "Your user interface does not support the Ltac debugger.") *)
270
271 open DebugHook.Intf
272 open DebugHook.Answer
273
274 let prompt g = wrap (fun () -> (hook ()).submit_answer (Prompt g))
275 let goal g = wrap (fun () -> (hook ()).submit_answer (Goal g))
276 let output g = wrap (fun () -> (hook ()).submit_answer (Output g))
277
278 (* routines for deferring output; output is sent only if
279 the debugger stops at the next step *)
280 let out_queue = Queue.create ()
281 let defer_output f = wrap (fun () -> Queue.add f out_queue)
282 let print_deferred () = wrap (fun () ->
283 while not (Queue.is_empty out_queue)
284 do
285 (hook ()).submit_answer (Output ((Queue.pop out_queue) ()))
286 done)
287 let clear_queue () = wrap (fun () -> Queue.clear out_queue)
288
289 [@@@ocaml.warning "-32"]
290 let print g = (hook ()).submit_answer (Output (str g))
291 [@@@ocaml.warning "+32"]
292 let isTerminal () = (hook ()).isTerminal
293 let read = wrap (fun () ->
294 let rec l () =
295 let cmd = (hook ()).read_cmd () in
296 let open DebugHook.Action in
297 match cmd with
298 | Ignore -> l ()
299 | UpdBpts updates -> upd_bpts updates; l ()
300 | GetStack ->
301 ((hook)()).submit_answer (Stack (format_stack (get_stack ())));
302 l ()
303 | GetVars framenum ->
304 ((hook)()).submit_answer (Vars (get_vars framenum));
305 l ()
306 | _ -> action := cmd; cmd
307 in
308 l ())
309
310 end
311
312 let defer_output = Comm.defer_output
313
314 (* Prints the goal *)
315
316 let db_pr_goal gl =
317 let env = Proofview.Goal.env gl in
318 let sigma = Proofview.Goal.sigma gl in
319 let concl = Proofview.Goal.concl gl in
320 let penv = Termops.Internal.print_named_context env sigma in
321 let pc = Printer.pr_econstr_env env sigma concl in
322 str" " ++ hv 0 (penv ++ fnl () ++
323 str "============================" ++ fnl () ++
324 str" " ++ pc) ++ fnl () ++ fnl ()
325
326 let db_pr_goal =
327 let open Proofview in
328 let open Notations in
329 Goal.goals >>= fun gl ->
330 Monad.List.map (fun x -> x) gl >>= fun gls ->
331 let pg = str (CString.plural (List.length gls) "Goal") ++ str ":" ++ fnl () ++
332 Pp.seq (List.map db_pr_goal gls) in
333 Proofview.tclLIFT (Comm.goal pg)
334
335 (* Prints the commands *)
336 let help () =
337 Comm.output
338 (str "Commands: <Enter> = Step" ++ fnl() ++
339 str " h/? = Help" ++ fnl() ++
340 str " r <num> = Run <num> times" ++ fnl() ++
341 str " r <string> = Run up to next idtac <string>" ++ fnl() ++
342 str " s = Skip" ++ fnl() ++
343 str " x = Exit")
344
345 [@@@ocaml.warning "-32"]
346 let tac_loc tac =
347 let open Tacexpr in
348 let open CAst in
349 let loc, tac = tac.loc, tac.v in
350 let rv = match tac with
351 | TacAtom _ -> "TacAtom"
352 | TacThen _ -> "TacThen"
353 | TacDispatch _ -> "TacDispatch"
354 | TacExtendTac _ -> "TacExtendTac"
355 | TacThens _ -> "TacThens"
356 | TacThens3parts _ -> "TacThens3parts"
357 | TacFirst _ -> "TacFirst"
358 | TacSolve _ -> "TacSolve"
359 | TacTry _ -> "TacTry"
360 | TacOr _ -> "TacOr"
361 | TacOnce _ -> "TacOnce"
362 | TacExactlyOnce _ -> "TacExactlyOnce"
363 | TacIfThenCatch _ -> "TacIfThenCatch"
364 | TacOrelse _ -> "TacOrelse"
365 | TacDo _ -> "TacDo"
366 | TacTimeout _ -> "TacTimeout"
367 | TacTime _ -> "TacTime"
368 | TacRepeat _ -> "TacRepeat"
369 | TacProgress _ -> "TacProgress"
370 | TacAbstract _ -> "TacAbstract"
371 | TacId _ -> "TacId"
372 | TacFail _ -> "TacFail"
373 | TacLetIn _ -> "TacLetIn"
374 | TacMatch _ -> "TacMatch"
375 | TacMatchGoal _ -> "TacMatchGoal"
376 | TacFun _ -> "TacFun"
377 | TacArg _ -> "TacArg"
378 | TacSelect _ -> "TacSelect"
379 | TacML _ -> "TacML"
380 | TacAlias _ -> "TacAlias"
381 in
382 (* Printf.printf " %s\n%!" (fst rv);*)
383 rv, loc
384
385 let print_loc desc loc =
386 let open Loc in
387 match loc with
388 | Some loc ->
389 let src = (match loc.fname with
390 | InFile {file} -> file
391 | ToplevelInput -> "ToplevelInput")
392 in
393 Printf.sprintf "%s: %s %d/%d %d:%d\n" desc src loc.bp loc.line_nb
394 (loc.bp - loc.bol_pos_last) (loc.ep - loc.bol_pos_last)
395 | None -> Printf.sprintf "%s: loc is None" desc
396
397 let print_loc_tac tac =
398 let (desc, loc) = tac_loc tac in
399 print_loc desc loc
400 [@@@ocaml.warning "+32"]
401
402 let cvt_stack stack =
403 List.map (fun k ->
404 let (loc, k) = k in
405 (* todo: compare to explain_ltac_call_trace below *)
406 match k with
407 | LtacNameCall l -> KerName.to_string l, loc
408 | LtacMLCall _ -> "??? LtacMLCall", loc
409 (* LtacMLCall should not even show the stack frame, but profiling may need it *)
410 | LtacNotationCall l -> "??? LtacNotationCall", loc
411 (* LtacNotationCall should not even show the stack frame, but profiling may need it *)
412 | LtacAtomCall _ -> "??? LtacAtomCall", loc (* not found in stack *)
413 | LtacVarCall (kn, id, e) ->
414 let fn_name =
415 match kn with
416 | Some kn -> KerName.to_string kn
417 | None -> "" (* anonymous function *)
418 in
419 fn_name, loc
420 | LtacConstrInterp _ -> "", loc
421 ) stack
422
423 (* Each list entry contains multiple trace frames. *)
424 let trace_chunks : ltac_trace list ref = ref [([], [])]
425 let push_chunk trace = trace_chunks := trace :: !trace_chunks
426 let pop_chunk trace = trace_chunks := List.tl !trace_chunks
427
428 let prev_stack = ref (Some []) (* previous stopping point in debugger *)
429 let prev_trace_chunks : ltac_trace list ref = ref [([], [])]
430
431
432 let save_loc tac varmap trace =
433 (* Comm.print (print_loc_tac tac);*)
434 let stack, varmaps = match trace with
435 | Some (stack, varmaps) -> stack, varmaps
436 | None -> [], []
437 in
438 debugger_state.cur_loc <- CAst.(tac.loc);
439 let (pstack, pvars) = List.fold_right (fun (s,v) (os, ov) -> (s @ os), (v @ ov))
440 !trace_chunks ([],[]) in
441 debugger_state.stack <- cvt_stack (stack @ pstack);
442 debugger_state.varmaps <- varmap :: (varmaps @ pvars)
443
444 (* Prints the goal and the command to be executed *)
445 let goal_com tac varmap trace =
446 save_loc tac varmap trace;
447 Proofview.tclTHEN
448 db_pr_goal
449 (if Comm.isTerminal () || debugger_state.cur_loc = None then
450 (Proofview.tclLIFT (Comm.output (str "Going to execute:" ++ fnl () ++ prtac tac)))
451 else
452 Proofview.tclLIFT (Proofview.NonLogical.return ()))
453
454 (* [run (new_ref _)] gives us a ref shared among [NonLogical.t]
455 expressions. It avoids parameterizing everything over a
456 reference. *)
457 let skipped = Proofview.NonLogical.run (Proofview.NonLogical.ref 0)
458 let skip = Proofview.NonLogical.run (Proofview.NonLogical.ref 0)
459 let idtac_breakpt = Proofview.NonLogical.run (Proofview.NonLogical.ref None)
460 let idtac_bpt_stop = ref false
461
462 let batch = ref false
463
464 open Goptions
465
466 let () =
467 declare_bool_option
468 { optstage = Summary.Stage.Interp;
469 optdepr = None;
470 optkey = ["Ltac";"Batch";"Debug"];
471 optread = (fun () -> !batch);
472 optwrite = (fun x -> batch := x) }
473
474 (* (Re-)initialize debugger. is_tac controls whether to set the action *)
475 let db_initialize is_tac =
476 if Sys.os_type = "Unix" then
477 Sys.set_signal Sys.sigusr1 (Sys.Signal_handle
478 (fun _ -> set_break true));
479 let open Proofview.NonLogical in
480 let x = (skip:=0) >> (skipped:=0) >> (idtac_breakpt:=None) in
481 if is_tac then begin
482 idtac_bpt_stop.contents <- false;
483 make Comm.init >> x
484 end else x
485
486 (* Prints the run counter *)
487 let print_run_ctr print =
488 let open Proofview.NonLogical in
489 if print then
490 begin
491 !skipped >>= fun skipped ->
492 Comm.output (str "Executed expressions: " ++ int skipped ++ fnl())
493 end >>
494 !skipped >>= fun x ->
495 skipped := x+1
496 else
497 return ()
498
499 (* Prints the prompt *)
500 let rec prompt level =
501 let runnoprint = print_run_ctr false in
502 let open Proofview.NonLogical in
503 let nl = if Stdlib.(!batch) then "\n" else "" in
504 Comm.print_deferred () >>
505 Comm.prompt (tag "message.prompt"
506 @@ fnl () ++ str "TcDebug (" ++ int level ++ str (") > " ^ nl)) >>
507 if Stdlib.(!batch) && Comm.isTerminal () then return (DebugOn (level+1)) else
508 let exit = (skip:=0) >> (skipped:=0) >> raise (Sys.Break, Exninfo.null) in
509 Comm.read >>= fun inst ->
510 let open DebugHook.Action in
511 match inst with
512 | Continue
513 | StepIn
514 | StepOver
515 | StepOut -> return (DebugOn (level+1))
516 | Skip -> return DebugOff
517 | Interrupt -> Proofview.NonLogical.print_char '\b' >> exit (* todo: why the \b? *)
518 | Help -> help () >> prompt level
519 | UpdBpts updates -> failwith "UpdBpts" (* handled in init() loop *)
520 | Configd -> failwith "Configd" (* handled in init() loop *)
521 | GetStack -> failwith "GetStack" (* handled in read() loop *)
522 | GetVars _ -> failwith "GetVars" (* handled in read() loop *)
523 | RunCnt num -> (skip:=num) >> (skipped:=0) >>
524 runnoprint >> return (DebugOn (level+1))
525 | RunBreakpoint s -> (idtac_breakpt:=(Some s)) >> (* todo: look in Continue? *)
526 runnoprint >> return (DebugOn (level+1))
527 | Command _ -> failwith "Command" (* not possible *)
528 | Failed -> prompt level
529 | Ignore -> failwith "Ignore" (* not possible *)
530
531 let at_breakpoint tac =
532 let open Loc in
533 let check_bpt dirpath offset =
534 (* Printf.printf "In tactic_debug, dirpath = %s offset = %d\n%!" dirpath offset;*)
535 BPSet.mem { dirpath; offset } !breakpoints
536 in
537 match CAst.(tac.loc) with
538 | Some {fname=InFile {dirpath=Some dirpath}; bp} -> check_bpt dirpath bp
539 | Some {fname=ToplevelInput; bp} -> check_bpt "Top" bp
540 | _ -> false
541
542 [@@@ocaml.warning "-32"]
543 open Tacexpr
544
545 let pr_call_kind n k =
546 let (loc, k) = k in
547 let kind = (match k with
548 | LtacMLCall _ -> "LtacMLCall"
549 | LtacNotationCall _ -> "LtacNotationCall"
550 | LtacNameCall l ->
551 let name = (KerName.to_string l) ^ (print_loc "" loc) in
552 Printf.printf "%s\n%!" name; Feedback.msg_notice (Pp.str name); "LtacNameCall"
553 | LtacAtomCall _ -> "LtacAtomCall"
554 | LtacVarCall _ -> "LtacVarCall"
555 | LtacConstrInterp _ -> "LtacConstrInterp") in
556 Printf.printf "stack %d: %s\n%!" n kind
557
558 let dump_stack msg stack =
559 match stack with
560 | Some stack ->
561 Printf.printf "%s: stack len = %d\n" msg (StdList.length stack);
562 StdList.iteri pr_call_kind stack;
563 | None -> ()
564
565 let dump_varmaps msg varmaps =
566 match varmaps with
567 | Some varmaps ->
568 List.iter (fun varmap ->
569 Printf.printf "%s: varmap len = %d\n" msg (Id.Map.cardinal varmap);
570 List.iter (fun b ->
571 let (k, b) = b in
572 Printf.printf "id = %s\n%!" (Id.to_string k);
573 ignore @@ Pptactic.pr_value Constrexpr.LevelSome b (* todo: LevelSome?? *)
574 (* b is Geninterp.Val.t Names.Id.Map.t *)
575 ) (Id.Map.bindings varmap)
576 ) varmaps
577 | None -> ()
578 [@@@ocaml.warning "+32"]
579
580 (* Prints the state and waits for an instruction *)
581 (* spiwack: the only reason why we need to take the continuation [f]
582 as an argument rather than returning the new level directly seems to
583 be that [f] is wrapped in with "explain_logic_error". I don't think
584 it serves any purpose in the current design, so we could just drop
585 that. *)
586 let debug_prompt lev tac f varmap trace =
587 (* trace omits the currently-running tactic, so add separately *)
588 let stack, varmaps = match trace with
589 | Some (stack, varmaps) -> Some stack, Some (varmap :: varmaps)
590 | None -> None, Some [varmap] in
591 let runprint = print_run_ctr true in
592 let open Proofview.NonLogical in
593 let (>=) = Proofview.tclBIND in
594 (* What to print and to do next *)
595 let newlevel =
596 Proofview.tclLIFT !skip >= fun s ->
597 let stop_here () =
598 (* dump_stack "at debug_prompt" stack;*)
599 (* dump_varmaps "at debug_prompt" varmaps;*)
600 prev_stack.contents <- stack;
601 prev_trace_chunks.contents <- trace_chunks.contents;
602 Proofview.tclTHEN (goal_com tac varmap trace) (Proofview.tclLIFT (prompt lev))
603 in
604 let stacks_info stack p_stack =
605 (* performance impact? *)
606 let st_chunks = StdList.map (fun (s, _) -> s) trace_chunks.contents in
607 let st = StdList.concat ((Option.default [] stack) :: st_chunks) in
608 let prev_st_chunks = StdList.map (fun (s, _) -> s) prev_trace_chunks.contents in
609 let st_prev = StdList.concat ((Option.default [] p_stack) :: prev_st_chunks) in
610 let l_cur, l_prev = StdList.length st, StdList.length st_prev in
611 st, st_prev, l_cur, l_prev
612 in
613 let p_stack = prev_stack.contents in
614 if action.contents = DebugHook.Action.Continue && at_breakpoint tac then
615 (* todo: skip := 0 *)
616 stop_here ()
617 else if get_break () then begin
618 set_break false;
619 stop_here ()
620 end else if s = 1 then begin
621 Proofview.tclLIFT ((skip := 0) >> runprint) >=
622 (fun () -> stop_here ())
623 end else if s > 0 then
624 Proofview.tclLIFT ((skip := s-1) >>
625 runprint >>
626 !skip >>= fun new_skip ->
627 (if new_skip = 0 then skipped := 0 else return ()) >>
628 return (DebugOn (lev+1)))
629 else if idtac_bpt_stop.contents then begin
630 idtac_bpt_stop.contents <- false;
631 stop_here ()
632 end else
633 Proofview.tclLIFT !idtac_breakpt >= fun idtac_breakpt ->
634 if Option.has_some idtac_breakpt then
635 Proofview.tclLIFT(runprint >> return (DebugOn (lev+1)))
636 else begin
637 let open DebugHook.Action in
638 let stop = match action.contents with
639 | Continue -> false
640 | StepIn -> true
641 | StepOver -> let st, st_prev, l_cur, l_prev = stacks_info stack p_stack in
642 if l_cur = 0 || l_cur < l_prev then true (* stepped out *)
643 else if l_prev = 0 (*&& l_cur > 0*) then false
644 else
645 let peq = StdList.nth st (l_cur - l_prev) == (StdList.hd st_prev) in
646 (l_cur > l_prev && (not peq)) || (* stepped out *)
647 (l_cur = l_prev && peq) (* stepped over *)
648 | StepOut -> let st, st_prev, l_cur, l_prev = stacks_info stack p_stack in
649 if l_cur < l_prev then true
650 else if l_prev = 0 then false
651 else
652 StdList.nth st (l_cur - l_prev) != (StdList.hd st_prev)
653 | Skip | RunCnt _ | RunBreakpoint _ -> false (* handled elsewhere *)
654 | _ -> failwith "action op"
655 in
656 if stop then begin
657 stop_here ()
658 end else
659 Proofview.tclLIFT (Comm.clear_queue () >>
660 return (DebugOn (lev+1)))
661 end
662 in
663 newlevel >= fun newlevel ->
664 (* What to execute *)
665 Proofview.tclOR
666 (f newlevel)
667 begin fun (reraise, info) ->
668 Proofview.tclTHEN
669 (Proofview.tclLIFT begin
670 (skip:=0) >> (skipped:=0) >>
671 Comm.defer_output (fun () -> str "Level " ++ int lev ++ str ": " ++ explain_logic_error reraise)
672 end)
673 (Proofview.tclZERO ~info reraise)
674 end
675
676 let is_debug db =
677 let open Proofview.NonLogical in
678 !idtac_breakpt >>= fun idtac_breakpt ->
679 match db, idtac_breakpt with
680 | DebugOff, _ -> return false
681 | _, Some _ -> return false
682 | _ ->
683 !skip >>= fun skip ->
684 return (skip = 0)
685
686 (* Prints a constr *)
687 let db_constr debug env sigma c =
688 let open Proofview.NonLogical in
689 is_debug debug >>= fun db ->
690 if db then
691 Comm.defer_output (fun () -> str "Evaluated term: " ++ Printer.pr_econstr_env env sigma c)
692 else return ()
693
694 let is_breakpoint brkname s = match brkname, s with
695 | Some s, MsgString s'::_ -> String.equal s s'
696 | _ -> false
697
698 let db_breakpoint debug s =
699 let open Proofview.NonLogical in
700 !idtac_breakpt >>= fun opt_breakpoint ->
701 match debug with
702 | DebugOn lev when not (CList.is_empty s) && is_breakpoint opt_breakpoint s ->
703 idtac_bpt_stop.contents <- true;
704 idtac_breakpt:=None
705 | _ ->
706 return ()
707
708 (** Extracting traces *)
709
710 let is_defined_ltac trace =
711 let rec aux = function
712 | (_, Tacexpr.LtacNameCall f) :: _ -> not (Tacenv.is_ltac_for_ml_tactic f)
713 | (_, Tacexpr.LtacNotationCall f) :: _ -> true
714 | (_, Tacexpr.LtacAtomCall _) :: _ -> false
715 | _ :: tail -> aux tail
716 | [] -> false in
717 aux (List.rev trace)
718
719 let explain_ltac_call_trace last trace =
720 let calls = last :: List.rev_map snd trace in
721 let pr_call ck = match ck with
722 | Tacexpr.LtacNotationCall kn -> quote (Pptactic.pr_alias_key kn)
723 | Tacexpr.LtacNameCall cst -> quote (Pptactic.pr_ltac_constant cst)
724 | Tacexpr.LtacMLCall t ->
725 quote (prtac t)
726 | Tacexpr.LtacVarCall (_,id,t) ->
727 quote (Id.print id) ++ strbrk " (bound to " ++
728 prtac t ++ str ")"
729 | Tacexpr.LtacAtomCall te ->
730 quote (prtac (CAst.make (Tacexpr.TacAtom te)))
731 | Tacexpr.LtacConstrInterp (env, sigma, c, { Ltac_pretype.ltac_constrs = vars }) ->
732 quote (Printer.pr_glob_constr_env env sigma c) ++
733 (if not (Id.Map.is_empty vars) then
734 strbrk " (with " ++
735 prlist_with_sep pr_comma
736 (fun (id,c) ->
737 Id.print id ++ str ":=" ++ Printer.pr_lconstr_under_binders_env env sigma c)
738 (List.rev (Id.Map.bindings vars)) ++ str ")"
739 else mt())
740 in
741 match calls with
742 | [] -> mt ()
743 | [a] -> hov 0 (str "Ltac call to " ++ pr_call a ++ str " failed.")
744 | _ ->
745 let kind_of_last_call = match List.last calls with
746 | Tacexpr.LtacConstrInterp _ -> ", last term evaluation failed."
747 | _ -> ", last call failed."
748 in
749 hov 0 (str "In nested Ltac calls to " ++
750 pr_enum pr_call calls ++ strbrk kind_of_last_call)
751
752 let skip_extensions trace =
753 let rec aux = function
754 | (_,Tacexpr.LtacNotationCall _ as tac) :: (_,Tacexpr.LtacMLCall _) :: tail ->
755 (* Case of an ML defined tactic with entry of the form <<"foo" args>> *)
756 (* see tacextend.mlp *)
757 tac :: aux tail
758 | t :: tail -> t :: aux tail
759 | [] -> [] in
760 List.rev (aux (List.rev trace))
761
762 let extract_ltac_trace trace =
763 let trace = skip_extensions trace in
764 let (_,c),tail = List.sep_last trace in
765 if is_defined_ltac trace then
766 (* We entered a user-defined tactic,
767 we display the trace with location of the call *)
768 let msg = hov 0 (explain_ltac_call_trace c tail ++ fnl()) in
769 msg
770 else
771 mt ()
772
773 let get_ltac_trace info =
774 let ltac_trace = Exninfo.get info ltac_trace_info in
775 match ltac_trace with
776 | None -> None
777 | Some trace -> Some (extract_ltac_trace trace)
778
779 let () = CErrors.register_additional_error_info get_ltac_trace