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