]> code.delx.au - gnu-emacs-elpa/blob - packages/fsm/fsm.el
fsm: Port to cl-lib
[gnu-emacs-elpa] / packages / fsm / fsm.el
1 ;;; fsm.el --- state machine library -*- lexical-binding: t; -*-
2
3 ;; Copyright (C) 2006, 2007, 2008 Magnus Henoch
4
5 ;; Author: Magnus Henoch <mange@freemail.hu>
6 ;; Version: 0.1ttn4
7
8 ;; This file is free software; you can redistribute it and/or modify
9 ;; it under the terms of the GNU General Public License as published by
10 ;; the Free Software Foundation; either version 2, or (at your option)
11 ;; any later version.
12
13 ;; This file is distributed in the hope that it will be useful,
14 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 ;; GNU General Public License for more details.
17
18 ;; You should have received a copy of the GNU General Public License
19 ;; along with GNU Emacs; see the file COPYING. If not, write to
20 ;; the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21 ;; Boston, MA 02110-1301, USA.
22
23 ;;; Commentary:
24
25 ;; fsm.el is an exercise in metaprogramming inspired by gen_fsm of
26 ;; Erlang/OTP. It aims to make asynchronous programming in Emacs Lisp
27 ;; easy and fun. By "asynchronous" I mean that long-lasting tasks
28 ;; don't interfer with normal editing.
29
30 ;; Some people say that it would be nice if Emacs Lisp had threads
31 ;; and/or continuations. They are probably right, but there are few
32 ;; things that can't be made to run in the background using facilities
33 ;; already available: timers, filters and sentinels. As the code can
34 ;; become a bit messy when using such means, with callbacks everywhere
35 ;; and such things, it can be useful to structure the program as a
36 ;; state machine.
37
38 ;; In this model, a state machine passes between different "states",
39 ;; which are actually only different event handler functions. The
40 ;; state machine receives "events" (from timers, filters, user
41 ;; requests, etc) and reacts to them, possibly entering another state,
42 ;; possibly returning a value.
43
44 ;; The essential macros/functions are:
45 ;;
46 ;; define-state-machine - create start-FOO function
47 ;; define-state - event handler for each state (required)
48 ;; define-enter-state - called when entering a state (optional)
49 ;; define-fsm - encapsulates the above three (more sugar!)
50 ;; fsm-send - send an event to a state machine
51 ;; fsm-call - send an event and wait for reply
52
53 ;; fsm.el is similar to but different from Distel:
54 ;; <URL:http://fresh.homeunix.net/~luke/distel/>
55 ;; Emacs' tq library is a similar idea.
56
57 ;; Here is a simple (not using all the features of fsm.el) example:
58 ;;
59 ;; ;; -*- lexical-binding: t; -*-
60 ;; (require 'fsm)
61 ;; (cl-labels ((hey (n ev)
62 ;; (message "%d (%s)\tp%sn%s!" n ev
63 ;; (if (zerop (% n 4)) "o" "i")
64 ;; (make-string (max 1 (abs n)) ?g))))
65 ;; (cl-macrolet ((zow (next timeout)
66 ;; `(progn (hey (cl-incf count) event)
67 ;; (list ,next count ,timeout))))
68 ;; (define-fsm pingpong
69 ;; :start ((init) "Start a pingpong fsm."
70 ;; (interactive "nInit (number, negative to auto-terminate): ")
71 ;; (list :ping (ash (ash init -2) 2) ; 4 is death
72 ;; (when (interactive-p) 0)))
73 ;; :state-data-name count
74 ;; :states
75 ;; ((:ping
76 ;; (:event (zow :pingg 0.1)))
77 ;; (:pingg
78 ;; (:event (zow :pinggg 0.1)))
79 ;; (:pinggg
80 ;; (:event (zow :pong 1)))
81 ;; (:pong
82 ;; (:event (zow :ping (if (= 0 count)
83 ;; (fsm-goodbye-cruel-world 'pingpong)
84 ;; 3))))))))
85 ;; (fsm-send (start-pingpong -16) t)
86 ;;
87 ;; Copy into a buffer, uncomment, and type M-x eval-buffer RET.
88 ;; Alternatively, you can replace the `fsm-goodbye-cruel-world'
89 ;; form with `nil', eval just the `cl-labels' form and then type
90 ;; M-x start-pingpong RET -16 RET.
91
92 ;; Version 0.2:
93 ;; -- Delete trailing whitespace.
94 ;; -- Fix formatting.
95 ;; -- Use lexical binding.
96 ;; -- Port to cl-lib.
97
98 ;; NOTE: This is version 0.1ttn4 of fsm.el, with the following
99 ;; mods (an exercise in meta-meta-programming ;-) by ttn:
100 ;; -- Refill for easy (traditional 80-column) perusal.
101 ;; -- New var `fsm-debug-timestamp-format'.
102 ;; -- Make variables satisfy `user-variable-p'.
103 ;; -- Use `format' instead of `concat'.
104 ;; -- New func `fsm-goodbye-cruel-world'.
105 ;; -- Make start-function respect `interactive' spec.
106 ;; -- Make enter-/event-functions anonymous.
107 ;; -- New macro `define-fsm'.
108 ;; -- Example usage in Commentary.
109
110 ;;; Code:
111
112 ;; We require cl-lib at runtime, since we insert `cl-destructuring-bind' into
113 ;; modules that use fsm.el.
114 (require 'cl-lib)
115
116 (defvar fsm-debug "*fsm-debug*"
117 "*Name of buffer for fsm debug messages.
118 If nil, don't output debug messages.")
119
120 (defvar fsm-debug-timestamp-format nil
121 "*Timestamp format (a string) for `fsm-debug-output'.
122 Default format is whatever `current-time-string' returns
123 followed by a colon and a space.")
124
125 (defun fsm-debug-output (format &rest args)
126 "Append debug output to buffer named by the variable `fsm-debug'.
127 FORMAT and ARGS are passed to `format'."
128 (when fsm-debug
129 (with-current-buffer (get-buffer-create fsm-debug)
130 (save-excursion
131 (goto-char (point-max))
132 (insert (if fsm-debug-timestamp-format
133 (format-time-string fsm-debug-timestamp-format)
134 (concat (current-time-string) ": "))
135 (apply 'format format args) "\n")))))
136
137 (cl-defmacro define-state-machine (name &key start sleep)
138 "Define a state machine class called NAME.
139 A function called start-NAME is created, which uses the argument
140 list and body specified in the :start argument. BODY should
141 return a list of the form (STATE STATE-DATA [TIMEOUT]), where
142 STATE is the initial state (defined by `define-state'),
143 STATE-DATA is any object, and TIMEOUT is the number of seconds
144 before a :timeout event will be sent to the state machine. BODY
145 may refer to the instance being created through the dynamically
146 bound variable `fsm'.
147
148 SLEEP-FUNCTION, if provided, takes one argument, the number of
149 seconds to sleep while allowing events concerning this state
150 machine to happen. There is probably no reason to change the
151 default, which is accept-process-output with rearranged
152 arguments.
153
154 \(fn NAME :start ((ARG ...) DOCSTRING BODY) [:sleep SLEEP-FUNCTION])"
155 (declare (debug (&define name :name start
156 &rest
157 &or [":start"
158 (lambda-list
159 [&optional ("interactive" interactive)]
160 stringp def-body)]
161 [":sleep" function-form])))
162 (let ((start-name (intern (format "start-%s" name)))
163 interactive-spec)
164 (cl-destructuring-bind (arglist docstring &body body) start
165 (when (and (consp (car body)) (eq 'interactive (caar body)))
166 (setq interactive-spec (list (pop body))))
167 (unless (stringp docstring)
168 (error "Docstring is not a string"))
169 `(progn
170 (put ',name :fsm-enter (make-hash-table :size 11 :test 'eq))
171 (put ',name :fsm-event (make-hash-table :size 11 :test 'eq))
172 (defun ,start-name ,arglist
173 ,docstring
174 ,@interactive-spec
175 (fsm-debug-output "Starting %s" ',name)
176 (let ((fsm (list :fsm ',name)))
177 (cl-destructuring-bind (state state-data &optional timeout)
178 (progn ,@body)
179 (nconc fsm (list :state nil :state-data nil
180 :sleep ,(or sleep (lambda (secs)
181 (accept-process-output
182 nil secs)))
183 :deferred nil))
184 (fsm-update fsm state state-data timeout)
185 fsm)))))))
186
187 (cl-defmacro define-state (fsm-name state-name arglist &body body)
188 "Define a state called STATE-NAME in the state machine FSM-NAME.
189 ARGLIST and BODY make a function that gets called when the state
190 machine receives an event in this state. The arguments are:
191
192 FSM the state machine instance (treat it as opaque)
193 STATE-DATA An object
194 EVENT The occurred event, an object.
195 CALLBACK A function of one argument that expects the response
196 to this event, if any (often `ignore' is used)
197
198 If the event should return a response, the state machine should
199 arrange to call CALLBACK at some point in the future (not necessarily
200 in this handler).
201
202 The function should return a list of the form (NEW-STATE
203 NEW-STATE-DATA TIMEOUT):
204
205 NEW-STATE The next state, a symbol
206 NEW-STATE-DATA An object
207 TIMEOUT A number: send timeout event after this many seconds
208 nil: cancel existing timer
209 :keep: let existing timer continue
210
211 Alternatively, the function may return the keyword :defer, in
212 which case the event will be resent when the state machine enters
213 another state."
214 (declare (debug (&define name name :name handler lambda-list def-body)))
215 `(setf (gethash ',state-name (get ',fsm-name :fsm-event))
216 (lambda ,arglist ,@body)))
217
218 (cl-defmacro define-enter-state (fsm-name state-name arglist &body body)
219 "Define a function to call when FSM-NAME enters the state STATE-NAME.
220 ARGLIST and BODY make a function that gets called when the state
221 machine enters this state. The arguments are:
222
223 FSM the state machine instance (treat it as opaque)
224 STATE-DATA An object
225
226 The function should return a list of the form (NEW-STATE-DATA
227 TIMEOUT):
228
229 NEW-STATE-DATA An object
230 TIMEOUT A number: send timeout event after this many seconds
231 nil: cancel existing timer
232 :keep: let existing timer continue"
233 (declare (debug (&define name name :name enter lambda-list def-body)))
234 `(setf (gethash ',state-name (get ',fsm-name :fsm-enter))
235 (lambda ,arglist ,@body)))
236
237 (cl-defmacro define-fsm (name &key
238 start sleep states
239 (fsm-name 'fsm)
240 (state-data-name 'state-data)
241 (callback-name 'callback)
242 (event-name 'event))
243 "Define a state machine class called NAME, along with its STATES.
244 This macro is (further) syntatic sugar for `define-state-machine',
245 `define-state' and `define-enter-state' macros, q.v.
246
247 NAME is a symbol. Everything else is specified with a keyword arg.
248
249 START and SLEEP are the same as for `define-state-machine'.
250
251 STATES is a list, each element having the form (STATE-NAME . STATE-SPEC).
252 STATE-NAME is a symbol. STATE-SPEC is an alist with keys `:event' or
253 `:enter', and values a series of expressions representing the BODY of
254 a `define-state' or `define-enter-state' call, respectively.
255
256 FSM-NAME, STATE-DATA-NAME, CALLBACK-NAME, and EVENT-NAME are symbols,
257 used to construct the state functions' arglists."
258 `(progn
259 (define-state-machine ,name :start ,start :sleep ,sleep)
260 ,@(cl-loop for (state-name . spec) in states
261 if (assq :enter spec) collect
262 `(define-enter-state ,name ,state-name
263 (,fsm-name ,state-data-name)
264 ,@(cdr it))
265 end
266 if (assq :event spec) collect
267 `(define-state ,name ,state-name
268 (,fsm-name ,state-data-name
269 ,event-name
270 ,callback-name)
271 ,@(cdr it))
272 end)))
273
274 (defun fsm-goodbye-cruel-world (name)
275 "Unbind functions related to fsm NAME (a symbol).
276 Includes start-NAME, and each fsm-NAME-STATE and fsm-NAME-enter-STATE.
277 Functions are `fmakunbound', which will probably give (fatal) pause to
278 any state machines using them. Return nil."
279 (interactive "SUnbind function definitions for fsm named: ")
280 (fmakunbound (intern (format "start-%s" name)))
281 (let (ht)
282 (when (hash-table-p (setq ht (get name :fsm-event)))
283 (clrhash ht)
284 (cl-remprop name :fsm-event))
285 (when (hash-table-p (setq ht (get name :fsm-enter)))
286 (clrhash ht)
287 (cl-remprop name :fsm-enter)))
288 nil)
289
290 (defun fsm-start-timer (fsm secs)
291 "Send a timeout event to FSM after SECS seconds.
292 The timer is canceled if another event occurs before, unless the
293 event handler explicitly asks to keep the timer."
294 (fsm-stop-timer fsm)
295 (setf (cddr fsm)
296 (plist-put
297 (cddr fsm)
298 :timeout (run-with-timer secs
299 nil
300 #'fsm-send-sync fsm
301 :timeout))))
302
303 (defun fsm-stop-timer (fsm)
304 "Stop the timeout timer of FSM."
305 (let ((timer (plist-get (cddr fsm) :timeout)))
306 (when (timerp timer)
307 (cancel-timer timer)
308 (setf (cddr fsm) (plist-put (cddr fsm) :timeout nil)))))
309
310 (defun fsm-maybe-change-timer (fsm timeout)
311 "Change the timer of FSM according to TIMEOUT."
312 (cond
313 ((numberp timeout)
314 (fsm-start-timer fsm timeout))
315 ((null timeout)
316 (fsm-stop-timer fsm))
317 ;; :keep needs no timer change
318 ))
319
320 (defun fsm-send (fsm event &optional callback)
321 "Send EVENT to FSM asynchronously.
322 If the state machine generates a response, eventually call
323 CALLBACK with the response as only argument."
324 (run-with-timer 0 nil #'fsm-send-sync fsm event callback))
325
326 (defun fsm-update (fsm new-state new-state-data timeout)
327 (let ((fsm-name (cadr fsm))
328 (old-state (plist-get (cddr fsm) :state)))
329 (plist-put (cddr fsm) :state new-state)
330 (plist-put (cddr fsm) :state-data new-state-data)
331 (fsm-maybe-change-timer fsm timeout)
332
333 ;; On state change, call enter function and send deferred events
334 ;; again.
335 (unless (eq old-state new-state)
336 (fsm-debug-output "%s enters %s" fsm-name new-state)
337 (let ((enter-fn (gethash new-state (get fsm-name :fsm-enter))))
338 (when (functionp enter-fn)
339 (fsm-debug-output "Found enter function for %S" new-state)
340 (condition-case e
341 (cl-destructuring-bind (newer-state-data newer-timeout)
342 (funcall enter-fn fsm new-state-data)
343 (fsm-debug-output "Using data from enter function")
344 (plist-put (cddr fsm) :state-data newer-state-data)
345 (fsm-maybe-change-timer fsm newer-timeout))
346 ((debug error)
347 (fsm-debug-output "Didn't work: %S" e)))))
348
349 (let ((deferred (nreverse (plist-get (cddr fsm) :deferred))))
350 (setf (cddr fsm)
351 (plist-put (cddr fsm) :deferred nil))
352 (dolist (event deferred)
353 (apply 'fsm-send-sync fsm event))))))
354
355 (defun fsm-send-sync (fsm event &optional callback)
356 "Send EVENT to FSM synchronously.
357 If the state machine generates a response, eventually call
358 CALLBACK with the response as only argument."
359 (save-match-data
360 (let* ((fsm-name (cl-second fsm))
361 (state (plist-get (cddr fsm) :state))
362 (state-data (plist-get (cddr fsm) :state-data))
363 (state-fn (gethash state (get fsm-name :fsm-event))))
364 ;; If the event is a list, output only the car, to avoid an
365 ;; overflowing debug buffer.
366 (fsm-debug-output "Sent %S to %s in state %s"
367 (or (car-safe event) event) fsm-name state)
368 (let ((result (condition-case e
369 (funcall state-fn fsm state-data event
370 (or callback 'ignore))
371 ((debug error) (cons :error-signaled e)))))
372 ;; Special case for deferring an event until next state change.
373 (cond
374 ((eq result :defer)
375 (let ((deferred (plist-get (cddr fsm) :deferred)))
376 (plist-put (cddr fsm) :deferred
377 (cons (list event callback) deferred))))
378 ((null result)
379 (fsm-debug-output "Warning: event %S ignored in state %s/%s"
380 event fsm-name state))
381 ((eq (car-safe result) :error-signaled)
382 (fsm-debug-output "Error in %s/%s: %s"
383 fsm-name state
384 (error-message-string (cdr result))))
385 ((and (listp result)
386 (<= 2 (length result))
387 (<= (length result) 3))
388 (cl-destructuring-bind (new-state new-state-data &optional timeout)
389 result
390 (fsm-update fsm new-state new-state-data timeout)))
391 (t
392 (fsm-debug-output "Incorrect return value in %s/%s: %S"
393 fsm-name state
394 result)))))))
395
396 (defun fsm-call (fsm event)
397 "Send EVENT to FSM synchronously, and wait for a reply.
398 Return the reply.
399 `with-timeout' might be useful."
400 (let (reply)
401 (fsm-send-sync fsm event (lambda (r) (setq reply (list r))))
402 (while (null reply)
403 (fsm-sleep fsm 1))
404 (car reply)))
405
406 (defun fsm-make-filter (fsm)
407 "Return a filter function that sends events to FSM.
408 Events sent are of the form (:filter PROCESS STRING)."
409 (let ((fsm fsm))
410 (lambda (process string)
411 (fsm-send-sync fsm (list :filter process string)))))
412
413 (defun fsm-make-sentinel (fsm)
414 "Return a sentinel function that sends events to FSM.
415 Events sent are of the form (:sentinel PROCESS STRING)."
416 (let ((fsm fsm))
417 (lambda (process string)
418 (fsm-send-sync fsm (list :sentinel process string)))))
419
420 (defun fsm-sleep (fsm secs)
421 "Sleep up to SECS seconds in a way that lets FSM receive events."
422 (funcall (plist-get (cddr fsm) :sleep) secs))
423
424 (defun fsm-get-state-data (fsm)
425 "Return the state data of FSM.
426 Note the absence of a set function. The fsm should manage its
427 state data itself; other code should just send messages to it."
428 (plist-get (cddr fsm) :state-data))
429
430 (provide 'fsm)
431
432 ;;; fsm.el ends here