1 ;;; fsm.el --- state machine library -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2006, 2007, 2008 Magnus Henoch
5 ;; Author: Magnus Henoch <mange@freemail.hu>
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)
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.
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.
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.
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
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.
44 ;; The essential macros/functions are:
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
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.
57 ;; Here is a simple (not using all the features of fsm.el) example:
59 ;; ;; -*- lexical-binding: t; -*-
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
76 ;; (:event (zow :pingg 0.1)))
78 ;; (:event (zow :pinggg 0.1)))
80 ;; (:event (zow :pong 1)))
82 ;; (:event (zow :ping (if (= 0 count)
83 ;; (fsm-goodbye-cruel-world 'pingpong)
85 ;; (fsm-send (start-pingpong -16) t)
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.
93 ;; -- Delete trailing whitespace.
95 ;; -- Use lexical binding.
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.
112 ;; We require cl-lib at runtime, since we insert `cl-destructuring-bind' into
113 ;; modules that use fsm.el.
116 (defvar fsm-debug "*fsm-debug*"
117 "*Name of buffer for fsm debug messages.
118 If nil, don't output debug messages.")
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.")
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'."
129 (with-current-buffer (get-buffer-create fsm-debug)
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")))))
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'.
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
154 \(fn NAME :start ((ARG ...) DOCSTRING BODY) [:sleep SLEEP-FUNCTION])"
155 (declare (debug (&define name :name start
159 [&optional ("interactive" interactive)]
161 [":sleep" function-form])))
162 (let ((start-name (intern (format "start-%s" name)))
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"))
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
175 (fsm-debug-output "Starting %s" ',name)
176 (let ((fsm (list :fsm ',name)))
177 (cl-destructuring-bind (state state-data &optional timeout)
179 (nconc fsm (list :state nil :state-data nil
180 :sleep ,(or sleep (lambda (secs)
181 (accept-process-output
184 (fsm-update fsm state state-data timeout)
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:
192 FSM the state machine instance (treat it as opaque)
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)
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
202 The function should return a list of the form (NEW-STATE
203 NEW-STATE-DATA TIMEOUT):
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
211 Alternatively, the function may return the keyword :defer, in
212 which case the event will be resent when the state machine enters
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)))
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:
223 FSM the state machine instance (treat it as opaque)
226 The function should return a list of the form (NEW-STATE-DATA
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)))
237 (cl-defmacro define-fsm (name &key
240 (state-data-name 'state-data)
241 (callback-name 'callback)
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.
247 NAME is a symbol. Everything else is specified with a keyword arg.
249 START and SLEEP are the same as for `define-state-machine'.
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.
256 FSM-NAME, STATE-DATA-NAME, CALLBACK-NAME, and EVENT-NAME are symbols,
257 used to construct the state functions' arglists."
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)
266 if (assq :event spec) collect
267 `(define-state ,name ,state-name
268 (,fsm-name ,state-data-name
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)))
282 (when (hash-table-p (setq ht (get name :fsm-event)))
284 (cl-remprop name :fsm-event))
285 (when (hash-table-p (setq ht (get name :fsm-enter)))
287 (cl-remprop name :fsm-enter)))
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."
298 :timeout (run-with-timer secs
303 (defun fsm-stop-timer (fsm)
304 "Stop the timeout timer of FSM."
305 (let ((timer (plist-get (cddr fsm) :timeout)))
308 (setf (cddr fsm) (plist-put (cddr fsm) :timeout nil)))))
310 (defun fsm-maybe-change-timer (fsm timeout)
311 "Change the timer of FSM according to TIMEOUT."
314 (fsm-start-timer fsm timeout))
316 (fsm-stop-timer fsm))
317 ;; :keep needs no timer change
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))
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)
333 ;; On state change, call enter function and send deferred events
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)
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))
347 (fsm-debug-output "Didn't work: %S" e)))))
349 (let ((deferred (nreverse (plist-get (cddr fsm) :deferred))))
351 (plist-put (cddr fsm) :deferred nil))
352 (dolist (event deferred)
353 (apply 'fsm-send-sync fsm event))))))
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."
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.
375 (let ((deferred (plist-get (cddr fsm) :deferred)))
376 (plist-put (cddr fsm) :deferred
377 (cons (list event callback) deferred))))
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"
384 (error-message-string (cdr result))))
386 (<= 2 (length result))
387 (<= (length result) 3))
388 (cl-destructuring-bind (new-state new-state-data &optional timeout)
390 (fsm-update fsm new-state new-state-data timeout)))
392 (fsm-debug-output "Incorrect return value in %s/%s: %S"
396 (defun fsm-call (fsm event)
397 "Send EVENT to FSM synchronously, and wait for a reply.
399 `with-timeout' might be useful."
401 (fsm-send-sync fsm event (lambda (r) (setq reply (list r))))
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)."
410 (lambda (process string)
411 (fsm-send-sync fsm (list :filter process string)))))
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)."
417 (lambda (process string)
418 (fsm-send-sync fsm (list :sentinel process string)))))
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))
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))