Source file variable_watcher.ml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
open! Core
open! Import

module Operation = struct
  module T = struct
    type t =
      | Set
      | Let
      | Unlet
      | Makunbound
      | Defvaralias
    [@@deriving enumerate, sexp_of]
  end

  include T

  let type_ =
    Value.Type.enum
      [%message "variable-change-operation"]
      (module T)
      ((function
         | Set -> "set"
         | Let -> "let"
         | Unlet -> "unlet"
         | Makunbound -> "makunbound"
         | Defvaralias -> "defvaralias")
       >> Symbol.intern
       >> Symbol.to_value)
  ;;
end

module Event = struct
  type t =
    { local_to_buffer : Buffer.t option
    ; new_value : Value.t
    ; operation : Operation.t
    ; variable_changed : Symbol.t
    }
  [@@deriving sexp_of]
end

let build_function here f =
  Defun.lambda
    here
    (Returns Value.Type.unit)
    (let%map_open.Defun () = return ()
     and symbol = required "symbol" Symbol.type_
     and newval = required "newval" Value.Type.value
     and operation = required "operation" Operation.type_
     and where = required "where" (Value.Type.nil_or Buffer.type_) in
     f
       { Event.local_to_buffer = where
       ; new_value = newval
       ; operation
       ; variable_changed = symbol
       })
;;

type t =
  { symbol : Symbol.t
  ; watcher : Function.t
  }

let add_variable_watcher =
  Funcall.Wrap.("add-variable-watcher" <: Symbol.type_ @-> Function.type_ @-> return nil)
;;

let add here var ~f =
  let watcher = build_function here f in
  add_variable_watcher (Var.symbol var) watcher;
  { symbol = Var.symbol var; watcher }
;;

let remove_variable_watcher =
  Funcall.Wrap.(
    "remove-variable-watcher" <: Symbol.type_ @-> Function.type_ @-> return nil)
;;

let remove { symbol; watcher } = remove_variable_watcher symbol watcher