Debian Codegraph @

engine/logic_monad.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 (** This file defines the low-level monadic operations used by the
12 tactic monad. The monad is divided into two layers: a non-logical
13 layer which consists in operations which will not (or cannot) be
14 backtracked in case of failure (input/output or persistent state)
15 and a logical layer which handles backtracking, proof
16 manipulation, and any other effect which needs to backtrack. *)
17
18
19 (** {6 Exceptions} *)
20
21
22 (** To help distinguish between exceptions raised by the IO monad from
23 the one used natively by Rocq, the former are wrapped in
24 [Exception]. It is only used internally so that [catch] blocks of
25 the IO monad would only catch exceptions raised by the [raise]
26 function of the IO monad, and not for instance, by system
27 interrupts. Also used in [Proofview] to avoid capturing exception
28 from the IO monad ([Proofview] catches errors in its compatibility
29 layer, and when lifting goal-level expressions). *)
30 exception Exception of exn
31
32 (** This exception is used to signal abortion in [timeout] functions. *)
33 exception Tac_Timeout
34
35 (** This exception is used by the tactics to signal failure by lack of
36 successes, rather than some other exceptions (like system
37 interrupts). *)
38 exception TacticFailure of exn
39
40 let _ = CErrors.register_handler begin function
41 | Exception e -> Some (CErrors.print e)
42 | TacticFailure e -> Some (CErrors.print e)
43 | _ -> None
44 end
45
46 (** {6 Non-logical layer} *)
47
48 (** The non-logical monad is a simple [unit -> 'a] (i/o) monad. The
49 operations are simple wrappers around corresponding usual
50 operations and require little documentation. *)
51 module NonLogical =
52 struct
53
54 (* The functions in this module follow the pattern that they are
55 defined with the form [(); fun ()->...]. This is an optimisation
56 which signals to the compiler that the function is usually partially
57 applied up to the [();]. Without this annotation, partial
58 applications can be significantly slower.
59
60 Documentation of this behaviour can be found at:
61 https://blog.janestreet.com/the-dangers-of-being-too-partial/ *)
62
63 include Monad.Make(struct
64 type 'a t = unit -> 'a
65
66 let return a = (); fun () -> a
67 let (>>=) a k = (); fun () -> k (a ()) ()
68 let (>>) a k = (); fun () -> a (); k ()
69 let map f a = (); fun () -> f (a ())
70 end)
71
72 type 'a ref = 'a Stdlib.ref
73
74 let ignore a = (); fun () -> ignore (a ())
75
76 let ref a = (); fun () -> ref a
77
78 (** [Pervasives.(:=)] *)
79 let (:=) r a = (); fun () -> r := a
80
81 (** [Pervasives.(!)] *)
82 let (!) = fun r -> (); fun () -> ! r
83
84 (** [Pervasives.raise]. Except that exceptions are wrapped with
85 {!Exception}. *)
86 let raise (e, info) () = Exninfo.iraise (Exception e, info)
87
88 (** [try ... with ...] but restricted to {!Exception}. *)
89 let catch = fun s h -> ();
90 fun () -> try s ()
91 with Exception e as src ->
92 let (src, info) = Exninfo.capture src in
93 h (e, info) ()
94
95 let read_line = fun () -> try read_line () with e ->
96 let (e, info) = Exninfo.capture e in
97 raise (e,info) ()
98
99 let print_char = fun c -> (); fun () -> print_char c
100
101 let timeout = fun n t -> (); fun () ->
102 Control.timeout n t ()
103
104 let make f = (); fun () ->
105 try f ()
106 with e when CErrors.noncritical e ->
107 let (e, info) = Exninfo.capture e in
108 Exninfo.iraise (Exception e, info)
109
110 (** Use the current logger. The buffer is also flushed. *)
111 let print_debug s = make (fun _ -> Feedback.msg_debug s)
112 let print_info s = make (fun _ -> Feedback.msg_info s)
113 let print_notice s = make (fun _ -> Feedback.msg_notice s)
114
115 let run = fun x ->
116 try x () with Exception e as src ->
117 let (src, info) = Exninfo.capture src in
118 Exninfo.iraise (e, info)
119 end
120
121 (** {6 Logical layer} *)
122
123 (** The logical monad is a backtracking monad on top of which is
124 layered a state monad (which is used to implement all of read/write,
125 read only, and write only effects). The state monad being layered on
126 top of the backtracking monad makes it so that the state is
127 backtracked on failure.
128
129 Backtracking differs from regular exception in that, writing (+)
130 for exception catching and (>>=) for bind, we require the
131 following extra distributivity laws:
132
133 x+(y+z) = (x+y)+z
134
135 zero+x = x
136
137 x+zero = x
138
139 (x+y)>>=k = (x>>=k)+(y>>=k) *)
140
141 (** A view type for the logical monad, which is a form of list, hence
142 we can decompose it with as a list. *)
143 type ('a, 'b, 'e) list_view_ =
144 | Nil of 'e
145 | Cons of 'a * 'b
146
147 type ('a, 'b, 'e) list_view = ('a, 'e -> 'b, 'e) list_view_
148
149 module BackState =
150 struct
151
152 (** Double-continuation backtracking monads are reasonable folklore
153 for "search" implementations (including the Tac interactive
154 prover's tactics). Yet it's quite hard to wrap your head around
155 these. I recommend reading a few times the "Backtracking,
156 Interleaving, and Terminating Monad Transformers" paper by
157 O. Kiselyov, C. Shan, D. Friedman, and A. Sabry. The peculiar
158 shape of the monadic type is reminiscent of that of the
159 continuation monad transformer.
160
161 The paper also contains the rationale for the [split] abstraction.
162
163 An explanation of how to derive such a monad from mathematical
164 principles can be found in "Kan Extensions for Program
165 Optimisation" by Ralf Hinze.
166
167 A somewhat concrete view is that the type ['a iolist] is, in fact
168 the impredicative encoding of the following stream type:
169
170 [type 'a _iolist' = Nil of exn | Cons of 'a*'a iolist'
171 and 'a iolist = 'a _iolist NonLogical.t]
172
173 Using impredicative encoding avoids intermediate allocation and
174 is, empirically, very efficient in Ocaml. It also has the
175 practical benefit that the monadic operation are independent of
176 the underlying monad, which simplifies the code and side-steps
177 the limited inlining of Ocaml.
178
179 In that vision, [bind] is simply [concat_map] (though the cps
180 version is significantly simpler), [plus] is concatenation, and
181 [split] is pattern-matching. *)
182
183 type ('a, 'i, 'o, 'e) t =
184 { iolist : 'r. 'i -> ('e -> 'r NonLogical.t) ->
185 ('a -> 'o -> ('e -> 'r NonLogical.t) -> 'r NonLogical.t) ->
186 'r NonLogical.t }
187
188 let return x =
189 { iolist = fun s nil cons -> cons x s nil }
190
191 let (>>=) m f =
192 { iolist = fun s nil cons ->
193 m.iolist s nil (fun x s next -> (f x).iolist s next cons) }
194
195 let (>>) m f =
196 { iolist = fun s nil cons ->
197 m.iolist s nil (fun () s next -> f.iolist s next cons) }
198
199 let map f m =
200 { iolist = fun s nil cons -> m.iolist s nil (fun x s next -> cons (f x) s next) }
201
202 let zero e =
203 { iolist = fun _ nil cons -> nil e }
204
205 let plus m1 m2 =
206 { iolist = fun s nil cons -> m1.iolist s (fun e -> (m2 e).iolist s nil cons) cons }
207
208 let ignore m =
209 { iolist = fun s nil cons -> m.iolist s nil (fun _ s next -> cons () s next) }
210
211 let lift m =
212 { iolist = fun s nil cons -> NonLogical.(m >>= fun x -> cons x s nil) }
213
214 (** State related *)
215
216 let get =
217 { iolist = fun s nil cons -> cons s s nil }
218
219 let set s =
220 { iolist = fun _ nil cons -> cons () s nil }
221
222 let modify f =
223 { iolist = fun s nil cons -> cons () (f s) nil }
224
225 (** Exception manipulation *)
226
227 let interleave src dst m =
228 { iolist = fun s nil cons ->
229 m.iolist s (fun e1 -> nil (src e1))
230 (fun x s next -> cons x s (fun e2 -> next (dst e2)))
231 }
232
233 (** List observation *)
234
235 let once m =
236 { iolist = fun s nil cons -> m.iolist s nil (fun x s _ -> cons x s nil) }
237
238 let break f m =
239 { iolist = fun s nil cons ->
240 m.iolist s nil (fun x s next -> cons x s (fun e -> match f e with None -> next e | Some e -> nil e))
241 }
242
243 (** For [reflect] and [split] see the "Backtracking, Interleaving,
244 and Terminating Monad Transformers" paper. *)
245 type ('a, 'e) reified = ('a, ('a, 'e) reified_, 'e) list_view_ NonLogical.t
246 and ('a, 'e) reified_ = {r : 'e -> ('a, 'e) reified} [@@unboxed]
247
248 let rec reflect (m : ('a * 'o, 'e) reified) =
249 { iolist = fun s0 nil cons ->
250 let next = function
251 | Nil e -> nil e
252 | Cons ((x, s), {r=l}) -> cons x s (fun e -> (reflect (l e)).iolist s0 nil cons)
253 in
254 NonLogical.(m >>= next)
255 }
256
257 let split m : (_ list_view, _, _, _) t =
258 let rnil e = NonLogical.return (Nil e) in
259 let rcons p s l = NonLogical.return (Cons ((p, s), {r=l})) in
260 { iolist = fun s nil cons ->
261 let open NonLogical in
262 m.iolist s rnil rcons >>= begin function
263 | Nil e -> cons (Nil e) s nil
264 | Cons ((x, s), {r=l}) ->
265 let l e = reflect (l e) in
266 cons (Cons (x, l)) s nil
267 end }
268
269 let run m s =
270 let rnil e = NonLogical.return (Nil e) in
271 let rcons x s l =
272 let p = (x, s) in
273 NonLogical.return (Cons (p, {r=l}))
274 in
275 m.iolist s rnil rcons
276
277 let repr x = x
278 end
279
280 module type Param = sig
281
282 (** Read only *)
283 type e
284
285 (** Write only *)
286 type w
287
288 (** [w] must be a monoid *)
289 val wunit : w
290 val wprod : w -> w -> w
291
292 (** Read-write *)
293 type s
294
295 (** Update-only. Essentially a writer on [u->u]. *)
296 type u
297
298 (** [u] must be pointed. *)
299 val uunit : u
300
301 end
302
303
304 module Logical (P:Param) =
305 struct
306
307 module Unsafe =
308 struct
309 (** All three of environment, writer and state are coded as a single
310 state-passing-style monad.*)
311 type state = {
312 rstate : P.e;
313 ustate : P.u;
314 wstate : P.w;
315 sstate : P.s;
316 }
317
318 let make m = m
319 let repr m = m
320 end
321
322 open Unsafe
323
324 type state = Unsafe.state
325
326 type iexn = Exninfo.iexn
327
328 type 'a reified = ('a, iexn) BackState.reified
329 type 'a reified_ = ('a, iexn) BackState.reified_
330
331 (** Inherited from Backstate *)
332
333 open BackState
334
335 include Monad.Make(struct
336 type 'a t = ('a, state, state, iexn) BackState.t
337 let return = BackState.return
338 let (>>=) = BackState.(>>=)
339 let (>>) = BackState.(>>)
340 let map = BackState.map
341 end)
342
343 let zero = BackState.zero
344 let plus = BackState.plus
345 let ignore = BackState.ignore
346 let lift = BackState.lift
347 let once = BackState.once
348 let break = BackState.break
349 let split = BackState.split
350 let repr = BackState.repr
351
352 (** State related. We specialize them here to ensure soundness (for reader and
353 writer) and efficiency. *)
354
355 let get =
356 { iolist = fun s nil cons -> cons s.sstate s nil }
357
358 let set (sstate : P.s) =
359 { iolist = fun s nil cons -> cons () { s with sstate } nil }
360
361 let modify (f : P.s -> P.s) =
362 { iolist = fun s nil cons -> cons () { s with sstate = f s.sstate } nil }
363
364 let current =
365 { iolist = fun s nil cons -> cons s.rstate s nil }
366
367 let local e m =
368 { iolist = fun s nil cons ->
369 m.iolist { s with rstate = e } nil
370 (fun x s' next -> cons x {s' with rstate = s.rstate} next) }
371
372 let put w =
373 { iolist = fun s nil cons -> cons () { s with wstate = P.wprod s.wstate w } nil }
374
375 let update (f : P.u -> P.u) =
376 { iolist = fun s nil cons -> cons () { s with ustate = f s.ustate } nil }
377
378 (** Monadic run is specialized to handle reader / writer *)
379
380 let run m r s =
381 let s = { wstate = P.wunit; ustate = P.uunit; rstate = r; sstate = s } in
382 let rnil e = NonLogical.return (Nil e) in
383 let rcons x s l =
384 let p = (x, s.sstate, s.wstate, s.ustate) in
385 NonLogical.return (Cons (p, {r=l}))
386 in
387 m.iolist s rnil rcons
388
389 end