e87c51191ab1e155c07758839b8b1c9ba26c7efc
[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 #:until #: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 (unless ,cond (return)) (progn ,@body)))
193
194 (defmacro until (cond &body body)
195 "If COND is true, evaluate to nil; otherwise evaluate BODY and try again."
196 `(loop (when ,cond (return)) (progn ,@body)))
197
198 (compile-time-defun do-case2-like (kind vform clauses)
199 "Helper function for `case2' and `ecase2'."
200 (with-gensyms (scrutinee argument)
201 `(multiple-value-bind (,scrutinee ,argument) ,vform
202 (declare (ignorable ,argument))
203 (,kind ,scrutinee
204 ,@(mapcar (lambda (clause)
205 (destructuring-bind
206 (cases (&optional varx vary) &rest forms)
207 clause
208 `(,cases
209 ,@(if varx
210 (list `(let ((,(or vary varx) ,argument)
211 ,@(and vary
212 `((,varx ,scrutinee))))
213 ,@forms))
214 forms))))
215 clauses)))))
216
217 (defmacro case2 (vform &body clauses)
218 "VFORM is a form which evaluates to two values, SCRUTINEE and ARGUMENT.
219 The CLAUSES have the form (CASES ([[SCRUVAR] ARGVAR]) FORMS...), where a
220 standard `case' clause has the form (CASES FORMS...). The `case2' form
221 evaluates the VFORM, and compares the SCRUTINEE to the various CASES, in
222 order, just like `case'. If there is a match, then the corresponding
223 FORMs are evaluated with ARGVAR bound to the ARGUMENT and SCRUVAR bound to
224 the SCRUTINEE (where specified). Note the bizarre defaulting behaviour:
225 ARGVAR is less optional than SCRUVAR."
226 (do-case2-like 'case vform clauses))
227
228 (defmacro ecase2 (vform &body clauses)
229 "Like `case2', but signals an error if no clause matches the SCRUTINEE."
230 (do-case2-like 'ecase vform clauses))
231
232 ;;;--------------------------------------------------------------------------
233 ;;; with-places
234
235 (defmacro %place-ref (getform setform newtmp)
236 "Grim helper macro for with-places."
237 (declare (ignore setform newtmp))
238 getform)
239
240 (define-setf-expander %place-ref (getform setform newtmp)
241 "Grim helper macro for with-places."
242 (values nil nil newtmp setform getform))
243
244 (defmacro with-places ((&key environment) places &body body)
245 "A hairy helper, for writing setf-like macros. PLACES is a list of binding
246 pairs (VAR PLACE), where PLACE defaults to VAR. The result is that BODY
247 is evaluated in a context where each VAR is bound to a gensym, and in the
248 final expansion, each of those gensyms will be bound to a symbol-macro
249 capable of reading or setting the value of the corresponding PLACE."
250 (if (null places)
251 `(progn ,@body)
252 (let*/gensyms (environment)
253 (labels
254 ((more (places)
255 (let ((place (car places)))
256 (with-gensyms (tmp valtmps valforms
257 newtmps setform getform)
258 `((let ((,tmp ,(cadr place))
259 (,(car place)
260 (gensym ,(symbol-name (car place)))))
261 (multiple-value-bind
262 (,valtmps ,valforms
263 ,newtmps ,setform ,getform)
264 (get-setf-expansion ,tmp
265 ,environment)
266 (list 'let*
267 (mapcar #'list ,valtmps ,valforms)
268 `(symbol-macrolet ((,,(car place)
269 (%place-ref ,,getform
270 ,,setform
271 ,,newtmps)))
272 ,,@(if (cdr places)
273 (more (cdr places))
274 body))))))))))
275 (car (more (mapcar #'pairify (listify places))))))))
276
277 ;;;--------------------------------------------------------------------------
278 ;;; Update-in-place macros built using with-places.
279
280 (defmacro update-place (op place arg &environment env)
281 "Update PLACE with the value of OP PLACE ARG, returning the new value."
282 (with-places (:environment env) (place)
283 `(setf ,place (,op ,place ,arg))))
284
285 (defmacro update-place-after (op place arg &environment env)
286 "Update PLACE with the value of OP PLACE ARG, returning the old value."
287 (with-places (:environment env) (place)
288 (with-gensyms (x)
289 `(let ((,x ,place))
290 (setf ,place (,op ,x ,arg))
291 ,x))))
292
293 (defmacro incf-after (place &optional (by 1))
294 "Increment PLACE by BY, returning the old value."
295 `(update-place-after + ,place ,by))
296
297 (defmacro decf-after (place &optional (by 1))
298 "Decrement PLACE by BY, returning the old value."
299 `(update-place-after - ,place ,by))
300
301 ;;;--------------------------------------------------------------------------
302 ;;; Locatives.
303
304 (defstruct (loc (:predicate locp) (:constructor make-loc (reader writer)))
305 "Locative data type. See `locf' and `ref'."
306 (reader (slot-uninitialized) :type function)
307 (writer (slot-uninitialized) :type function))
308
309 (defmacro locf (place &environment env)
310 "Slightly cheesy locatives. (locf PLACE) returns an object which, using
311 the `ref' function, can be used to read or set the value of PLACE. It's
312 cheesy because it uses closures rather than actually taking the address of
313 something. Also, unlike Zetalisp, we don't overload `car' to do our dirty
314 work."
315 (multiple-value-bind
316 (valtmps valforms newtmps setform getform)
317 (get-setf-expansion place env)
318 `(let* (,@(mapcar #'list valtmps valforms))
319 (make-loc (lambda () ,getform)
320 (lambda (,@newtmps) ,setform)))))
321
322 (declaim (inline loc (setf loc)))
323
324 (defun ref (loc)
325 "Fetch the value referred to by a locative."
326 (funcall (loc-reader loc)))
327
328 (defun (setf ref) (new loc)
329 "Store a new value in the place referred to by a locative."
330 (funcall (loc-writer loc) new))
331
332 (defmacro with-locatives (locs &body body)
333 "LOCS is a list of items of the form (SYM [LOC-EXPR]), where SYM is a
334 symbol and LOC-EXPR evaluates to a locative. If LOC-EXPR is omitted, it
335 defaults to SYM. As an abbreviation for a common case, LOCS may be a
336 symbol instead of a list. The BODY is evaluated in an environment where
337 each SYM is a symbol macro which expands to (ref LOC-EXPR) -- or, in fact,
338 something similar which doesn't break if LOC-EXPR has side-effects. Thus,
339 references, including `setf' forms, fetch or modify the thing referred to
340 by the LOC-EXPR. Useful for covering over where something uses a
341 locative."
342 (setf locs (mapcar #'pairify (listify locs)))
343 (let ((tt (mapcar (lambda (l) (declare (ignore l)) (gensym)) locs))
344 (ll (mapcar #'cadr locs))
345 (ss (mapcar #'car locs)))
346 `(let (,@(mapcar (lambda (tmp loc) `(,tmp ,loc)) tt ll))
347 (symbol-macrolet (,@(mapcar (lambda (sym tmp)
348 `(,sym (ref ,tmp))) ss tt))
349 ,@body))))
350
351 ;;;----- That's all, folks --------------------------------------------------