Debian Codegraph @

vernac/vernacControl.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 type 'e profile_state_gen = {
12 events : 'e;
13 sums : NewProfile.sums;
14 counters : NewProfile.Counters.t;
15 }
16
17 type profile_state = NewProfile.MiniJson.t list list profile_state_gen
18
19 let empty_profstate = {
20 events = [];
21 sums = NewProfile.empty_sums;
22 counters = NewProfile.Counters.zero;
23 }
24
25 (** Partially interpreted control flags.
26
27 [ControlTime {duration}] means "Time" where the
28 partial interpretation has already take [duration].
29
30 In [ControlRedirect], [truncate] tells whether we should truncate
31 the file before printing (ie [false] if not the first phase).
32 Alternatively we could do [ControlRedirect of out_channel],
33 but that risks leaking open channels.
34
35 [ControlFail {st}] means "Fail" where the partial interpretation
36 did not fail and produced state [st].
37
38 [ControlSucceed {st}] means "Succeed" where the partial
39 interpretation succeeded and produced state [st].
40 *)
41 type 'state control_entry =
42 | ControlTime of { duration: System.duration }
43 | ControlInstructions of { instructions: System.instruction_count }
44 | ControlProfile of { to_file : string option; profstate : profile_state }
45 | ControlRedirect of { fname : string; truncate : bool}
46 | ControlTimeout of { remaining : float }
47 | ControlFail of { st : 'state }
48 | ControlSucceed of { st : 'state }
49
50 type 'state control_entries = 'state control_entry list
51
52 let check_timeout_f n =
53 if n <= 0. then CErrors.user_err Pp.(str "Timeout must be > 0.")
54
55 let with_measure measure add fmt flag init f =
56 let result = measure f () in
57 let result = match result with
58 | Ok (v,d) -> Ok (v, add init d)
59 | Error (e,d) -> Error (e, add init d)
60 in
61 begin match result with
62 | Ok (v,result) -> Some (flag result, v)
63 | Error (e,_) ->
64 Feedback.msg_notice @@ fmt result;
65 Exninfo.iraise e
66 end
67
68 let measure_profile f () =
69 let start_cnt = NewProfile.Counters.get() in
70 let events, sums, v = NewProfile.with_profiling (fun () ->
71 try Ok (f ())
72 with e -> Error (Exninfo.capture e))
73 in
74 let counters = NewProfile.Counters.(get() - start_cnt) in
75 let prof = { events=events; sums; counters } in
76 match v with
77 | Ok v -> Ok (v,prof)
78 | Error e -> Error (e, prof)
79
80 let add_profile a b = {
81 events = if CList.is_empty b.events then a.events else b.events :: a.events;
82 sums = NewProfile.sums_union a.sums b.sums;
83 counters = NewProfile.Counters.(a.counters + b.counters);
84 }
85
86 let fmt_profiling counters (sums:NewProfile.sums) =
87 let open Pp in
88 let sums = CString.Map.bindings sums in
89 let sums = List.sort (fun (_,(t1,_)) (_,(t2,_)) -> Float.compare t2 t1) sums in
90 let longest = List.fold_left (fun longest (name,_) -> max longest (String.length name)) 0 sums in
91 let pr_one (name,(time,cnt)) =
92 hov 1
93 (str name ++ str ":" ++ brk (1 + longest - String.length name, 0) ++
94 str (Format.asprintf "%a" NewProfile.pptime time) ++
95 pr_comma () ++ int cnt ++ str " calls")
96 in
97 v 0 (
98 NewProfile.Counters.print counters ++ spc() ++ spc() ++
99 prlist_with_sep spc pr_one sums)
100
101 (* Output comma and newline separated events given as a list of nonempty lists.
102 The last event is not followed by a comma. *)
103 let rec output_events fmt = function
104 | [] -> ()
105 | [[last]] -> Format.fprintf fmt "%a\n" NewProfile.MiniJson.pr last
106 | [] :: rest -> assert false
107 | (current :: next) :: rest ->
108 Format.fprintf fmt "%a,\n" NewProfile.MiniJson.pr current;
109 match next with
110 | [] -> output_events fmt rest
111 | _::_ -> output_events fmt (next :: rest)
112
113 let fmt_profile to_file v =
114 let {events;sums;counters} = match v with
115 | Ok (_,x) -> x
116 | Error (_,x) -> x
117 in
118 to_file |> Option.iter (fun to_file ->
119 let to_file = System.get_output_path (to_file ^ ".json") in
120 let f = open_out to_file in
121 let fmt = Format.formatter_of_out_channel f in
122 NewProfile.format_header fmt;
123 output_events fmt events;
124 NewProfile.format_footer fmt;
125 close_out f
126 );
127 fmt_profiling counters sums
128
129 (* do not reuse Control.Timeout: once we hit the timeout handler the
130 exn becomes a regular, noncritical error *)
131 exception CmdTimeout
132
133 let () = CErrors.register_handler (function
134 | CmdTimeout -> Some Pp.(str "Timeout!")
135 | _ -> None)
136
137 let with_timeout ~timeout:n f =
138 check_timeout_f n;
139 let start = Unix.gettimeofday () in
140 begin match Control.timeout n f () with
141 | Error info -> Exninfo.iraise (CmdTimeout, info)
142 | Ok v ->
143 let stop = Unix.gettimeofday () in
144 let remaining = n -. (stop -. start) in
145 if remaining <= 0. then raise CmdTimeout
146 else Some (ControlTimeout { remaining }, v)
147 end
148
149 let real_error_loc ~cmdloc ~eloc =
150 if Loc.finer eloc cmdloc then eloc
151 else cmdloc
152
153 (* Restoring the state is the caller's responsibility *)
154 let with_fail f : (Loc.t option * Pp.t, 'a) result =
155 try
156 let x = f () in
157 Error x
158 with
159 | e ->
160 (* The error has to be printed in the failing state *)
161 let _, info as exn = Exninfo.capture e in
162 (* Don't catch async exceptions, don't turn anomalies into successes *)
163 if CErrors.is_async e || CErrors.is_sync_anomaly e then Exninfo.iraise exn;
164 Ok (Loc.get_loc info, CErrors.iprint exn)
165
166 type ('st0,'st) with_local_state = { with_local_state : 'a. 'st0 -> (unit -> 'a) -> 'st * 'a }
167
168 let trivial_state = { with_local_state = fun () f -> (), f () }
169
170 let with_fail ~loc ~with_local_state st0 f =
171 let transient_st, res = with_local_state.with_local_state st0 (fun () -> with_fail f) in
172 match res with
173 | Error v ->
174 Some (ControlFail { st = transient_st }, v)
175 | Ok (eloc, msg) ->
176 let loc = if !Flags.test_mode then real_error_loc ~cmdloc:loc ~eloc else None in
177 if not !Flags.quiet || !Flags.test_mode
178 then Feedback.msg_notice ?loc Pp.(str "The command has indeed failed with message:" ++ fnl () ++ msg);
179 None
180
181 let with_succeed ~with_local_state st0 f =
182 let transient_st, v = with_local_state.with_local_state st0 f in
183 Some (ControlSucceed { st = transient_st }, v)
184
185 let under_one_control ~loc ~with_local_state control f =
186 match control with
187 | ControlTime { duration } ->
188 with_measure System.measure_duration System.duration_add System.fmt_transaction_result
189 (fun duration -> ControlTime {duration})
190 duration
191 f
192 | ControlInstructions {instructions} ->
193 with_measure System.count_instructions System.instruction_count_add System.fmt_instructions_result
194 (fun instructions -> ControlInstructions {instructions})
195 instructions
196 f
197 | ControlProfile {to_file; profstate} ->
198 with_measure measure_profile add_profile (fun v -> fmt_profile to_file v)
199 (fun profstate -> ControlProfile {to_file; profstate})
200 profstate
201 f
202 | ControlRedirect { fname; truncate } ->
203 let v = Topfmt.with_output_to_file ~truncate fname f () in
204 Some (ControlRedirect {fname; truncate=false}, v)
205 | ControlTimeout {remaining} -> with_timeout ~timeout:remaining f
206 | ControlFail {st} -> with_fail ~loc ~with_local_state st f
207 | ControlSucceed {st} -> with_succeed ~with_local_state st f
208
209 let rec under_control ~loc ~with_local_state controls ~noop f =
210 match controls with
211 | [] -> [], f ()
212 | control :: rest ->
213 let f () = under_control ~loc ~with_local_state rest ~noop f in
214 match under_one_control ~loc ~with_local_state control f with
215 | Some (control, (rest,v)) -> control :: rest, v
216 | None -> [], noop
217
218 let ignore_state = { with_local_state = fun _ f -> (), f () }
219
220 let rec after_last_phase ~loc = function
221 | [] -> false
222 | control :: rest ->
223 (* don't match on [control] before processing [rest]: correctly handle eg [Fail Fail]. *)
224 let rest () = after_last_phase ~loc rest in
225 match under_one_control ~loc ~with_local_state:ignore_state control rest with
226 | None -> true
227 | Some (control,noop) ->
228 match control with
229 | ControlTime {duration} ->
230 Feedback.msg_notice @@ System.fmt_transaction_result (Ok ((),duration));
231 noop
232 | ControlInstructions {instructions} ->
233 Feedback.msg_notice @@ System.fmt_instructions_result (Ok ((),instructions));
234 noop
235 | ControlProfile {to_file; profstate} ->
236 Feedback.msg_notice @@ fmt_profile to_file (Ok ((),profstate));
237 noop
238 | ControlRedirect _ -> noop
239 | ControlTimeout _ -> noop
240 | ControlFail _ -> CErrors.user_err Pp.(str "The command has not failed!")
241 | ControlSucceed _ -> true
242
243 (** A global default timeout, controlled by option "Set Default Timeout n".
244 Use "Unset Default Timeout" to deactivate it. *)
245
246 let default_timeout = ref None
247
248 let check_timeout n =
249 if n <= 0 then CErrors.user_err Pp.(str "Timeout must be > 0.")
250
251 let () = let open Goptions in
252 declare_int_option
253 { optstage = Summary.Stage.Synterp;
254 optdepr = None;
255 optkey = ["Default";"Timeout"];
256 optread = (fun () -> !default_timeout);
257 optwrite = (fun n -> Option.iter check_timeout n; default_timeout := n) }
258
259 let has_timeout ctrl = ctrl |> List.exists (function
260 | { CAst.v = Vernacexpr.ControlTimeout _ } -> true
261 | _ -> false)
262
263 let add_default_timeout control =
264 match !default_timeout with
265 | None -> control
266 | Some n ->
267 if has_timeout control then control
268 else CAst.make (Vernacexpr.ControlTimeout n) :: control
269
270 let from_syntax_one : Vernacexpr.control_flag -> unit control_entry = fun flag ->
271 match flag.v with
272 | ControlTime -> ControlTime { duration = System.empty_duration }
273 | ControlInstructions -> ControlInstructions { instructions = Ok 0L }
274 | ControlProfile to_file -> ControlProfile {to_file; profstate = empty_profstate}
275 | ControlRedirect s -> ControlRedirect { fname = s; truncate = true }
276 | ControlTimeout timeout ->
277 (* don't check_timeout here as the error won't be caught by surrounding Fail *)
278 ControlTimeout { remaining = float_of_int timeout }
279 | ControlFail -> ControlFail { st = () }
280 | ControlSucceed -> ControlSucceed { st = () }
281
282 let from_syntax control = List.map from_syntax_one (add_default_timeout control)