mdw-base.lisp: Refactor `with-places' incompatibly.
[lisp] / mdw-base.lisp
CommitLineData
861345b4 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.
b2c12b4e 16;;;
861345b4 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.
b2c12b4e 21;;;
861345b4 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
02866e07
MW
26;;;--------------------------------------------------------------------------
27;;; Package things.
28
861345b4 29(defpackage #:mdw.base
30 (:use #:common-lisp)
23f32e98
MW
31 (:export #:unsigned-fixnum
32 #:compile-time-defun
861345b4 33 #:show
f5612edb
MW
34 #:stringify #:functionify #:mappend
35 #:listify #:fix-pair #:pairify
8f801ae8 36 #:parse-body #:with-parsed-body
861345b4 37 #:whitespace-char-p
38 #:slot-uninitialized
2af61873 39 #:nlet #:while #:until #:case2 #:ecase2 #:setf-default
861345b4 40 #:with-gensyms #:let*/gensyms #:with-places
e979e568
MW
41 #:locp #:locf #:ref #:with-locatives
42 #:update-place #:update-place-after
7dcf04ad
MW
43 #:incf-after #:decf-after
44 #:fixnump)
45 #+cmu (:import-from #:extensions #:fixnump))
46
861345b4 47(in-package #:mdw.base)
48
02866e07 49;;;--------------------------------------------------------------------------
23f32e98
MW
50;;; Useful types.
51
52(deftype unsigned-fixnum ()
53 "Unsigned fixnums; useful as array indices and suchlike."
54 `(mod ,most-positive-fixnum))
55
56;;;--------------------------------------------------------------------------
02866e07
MW
57;;; Some simple macros to get things going.
58
861345b4 59(defmacro compile-time-defun (name args &body body)
60 "Define a function which can be used by macros during the compilation
0ff9df03 61 process."
fe0f07ea 62 `(eval-when (:compile-toplevel :load-toplevel :execute)
861345b4 63 (defun ,name ,args ,@body)))
64
65(defmacro show (x)
2f94737a 66 "Debugging tool: print the expression X and its values."
861345b4 67 (let ((tmp (gensym)))
2f94737a 68 `(let ((,tmp (multiple-value-list ,x)))
f36fbd9c 69 (fresh-line)
2f94737a
MW
70 (pprint-logical-block (*standard-output* nil :per-line-prefix ";; ")
71 (format t
72 "~S = ~@_~:I~:[#<no values>~;~:*~{~S~^ ~_~}~]"
73 ',x
74 ,tmp))
75 (terpri)
76 (values-list ,tmp))))
861345b4 77
78(defun stringify (str)
79 "Return a string representation of STR. Strings are returned unchanged;
0ff9df03
MW
80 symbols are converted to their names (unqualified!). Other objects are
81 converted to their print representations."
861345b4 82 (typecase str
83 (string str)
84 (symbol (symbol-name str))
53e95db0 85 (t (princ-to-string str))))
02866e07 86
f5612edb
MW
87(defun functionify (func)
88 "Convert the function-designator FUNC to a function."
89 (declare (type (or function symbol) func))
90 (etypecase func
91 (function func)
92 (symbol (symbol-function func))))
93
4b6a6387
MW
94(defun mappend (function list &rest more-lists)
95 "Apply FUNCTION to corresponding elements of LIST and MORE-LISTS, yielding
96 a list. Return the concatenation of all the resulting lists. Like
97 mapcan, but nondestructive."
98 (apply #'append (apply #'mapcar function list more-lists)))
99
861345b4 100(compile-time-defun listify (x)
101 "If X is a (possibly empty) list, return X; otherwise return (list X)."
102 (if (listp x) x (list x)))
02866e07 103
861345b4 104(compile-time-defun do-fix-pair (x y defaultp)
105 "Helper function for fix-pair and pairify."
106 (flet ((singleton (x) (values x (if defaultp y x))))
107 (cond ((atom x) (singleton x))
108 ((null (cdr x)) (singleton (car x)))
109 ((atom (cdr x)) (values (car x) (cdr x)))
110 ((cddr x) (error "Too many elements for a pair."))
111 (t (values (car x) (cadr x))))))
02866e07 112
861345b4 113(compile-time-defun fix-pair (x &optional (y nil defaultp))
114 "Return two values extracted from X. It works as follows:
0ff9df03
MW
115 (A) -> A, Y
116 (A B) -> A, B
117 (A B . C) -> error
118 (A . B) -> A, B
119 A -> A, Y
120 where Y defaults to A if not specified."
861345b4 121 (do-fix-pair x y defaultp))
02866e07 122
861345b4 123(compile-time-defun pairify (x &optional (y nil defaultp))
124 "As for fix-pair, but returns a list instead of two values."
125 (multiple-value-call #'list (do-fix-pair x y defaultp)))
126
127(defun whitespace-char-p (ch)
128 "Return whether CH is a whitespace character or not."
129 (case ch
67cb6748
MW
130 (#.(loop for i below char-code-limit
131 for ch = (code-char i)
132 unless (with-input-from-string (in (string ch))
133 (peek-char t in nil))
134 collect ch)
135 t)
861345b4 136 (t nil)))
137
d6caa73b
MW
138(defmacro defconstant* (name value &key doc test)
139 "Define a constant, like `defconstant'. The TEST is an equality test used
140 to decide whether to override the current definition, if any."
141 (let ((temp (gensym)))
142 `(eval-when (:compile-toplevel :load-toplevel :execute)
143 (let ((,temp ,value))
144 (unless (and (boundp ',name)
145 (funcall ,(or test ''eql) (symbol-value ',name) ,temp))
146 (defconstant ,name ,value ,@(and doc (list doc))))
147 ',name))))
148
861345b4 149(declaim (ftype (function nil ()) slot-unitialized))
150(defun slot-uninitialized ()
151 "A function which signals an error. Can be used as an initializer form in
0ff9df03 152 structure definitions without doom ensuing."
861345b4 153 (error "No initializer for slot."))
154
e2a3c923 155(compile-time-defun parse-body (body &key (allow-docstring-p t))
9d3ccec7 156 "Given a BODY (a list of forms), parses it into three sections: a
0ff9df03
MW
157 docstring, a list of declarations (forms beginning with the symbol
158 `declare') and the body forms. The result is returned as three lists
159 (even the docstring), suitable for interpolation into a backquoted list
e2a3c923
MW
160 using `@,'. If ALLOW-DOCSTRING-P is nil, docstrings aren't allowed at
161 all."
162 (let ((doc nil) (decls nil))
163 (do ((forms body (cdr forms))) (nil)
164 (let ((form (and forms (car forms))))
165 (cond ((and allow-docstring-p (not doc) (stringp form) (cdr forms))
166 (setf doc form))
167 ((and (consp form)
168 (eq (car form) 'declare))
169 (setf decls (append decls (cdr form))))
170 (t (return (values (and doc (list doc))
171 (and decls (list (cons 'declare decls)))
172 forms))))))))
9d3ccec7 173
8f801ae8
MW
174(defmacro with-parsed-body
175 ((bodyvar declvar &optional (docvar (gensym) docp)) form &body body)
176 "Parse FORM into a body, declarations and (maybe) a docstring; bind BODYVAR
177 to the body, DECLVAR to the declarations, and DOCVAR to (a list
178 containing) the docstring, and evaluate BODY."
179 `(multiple-value-bind
180 (,docvar ,declvar ,bodyvar)
181 (parse-body ,form :allow-docstring-p ,docp)
182 ,@(if docp nil `((declare (ignore ,docvar))))
183 ,@body))
184
7dcf04ad
MW
185#-cmu
186(progn
187 (declaim (inline fixnump))
188 (defun fixnump (object)
189 "Answer non-nil if OBJECT is a fixnum, or nil if it isn't."
190 (typep object 'fixnum)))
191
02866e07
MW
192;;;--------------------------------------------------------------------------
193;;; Generating symbols.
194
861345b4 195(defmacro with-gensyms (syms &body body)
196 "Everyone's favourite macro helper."
197 `(let (,@(mapcar (lambda (sym) `(,sym (gensym ,(symbol-name sym))))
4da88bb9 198 (listify syms)))
861345b4 199 ,@body))
200
201(defmacro let*/gensyms (binds &body body)
202 "A macro helper. BINDS is a list of binding pairs (VAR VALUE), where VALUE
0ff9df03
MW
203 defaults to VAR. The result is that BODY is evaluated in a context where
204 each VAR is bound to a gensym, and in the final expansion, each of those
205 gensyms will be bound to the corresponding VALUE."
861345b4 206 (labels ((more (binds)
4da88bb9
MW
207 (let ((tmp (gensym "TMP")) (bind (car binds)))
208 `((let ((,tmp ,(cadr bind))
209 (,(car bind) (gensym ,(symbol-name (car bind)))))
210 `(let ((,,(car bind) ,,tmp))
211 ,,@(if (cdr binds)
212 (more (cdr binds))
213 body)))))))
861345b4 214 (if (null binds)
4da88bb9
MW
215 `(progn ,@body)
216 (car (more (mapcar #'pairify (listify binds)))))))
861345b4 217
02866e07 218;;;--------------------------------------------------------------------------
f2d46aaa
MW
219;;; Some simple yet useful control structures.
220
221(defmacro nlet (name binds &body body)
222 "Scheme's named let."
223 (multiple-value-bind (vars vals)
224 (loop for bind in binds
225 for (var val) = (pairify bind nil)
226 collect var into vars
227 collect val into vals
228 finally (return (values vars vals)))
229 `(labels ((,name ,vars
4da88bb9 230 ,@body))
f2d46aaa
MW
231 (,name ,@vals))))
232
233(defmacro while (cond &body body)
234 "If COND is false, evaluate to nil; otherwise evaluate BODY and try again."
38ccae7f
MW
235 `(loop (unless ,cond (return)) (progn ,@body)))
236
237(defmacro until (cond &body body)
238 "If COND is true, evaluate to nil; otherwise evaluate BODY and try again."
239 `(loop (when ,cond (return)) (progn ,@body)))
f2d46aaa 240
560e1186
MW
241(compile-time-defun do-case2-like (kind vform clauses)
242 "Helper function for `case2' and `ecase2'."
243 (with-gensyms (scrutinee argument)
244 `(multiple-value-bind (,scrutinee ,argument) ,vform
245 (declare (ignorable ,argument))
246 (,kind ,scrutinee
247 ,@(mapcar (lambda (clause)
248 (destructuring-bind
b3bc3745 249 (cases (&optional varx vary) &rest forms)
560e1186
MW
250 clause
251 `(,cases
b3bc3745
MW
252 ,@(if varx
253 (list `(let ((,(or vary varx) ,argument)
254 ,@(and vary
255 `((,varx ,scrutinee))))
4da88bb9 256 ,@forms))
560e1186
MW
257 forms))))
258 clauses)))))
259
260(defmacro case2 (vform &body clauses)
261 "VFORM is a form which evaluates to two values, SCRUTINEE and ARGUMENT.
b3bc3745
MW
262 The CLAUSES have the form (CASES ([[SCRUVAR] ARGVAR]) FORMS...), where a
263 standard `case' clause has the form (CASES FORMS...). The `case2' form
264 evaluates the VFORM, and compares the SCRUTINEE to the various CASES, in
265 order, just like `case'. If there is a match, then the corresponding
266 FORMs are evaluated with ARGVAR bound to the ARGUMENT and SCRUVAR bound to
267 the SCRUTINEE (where specified). Note the bizarre defaulting behaviour:
268 ARGVAR is less optional than SCRUVAR."
560e1186
MW
269 (do-case2-like 'case vform clauses))
270
271(defmacro ecase2 (vform &body clauses)
272 "Like `case2', but signals an error if no clause matches the SCRUTINEE."
273 (do-case2-like 'ecase vform clauses))
274
2af61873
MW
275(defmacro setf-default (&rest specs &environment env)
276 "Like setf, but only sets places which are currently nil.
277
278 The arguments are an alternating list of PLACEs and DEFAULTs. If a PLACE
279 is nil, the DEFAULT is evaluated and stored in the PLACE; otherwise the
280 default is /not/ stored. The result is the (new) value of the last
281 PLACE."
282 (labels ((doit (specs)
283 (cond ((null specs) nil)
284 ((null (cdr specs))
285 (error "Odd number of arguments for SETF-DEFAULT."))
286 (t
287 (let ((place (car specs))
288 (default (cadr specs))
289 (rest (cddr specs)))
290 (multiple-value-bind
291 (vars vals store-vals writer reader)
292 (get-setf-expansion place env)
293 `(let* ,(mapcar #'list vars vals)
294 (or ,reader
295 (multiple-value-bind ,store-vals ,default
296 ,writer))
297 ,@(and rest (list (doit rest))))))))))
298 (doit specs)))
299
f2d46aaa 300;;;--------------------------------------------------------------------------
ea87c989 301;;; Capturing places as symbols.
02866e07 302
861345b4 303(defmacro %place-ref (getform setform newtmp)
304 "Grim helper macro for with-places."
305 (declare (ignore setform newtmp))
306 getform)
02866e07 307
861345b4 308(define-setf-expander %place-ref (getform setform newtmp)
309 "Grim helper macro for with-places."
310 (values nil nil newtmp setform getform))
02866e07 311
171bb403
MW
312(defmacro with-places (clauses &body body &environment env)
313 "Define symbols which refer to `setf'-able places.
314
315 The syntax is similar to `let'. The CLAUSES are a list of (NAME PLACE)
316 pairs. Each NAME is defined as a symbol-macro referring to the
317 corresponding PLACE: a mention of the NAME within the BODY forms extracts
318 the current value(s) of the PLACE, while a `setf' (or `setq', because
319 symbol macros are strange like that) of a NAME updates the value(s) in the
320 PLACE. The returned values are those of the BODY, evaluated as an
321 implicit `progn'."
322
323 (let ((temp-binds nil)
324 (macro-binds nil))
325 (dolist (clause clauses)
326 (destructuring-bind (name place) clause
327 (multiple-value-bind (valtmps valforms newtmps setform getform)
328 (get-setf-expansion place env)
329 (setf temp-binds
330 (nconc (nreverse (mapcar #'list valtmps valforms))
331 temp-binds))
332 (push `(,name (%place-ref ,getform ,setform ,newtmps))
333 macro-binds))))
334 `(let (,@(nreverse temp-binds))
335 (symbol-macrolet (,@(nreverse macro-binds))
336 ,@body))))
337
338(defmacro with-places/gensyms (clauses &body body)
339 "A kind of a cross between `with-places' and `let*/gensyms'.
340
341 This is a hairy helper for writing `setf'-like macros. The CLAUSES are a
342 list of (NAME [PLACE]) pairs, where the PLACE defaults to NAME, and a
343 bare NAME may be written in place of the singleton list (NAME). The
344 PLACEs are evaluated.
345
346 The BODY forms are evaluated as an implicit `progn', with each NAME bound
347 to a gensym, to produce a Lisp form, called the `kernel'. The result of
348 the `with-places/gensyms' macro is then itself a Lisp form, called the
349 `result'.
350
351 The effect of evaluating the `result' form is to evaluate the `kernel'
352 form with each of the gensyms stands for the value(s) stored in the
353 corresponding PLACE; a `setf' (or `setq') of one of the gensyms updates
354 the value(s) in the corresponding PLACE. The values returned by the
355 `result' form are the values returned by the `kernel'."
356
357 (let* ((clauses (mapcar #'pairify clauses))
358 (names (mapcar #'car clauses))
359 (places (mapcar #'cadr clauses))
360 (gensyms (mapcar (lambda (name) (gensym (symbol-name name)))
361 names)))
362 ``(with-places (,,@(mapcar (lambda (gensym place)
363 ``(,',gensym ,,place))
364 gensyms places))
365 ,(let (,@(mapcar (lambda (name gensym)
366 `(,name ',gensym))
367 names gensyms))
368 ,@body))))
861345b4 369
02866e07
MW
370;;;--------------------------------------------------------------------------
371;;; Update-in-place macros built using with-places.
372
171bb403 373(defmacro update-place (op place &rest args)
53ccd042 374 "Update PLACE with (OP PLACE . ARGS), returning the new value."
171bb403 375 (with-places/gensyms (place)
53ccd042 376 `(setf ,place (,op ,place ,@args))))
02866e07 377
171bb403 378(defmacro update-place-after (op place &rest args)
53ccd042 379 "Update PLACE with (OP PLACE . ARGS), returning the old value."
171bb403 380 (with-places/gensyms (place)
e979e568
MW
381 (with-gensyms (x)
382 `(let ((,x ,place))
53ccd042 383 (setf ,place (,op ,x ,@args))
02866e07
MW
384 ,x))))
385
e979e568
MW
386(defmacro incf-after (place &optional (by 1))
387 "Increment PLACE by BY, returning the old value."
388 `(update-place-after + ,place ,by))
02866e07 389
e979e568
MW
390(defmacro decf-after (place &optional (by 1))
391 "Decrement PLACE by BY, returning the old value."
392 `(update-place-after - ,place ,by))
393
02866e07
MW
394;;;--------------------------------------------------------------------------
395;;; Locatives.
e979e568 396
861345b4 397(defstruct (loc (:predicate locp) (:constructor make-loc (reader writer)))
398 "Locative data type. See `locf' and `ref'."
399 (reader (slot-uninitialized) :type function)
400 (writer (slot-uninitialized) :type function))
02866e07 401
861345b4 402(defmacro locf (place &environment env)
403 "Slightly cheesy locatives. (locf PLACE) returns an object which, using
0ff9df03
MW
404 the `ref' function, can be used to read or set the value of PLACE. It's
405 cheesy because it uses closures rather than actually taking the address of
406 something. Also, unlike Zetalisp, we don't overload `car' to do our dirty
407 work."
861345b4 408 (multiple-value-bind
409 (valtmps valforms newtmps setform getform)
410 (get-setf-expansion place env)
411 `(let* (,@(mapcar #'list valtmps valforms))
412 (make-loc (lambda () ,getform)
4da88bb9 413 (lambda (,@newtmps) ,setform)))))
02866e07 414
861345b4 415(declaim (inline loc (setf loc)))
02866e07 416
861345b4 417(defun ref (loc)
418 "Fetch the value referred to by a locative."
419 (funcall (loc-reader loc)))
02866e07 420
861345b4 421(defun (setf ref) (new loc)
422 "Store a new value in the place referred to by a locative."
423 (funcall (loc-writer loc) new))
02866e07 424
861345b4 425(defmacro with-locatives (locs &body body)
426 "LOCS is a list of items of the form (SYM [LOC-EXPR]), where SYM is a
0ff9df03
MW
427 symbol and LOC-EXPR evaluates to a locative. If LOC-EXPR is omitted, it
428 defaults to SYM. As an abbreviation for a common case, LOCS may be a
429 symbol instead of a list. The BODY is evaluated in an environment where
430 each SYM is a symbol macro which expands to (ref LOC-EXPR) -- or, in fact,
431 something similar which doesn't break if LOC-EXPR has side-effects. Thus,
432 references, including `setf' forms, fetch or modify the thing referred to
433 by the LOC-EXPR. Useful for covering over where something uses a
434 locative."
861345b4 435 (setf locs (mapcar #'pairify (listify locs)))
436 (let ((tt (mapcar (lambda (l) (declare (ignore l)) (gensym)) locs))
437 (ll (mapcar #'cadr locs))
438 (ss (mapcar #'car locs)))
439 `(let (,@(mapcar (lambda (tmp loc) `(,tmp ,loc)) tt ll))
440 (symbol-macrolet (,@(mapcar (lambda (sym tmp)
441 `(,sym (ref ,tmp))) ss tt))
442 ,@body))))
443
444;;;----- That's all, folks --------------------------------------------------