infix: Replace multiple-value constructs with a single bind.
[lisp] / mdw-base.lisp
1 ;;; -*-lisp-*-
2 ;;;
3 ;;; $Id$
4 ;;;
5 ;;; Basic definitions
6 ;;;
7 ;;; (c) 2005 Mark Wooding
8 ;;;
9
10 ;;;----- Licensing notice ---------------------------------------------------
11 ;;;
12 ;;; This program is free software; you can redistribute it and/or modify
13 ;;; it under the terms of the GNU General Public License as published by
14 ;;; the Free Software Foundation; either version 2 of the License, or
15 ;;; (at your option) any later version.
16 ;;;
17 ;;; This program is distributed in the hope that it will be useful,
18 ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;;; GNU General Public License for more details.
21 ;;;
22 ;;; You should have received a copy of the GNU General Public License
23 ;;; along with this program; if not, write to the Free Software Foundation,
24 ;;; Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
25
26 ;;;--------------------------------------------------------------------------
27 ;;; Package things.
28
29 (defpackage #:mdw.base
30 (:use #:common-lisp)
31 (:export #:compile-time-defun
32 #:show
33 #:stringify #:mappend #:listify #:fix-pair #:pairify #:parse-body
34 #:whitespace-char-p
35 #:slot-uninitialized
36 #:nlet #:while #:case2 #:ecase2
37 #:with-gensyms #:let*/gensyms #:with-places
38 #:locp #:locf #:ref #:with-locatives
39 #:update-place #:update-place-after
40 #:incf-after #:decf-after
41 #:fixnump)
42 #+cmu (:import-from #:extensions #:fixnump))
43
44 (in-package #:mdw.base)
45
46 ;;;--------------------------------------------------------------------------
47 ;;; Some simple macros to get things going.
48
49 (defmacro compile-time-defun (name args &body body)
50 "Define a function which can be used by macros during the compilation
51 process."
52 `(eval-when (:compile-toplevel :load-toplevel)
53 (defun ,name ,args ,@body)))
54
55 (defmacro show (x)
56 "Debugging tool: print the expression X and its values."
57 (let ((tmp (gensym)))
58 `(let ((,tmp (multiple-value-list ,x)))
59 (format t "~&")
60 (pprint-logical-block (*standard-output* nil :per-line-prefix ";; ")
61 (format t
62 "~S = ~@_~:I~:[#<no values>~;~:*~{~S~^ ~_~}~]"
63 ',x
64 ,tmp))
65 (terpri)
66 (values-list ,tmp))))
67
68 (defun stringify (str)
69 "Return a string representation of STR. Strings are returned unchanged;
70 symbols are converted to their names (unqualified!). Other objects are
71 converted to their print representations."
72 (typecase str
73 (string str)
74 (symbol (symbol-name str))
75 (t (with-output-to-string (s)
76 (princ str s)))))
77
78 (defun mappend (function list &rest more-lists)
79 "Apply FUNCTION to corresponding elements of LIST and MORE-LISTS, yielding
80 a list. Return the concatenation of all the resulting lists. Like
81 mapcan, but nondestructive."
82 (apply #'append (apply #'mapcar function list more-lists)))
83
84 (compile-time-defun listify (x)
85 "If X is a (possibly empty) list, return X; otherwise return (list X)."
86 (if (listp x) x (list x)))
87
88 (compile-time-defun do-fix-pair (x y defaultp)
89 "Helper function for fix-pair and pairify."
90 (flet ((singleton (x) (values x (if defaultp y x))))
91 (cond ((atom x) (singleton x))
92 ((null (cdr x)) (singleton (car x)))
93 ((atom (cdr x)) (values (car x) (cdr x)))
94 ((cddr x) (error "Too many elements for a pair."))
95 (t (values (car x) (cadr x))))))
96
97 (compile-time-defun fix-pair (x &optional (y nil defaultp))
98 "Return two values extracted from X. It works as follows:
99 (A) -> A, Y
100 (A B) -> A, B
101 (A B . C) -> error
102 (A . B) -> A, B
103 A -> A, Y
104 where Y defaults to A if not specified."
105 (do-fix-pair x y defaultp))
106
107 (compile-time-defun pairify (x &optional (y nil defaultp))
108 "As for fix-pair, but returns a list instead of two values."
109 (multiple-value-call #'list (do-fix-pair x y defaultp)))
110
111 (defun whitespace-char-p (ch)
112 "Return whether CH is a whitespace character or not."
113 (case ch
114 ((#\space #\tab #\newline #\return #\vt #\formfeed) t)
115 (t nil)))
116
117 (declaim (ftype (function nil ()) slot-unitialized))
118 (defun slot-uninitialized ()
119 "A function which signals an error. Can be used as an initializer form in
120 structure definitions without doom ensuing."
121 (error "No initializer for slot."))
122
123 (compile-time-defun parse-body (body &key (allow-docstring-p t))
124 "Given a BODY (a list of forms), parses it into three sections: a
125 docstring, a list of declarations (forms beginning with the symbol
126 `declare') and the body forms. The result is returned as three lists
127 (even the docstring), suitable for interpolation into a backquoted list
128 using `@,'. If ALLOW-DOCSTRING-P is nil, docstrings aren't allowed at
129 all."
130 (let ((doc nil) (decls nil))
131 (do ((forms body (cdr forms))) (nil)
132 (let ((form (and forms (car forms))))
133 (cond ((and allow-docstring-p (not doc) (stringp form) (cdr forms))
134 (setf doc form))
135 ((and (consp form)
136 (eq (car form) 'declare))
137 (setf decls (append decls (cdr form))))
138 (t (return (values (and doc (list doc))
139 (and decls (list (cons 'declare decls)))
140 forms))))))))
141
142 #-cmu
143 (progn
144 (declaim (inline fixnump))
145 (defun fixnump (object)
146 "Answer non-nil if OBJECT is a fixnum, or nil if it isn't."
147 (typep object 'fixnum)))
148
149 ;;;--------------------------------------------------------------------------
150 ;;; Generating symbols.
151
152 (defmacro with-gensyms (syms &body body)
153 "Everyone's favourite macro helper."
154 `(let (,@(mapcar (lambda (sym) `(,sym (gensym ,(symbol-name sym))))
155 (listify syms)))
156 ,@body))
157
158 (defmacro let*/gensyms (binds &body body)
159 "A macro helper. BINDS is a list of binding pairs (VAR VALUE), where VALUE
160 defaults to VAR. The result is that BODY is evaluated in a context where
161 each VAR is bound to a gensym, and in the final expansion, each of those
162 gensyms will be bound to the corresponding VALUE."
163 (labels ((more (binds)
164 (let ((tmp (gensym "TMP")) (bind (car binds)))
165 `((let ((,tmp ,(cadr bind))
166 (,(car bind) (gensym ,(symbol-name (car bind)))))
167 `(let ((,,(car bind) ,,tmp))
168 ,,@(if (cdr binds)
169 (more (cdr binds))
170 body)))))))
171 (if (null binds)
172 `(progn ,@body)
173 (car (more (mapcar #'pairify (listify binds)))))))
174
175 ;;;--------------------------------------------------------------------------
176 ;;; Some simple yet useful control structures.
177
178 (defmacro nlet (name binds &body body)
179 "Scheme's named let."
180 (multiple-value-bind (vars vals)
181 (loop for bind in binds
182 for (var val) = (pairify bind nil)
183 collect var into vars
184 collect val into vals
185 finally (return (values vars vals)))
186 `(labels ((,name ,vars
187 ,@body))
188 (,name ,@vals))))
189
190 (defmacro while (cond &body body)
191 "If COND is false, evaluate to nil; otherwise evaluate BODY and try again."
192 `(loop
193 (unless ,cond (return))
194 ,@body))
195
196 (compile-time-defun do-case2-like (kind vform clauses)
197 "Helper function for `case2' and `ecase2'."
198 (with-gensyms (scrutinee argument)
199 `(multiple-value-bind (,scrutinee ,argument) ,vform
200 (declare (ignorable ,argument))
201 (,kind ,scrutinee
202 ,@(mapcar (lambda (clause)
203 (destructuring-bind
204 (cases (&optional varx vary) &rest forms)
205 clause
206 `(,cases
207 ,@(if varx
208 (list `(let ((,(or vary varx) ,argument)
209 ,@(and vary
210 `((,varx ,scrutinee))))
211 ,@forms))
212 forms))))
213 clauses)))))
214
215 (defmacro case2 (vform &body clauses)
216 "VFORM is a form which evaluates to two values, SCRUTINEE and ARGUMENT.
217 The CLAUSES have the form (CASES ([[SCRUVAR] ARGVAR]) FORMS...), where a
218 standard `case' clause has the form (CASES FORMS...). The `case2' form
219 evaluates the VFORM, and compares the SCRUTINEE to the various CASES, in
220 order, just like `case'. If there is a match, then the corresponding
221 FORMs are evaluated with ARGVAR bound to the ARGUMENT and SCRUVAR bound to
222 the SCRUTINEE (where specified). Note the bizarre defaulting behaviour:
223 ARGVAR is less optional than SCRUVAR."
224 (do-case2-like 'case vform clauses))
225
226 (defmacro ecase2 (vform &body clauses)
227 "Like `case2', but signals an error if no clause matches the SCRUTINEE."
228 (do-case2-like 'ecase vform clauses))
229
230 ;;;--------------------------------------------------------------------------
231 ;;; with-places
232
233 (defmacro %place-ref (getform setform newtmp)
234 "Grim helper macro for with-places."
235 (declare (ignore setform newtmp))
236 getform)
237
238 (define-setf-expander %place-ref (getform setform newtmp)
239 "Grim helper macro for with-places."
240 (values nil nil newtmp setform getform))
241
242 (defmacro with-places ((&key environment) places &body body)
243 "A hairy helper, for writing setf-like macros. PLACES is a list of binding
244 pairs (VAR PLACE), where PLACE defaults to VAR. The result is that BODY
245 is evaluated in a context where each VAR is bound to a gensym, and in the
246 final expansion, each of those gensyms will be bound to a symbol-macro
247 capable of reading or setting the value of the corresponding PLACE."
248 (if (null places)
249 `(progn ,@body)
250 (let*/gensyms (environment)
251 (labels
252 ((more (places)
253 (let ((place (car places)))
254 (with-gensyms (tmp valtmps valforms
255 newtmps setform getform)
256 `((let ((,tmp ,(cadr place))
257 (,(car place)
258 (gensym ,(symbol-name (car place)))))
259 (multiple-value-bind
260 (,valtmps ,valforms
261 ,newtmps ,setform ,getform)
262 (get-setf-expansion ,tmp
263 ,environment)
264 (list 'let*
265 (mapcar #'list ,valtmps ,valforms)
266 `(symbol-macrolet ((,,(car place)
267 (%place-ref ,,getform
268 ,,setform
269 ,,newtmps)))
270 ,,@(if (cdr places)
271 (more (cdr places))
272 body))))))))))
273 (car (more (mapcar #'pairify (listify places))))))))
274
275 ;;;--------------------------------------------------------------------------
276 ;;; Update-in-place macros built using with-places.
277
278 (defmacro update-place (op place arg &environment env)
279 "Update PLACE with the value of OP PLACE ARG, returning the new value."
280 (with-places (:environment env) (place)
281 `(setf ,place (,op ,place ,arg))))
282
283 (defmacro update-place-after (op place arg &environment env)
284 "Update PLACE with the value of OP PLACE ARG, returning the old value."
285 (with-places (:environment env) (place)
286 (with-gensyms (x)
287 `(let ((,x ,place))
288 (setf ,place (,op ,x ,arg))
289 ,x))))
290
291 (defmacro incf-after (place &optional (by 1))
292 "Increment PLACE by BY, returning the old value."
293 `(update-place-after + ,place ,by))
294
295 (defmacro decf-after (place &optional (by 1))
296 "Decrement PLACE by BY, returning the old value."
297 `(update-place-after - ,place ,by))
298
299 ;;;--------------------------------------------------------------------------
300 ;;; Locatives.
301
302 (defstruct (loc (:predicate locp) (:constructor make-loc (reader writer)))
303 "Locative data type. See `locf' and `ref'."
304 (reader (slot-uninitialized) :type function)
305 (writer (slot-uninitialized) :type function))
306
307 (defmacro locf (place &environment env)
308 "Slightly cheesy locatives. (locf PLACE) returns an object which, using
309 the `ref' function, can be used to read or set the value of PLACE. It's
310 cheesy because it uses closures rather than actually taking the address of
311 something. Also, unlike Zetalisp, we don't overload `car' to do our dirty
312 work."
313 (multiple-value-bind
314 (valtmps valforms newtmps setform getform)
315 (get-setf-expansion place env)
316 `(let* (,@(mapcar #'list valtmps valforms))
317 (make-loc (lambda () ,getform)
318 (lambda (,@newtmps) ,setform)))))
319
320 (declaim (inline loc (setf loc)))
321
322 (defun ref (loc)
323 "Fetch the value referred to by a locative."
324 (funcall (loc-reader loc)))
325
326 (defun (setf ref) (new loc)
327 "Store a new value in the place referred to by a locative."
328 (funcall (loc-writer loc) new))
329
330 (defmacro with-locatives (locs &body body)
331 "LOCS is a list of items of the form (SYM [LOC-EXPR]), where SYM is a
332 symbol and LOC-EXPR evaluates to a locative. If LOC-EXPR is omitted, it
333 defaults to SYM. As an abbreviation for a common case, LOCS may be a
334 symbol instead of a list. The BODY is evaluated in an environment where
335 each SYM is a symbol macro which expands to (ref LOC-EXPR) -- or, in fact,
336 something similar which doesn't break if LOC-EXPR has side-effects. Thus,
337 references, including `setf' forms, fetch or modify the thing referred to
338 by the LOC-EXPR. Useful for covering over where something uses a
339 locative."
340 (setf locs (mapcar #'pairify (listify locs)))
341 (let ((tt (mapcar (lambda (l) (declare (ignore l)) (gensym)) locs))
342 (ll (mapcar #'cadr locs))
343 (ss (mapcar #'car locs)))
344 `(let (,@(mapcar (lambda (tmp loc) `(,tmp ,loc)) tt ll))
345 (symbol-macrolet (,@(mapcar (lambda (sym tmp)
346 `(,sym (ref ,tmp))) ss tt))
347 ,@body))))
348
349 ;;;----- That's all, folks --------------------------------------------------