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