Debian Codegraph @

src/Util/DebugMonad.v

raw
1 From Coq Require Import String.
2 From Coq Require Import List.
3 Require Import Crypto.Util.Notations.
4 Require Export Crypto.Util.GlobalSettings.
5 Require Export Crypto.Util.FixCoqMistakes.
6 Import ListNotations.
7
8 Local Set Boolean Equality Schemes.
9 Local Set Decidable Equality Schemes.
10 Local Set Implicit Arguments.
11 Module tree. (* for efficient debugging at various depths *)
12 Section tree.
13 Context (T : Type).
14 Inductive t := empty | singleton (_ : T) | app (_ _ : t).
15 (* deduplicates empties *)
16 Definition smart_app (x y : t)
17 := match x, y with
18 | empty, _ => y
19 | _, empty => x
20 | _, _ => app x y
21 end.
22 Definition fold {A} (f : T -> A -> A) :=
23 fix fold (v : t) (init : A) : A
24 := match v with
25 | empty => init
26 | singleton v => f v init
27 | app l r => fold l (fold r init)
28 end.
29 Definition to_list (v : t) : list T := fold (@cons _) v nil.
30 End tree.
31 Global Arguments empty {_}.
32 End tree.
33 Definition DebugM {dbg} (T : Type) : Type := (tree.t (unit -> list dbg)) * T.
34 Global Arguments DebugM {_} _, _ _.
35 Declare Scope debugM_scope.
36 Delimit Scope debugM_scope with debugM.
37 Bind Scope debugM_scope with DebugM.
38 Module Debug.
39 Definition debug' {dbg} : (unit -> list dbg) -> DebugM unit
40 := fun msg => (tree.singleton msg, tt).
41 Notation debug v := (debug' (fun 'tt => v)).
42 Local Notation eta x := (fst x, snd x).
43 Definition bind {dbg A B} (x : DebugM A) (k : A -> DebugM B) : @DebugM dbg B
44 := let x := x in
45 let '(dbg1, a) := eta x in
46 let ka := k a in
47 let '(dbg2, b) := eta ka in
48 (tree.smart_app dbg1 dbg2, b).
49 Definition sequence {dbg A} (x : DebugM unit) (k : DebugM A) : @DebugM dbg A
50 := bind x (fun 'tt => k).
51 Definition map {dbg A B} (f : A -> B) (x : DebugM A) : @DebugM dbg B
52 := let x := x in
53 let '(dbg, a) := eta x in
54 (dbg, f a).
55 Definition ret {dbg A} (a : A) : @DebugM dbg A
56 := (tree.empty, a).
57 Definition eval_result {dbg A} : @DebugM dbg A -> A
58 := @snd _ _.
59 Definition copy_debug_info {dbg A} (x : DebugM A) : @DebugM dbg unit
60 := bind x (fun _ => ret tt).
61 Definition with_debug_info {dbg A B} (x : DebugM A) (y : DebugM B) : @DebugM dbg B
62 := sequence (copy_debug_info x) y.
63 Definition get_debug_info {dbg A} (v : DebugM dbg A) : list (unit -> list dbg)
64 := tree.to_list (fst v).
65
66 Lemma eval_result_bind dbg A B x k
67 : eval_result (@bind dbg A B x k) = let y := eval_result x in eval_result (k y).
68 Proof. reflexivity. Qed.
69 End Debug.
70
71 Notation "x <- y ; f" := (Debug.bind y (fun x => f%debugM)) : debugM_scope.
72 Notation "f ;; g" := (Debug.sequence f g) : debugM_scope.